Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
400
def get_moderation(request): with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute() moderations = [x[0] for x in cursor.fetchall()] return moderations
Return the list of publications that need moderation.
401
def _change_precision(self, val, base=0): if not isinstance(val, int): raise TypeError() val = round(abs(val)) val = (lambda num: base if is_num(num) else num)(val) return val
Check and normalise the value of precision (must be positive integer). Args: val (INT): must be positive integer base (INT): Description Returns: VAL (INT): Description
402
def _add_file(self, key, path): filename = os.path.basename(path) base, ext = os.path.splitext(filename) if os.path.exists(self.file_path(filename)): with tempfile.NamedTemporaryFile( dir=self.path, prefix=base, suffix=ext) as tf: filename...
Copy a file into the reference package.
403
def Open(self): self.h_process = kernel32.OpenProcess( PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, 0, self.pid) if not self.h_process: raise process_error.ProcessError( "Failed to open process (pid %d)." % self.pid) if self.Is64bit(): si = self.GetNativeSystemInfo() ...
Opens the process for reading.
404
def _parse_fields_http(self, *args, **kwargs): from warnings import warn warn( ) return self.parse_fields_http(*args, **kwargs)
Deprecated. This will be removed in a future release.
405
def enable_pretty_logging(options: Any = None, logger: logging.Logger = None) -> None: if options is None: import tornado.options options = tornado.options.options if options.logging is None or options.logging.lower() == "none": return if logger is None: logger = loggin...
Turns on formatted logging output as configured. This is called automatically by `tornado.options.parse_command_line` and `tornado.options.parse_config_file`.
406
def interleave(*arrays,**kwargs): abcd@ anum = arrays.__len__() rslt = [] length = arrays[0].__len__() for j in range(0,length): for i in range(0,anum): array = arrays[i] rslt.append(array[j]) return(rslt)
arr1 = [1,2,3,4] arr2 = ['a','b','c','d'] arr3 = ['@','#','%','*'] interleave(arr1,arr2,arr3)
407
def add_or_update_records(cls, tables: I2B2Tables, records: List["ObservationFact"]) -> Tuple[int, int]: return cls._add_or_update_records(tables.crc_connection, tables.observation_fact, records)
Add or update the observation_fact table as needed to reflect the contents of records :param tables: i2b2 sql connection :param records: records to apply :return: number of records added / modified
408
def get(self, remote_file, local_file): sftp = self.get_sftp() try: sftp.get(remote_file, local_file) except Exception as e: logger.error() logger.error( % (remote_file, local_file)) logger.error(e)
下载文件 :param remote_file: :param local_file: :return:
409
def com_google_fonts_check_family_equal_font_versions(ttFonts): all_detected_versions = [] fontfile_versions = {} for ttFont in ttFonts: v = ttFont[].fontRevision fontfile_versions[ttFont] = v if v not in all_detected_versions: all_detected_versions.append(v) if len(all_detected_versions) ...
Make sure all font files have the same version value.
410
def grow(self, *args): if len(args) == 1: return Region.grow(self.x, self.y, args[0], args[0]) elif len(args) == 2: return Region(self.x, self.y, args[0], args[1]) elif len(args) == 4: return Region.create(self, *args) else: raise ...
Creates a region around the given point Valid arguments: * ``grow(wh)`` - Creates a region centered on this point with a width and height of ``wh``. * ``grow(w, h)`` - Creates a region centered on this point with a width of ``w`` and height of ``h``. * ``grow(Region.CREATE_X_DIRECTION...
411
def locate(pattern, root=os.curdir): for path, dummy, files in os.walk(os.path.abspath(root)): for filename in fnmatch.filter(files, pattern): yield os.path.join(path, filename)
Locate all files matching supplied filename pattern recursively.
412
def _create_checkable_action(self, text, conf_name, editorstack_method): def toogle(checked): self.switch_to_plugin() self._toggle_checkable_action(checked, editorstack_method, conf_name) action = create_action(self, text, ...
Helper function to create a checkable action. Args: text (str): Text to be displayed in the action. conf_name (str): configuration setting associated with the action editorstack_method (str): name of EditorStack class that will be used to update the cha...
413
def start(self): cert_path = os.path.join(self.work_dir, ) public_keys_dir = os.path.join(cert_path, ) private_keys_dir = os.path.join(cert_path, ) client_secret_file = os.path.join(private_keys_dir, "client.key") client_public, client_secret = zmq.auth.load_certificate...
Starts services.
414
def cast_pars_dict(pars_dict): o = {} for pname, pdict in pars_dict.items(): o[pname] = {} for k, v in pdict.items(): if k == : o[pname][k] = bool(int(v)) elif k == : o[pname][k] = v else: o[pname][k] =...
Cast the bool and float elements of a parameters dict to the appropriate python types.
415
def parse_na(txt: str) -> (MetarData, Units): units = Units(**NA_UNITS) clean = core.sanitize_report_string(txt) wxresp = {: txt, : clean} wxdata, wxresp[] = core.get_remarks(clean) wxdata, wxresp[], _ = core.sanitize_report_list(wxdata) wxdata, wxresp[], wxresp[] = core.get_station_and...
Parser for the North American METAR variant
416
def multiply_slow(x, y, prim=0x11b): def cl_mult(x,y): z = 0 i = 0 while (y>>i) > 0: if y & (1<<i): z ^= x<<i i += 1 return z def bit_length(n): b...
Another equivalent (but even slower) way to compute multiplication in Galois Fields without using a precomputed look-up table. This is the form you will most often see in academic literature, by using the standard carry-less multiplication + modular reduction using an irreducible prime polynomial.
417
def start_receive(self, fd, data=None): self._rfds[fd] = (data or fd, self._generation) self._update(fd)
Cause :meth:`poll` to yield `data` when `fd` is readable.
418
def measure_old_norse_syllable(syllable: list) -> Union[Length, None]: index = 0 while index < len(syllable) and not isinstance(syllable[index], Vowel): index += 1 if index == len(syllable): return None else: long_vowel_number = 0 short_vowel_number = 0 gemin...
Old Norse syllables are considered as: - short if - long if - overlong if >>> measure_old_norse_syllable([m, a.lengthen(), l]).name 'long' >>> measure_old_norse_syllable([a, l]).name 'short' >>> measure_old_norse_syllable([s, t, ee, r, k, r]).name 'long' >>> measure_old_norse...
419
def _create_hidden_port(self, context, network_id, device_id, fixed_ips, port_type=DEVICE_OWNER_ROUTER_INTF): port = {: { : , : network_id, : ATTR_NOT_SPECIFIED, : fixed_ips, : device_id, : port_type, ...
Creates port used specially for HA purposes.
420
def polygen(*coefficients): if not coefficients: return lambda i: 0 else: c0 = coefficients[0] coefficients = coefficients[1:] def _(i): v = c0 for c in coefficients: v += c*i i *= i return v ...
Polynomial generating function
421
def stopping_function(results, args=None, rstate=None, M=None, return_vals=False): if args is None: args = dict({}) if rstate is None: rstate = np.random if M is None: M = map pfrac = args.get(, 1.0) if not 0. <= pfrac <= 1.: rai...
The default stopping function utilized by :class:`DynamicSampler`. Zipped parameters are passed to the function via :data:`args`. Assigns the run a stopping value based on a weighted average of the stopping values for the posterior and evidence:: stop = pfrac * stop_post + (1.- pfrac) * stop_evid ...
422
def _rewind(self): DFReader._rewind(self) self.line = 0 while self.line < len(self.lines): if self.lines[self.line].startswith("FMT, "): break self.line += 1
rewind to start of log
423
def convertforoutput(self,outputfile): super(CharEncodingConverter,self).convertforoutput(outputfile) return withheaders( flask.make_response( ( line.encode(self.charset) for line in outputfile ) ) , + self.charset)
Convert from one of the source formats into target format. Relevant if converters are used in OutputTemplates. Outputfile is a CLAMOutputFile instance.
424
def set_port_profile_created(self, vlan_id, profile_name, device_id): with self.session.begin(subtransactions=True): port_profile = self.session.query( ucsm_model.PortProfile).filter_by( vlan_id=vlan_id, profile_id=profile_name, device...
Sets created_on_ucs flag to True.
425
def get_learning_objective_ids_metadata(self): metadata = dict(self._learning_objective_ids_metadata) metadata.update({: self.my_osid_object_form._my_map[][0]}) return Metadata(**metadata)
get the metadata for learning objective
426
def remove_col_label(self, event=None, col=None): if event: col = event.GetCol() if not col: return label = self.grid.GetColLabelValue(col) if in label: label = label.strip() elif in label: label = label.strip() i...
check to see if column is required if it is not, delete it from grid
427
def preorder(self): if not self: return yield self if self.left: for x in self.left.preorder(): yield x if self.right: for x in self.right.preorder(): yield x
iterator for nodes: root, left, right
428
def _get_system_volume(vm_): disk_size = get_size(vm_)[] if in vm_: disk_size = vm_[] volume = Volume( name=.format(vm_[]), size=disk_size, disk_type=get_disk_type(vm_) ) if in vm_: image_password = vm_[] volume.image_password = ima...
Construct VM system volume list from cloud profile config
429
def TRUE(classical_reg): warn("`TRUE a` has been deprecated. Use `MOVE a 1` instead.") if isinstance(classical_reg, int): classical_reg = Addr(classical_reg) return MOVE(classical_reg, 1)
Produce a TRUE instruction. :param classical_reg: A classical register to modify. :return: An instruction object representing the equivalent MOVE.
430
def __get_strut_token(self): try: response = self.lc.session.get() soup = BeautifulSoup(response.text, "html5lib") strut_tag = None strut_token_name = soup.find(, {: }) if strut_token_na...
Move the staged loan notes to the order stage and get the struts token from the place order HTML. The order will not be placed until calling _confirm_order() Returns ------- dict A dict with the token name and value
431
def script(self, s): try: script = self._network.script.compile(s) script_info = self._network.contract.info_for_script(script) return Contract(script_info, self._network) except Exception: return None
Parse a script by compiling it. Return a :class:`Contract` or None.
432
def key_wait(): while 1: for event in get(): if event.type == : return event if event.type == : return KeyDown(, , True, False, True, False, False) _time.sleep(.001)
Waits until the user presses a key. Then returns a :any:`KeyDown` event. Key events will repeat if held down. A click to close the window will be converted into an Alt+F4 KeyDown event. Returns: tdl.event.KeyDown: The pressed key.
433
def capture(board): game = Game() v = (0, 0) stub_actor = base.Actor(, v, v, v, v, v, v, v, v, v) root = base.State(board, stub_actor, stub_actor, turn=1, actions_remaining=1) solution_node = None for eot in game.all_ends_of_turn(root): if eot.is_mana_...
Try to solve the board described by board_string. Return sequence of summaries that describe how to get to the solution.
434
def _read_descriptions(self, password): descfiles = [FRITZ_IGD_DESC_FILE] if password: descfiles.append(FRITZ_TR64_DESC_FILE) for descfile in descfiles: parser = FritzDescParser(self.address, self.port, descfile) if not self.modelname: ...
Read and evaluate the igddesc.xml file and the tr64desc.xml file if a password is given.
435
def getlanguage(self, language=None, windowsversion=None): if not language: language = self.language if language in (None, "", "*", "neutral"): return (LANGUAGE_NEUTRAL_NT5, LANGUAGE_NEUTRAL_NT6)[(windowsversion or ...
Get and return the manifest's language as string. Can be either language-culture e.g. 'en-us' or a string indicating language neutrality, e.g. 'x-ww' on Windows XP or 'none' on Vista and later.
436
def _get_account_number(self, token, uuid): data = {"accessToken": token, "uuid": uuid} try: raw_res = yield from self._session.post(ACCOUNT_URL, data=data, ...
Get fido account number.
437
def call(method, *args, **kwargs): kwargs = clean_kwargs(**kwargs) return getattr(pyeapi_device[], method)(*args, **kwargs)
Calls an arbitrary pyeapi method.
438
def run_band_structure(self, paths, with_eigenvectors=False, with_group_velocities=False, is_band_connection=False, path_connections=None, labels=None, ...
Run phonon band structure calculation. Parameters ---------- paths : List of array_like Sets of qpoints that can be passed to phonopy.set_band_structure(). Numbers of qpoints can be different. shape of each array_like : (qpoints, 3) with_eigenvectors ...
439
def save_features(self, train_features, test_features, feature_names, feature_list_id): self.save_feature_names(feature_names, feature_list_id) self.save_feature_list(train_features, , feature_list_id) self.save_feature_list(test_features, , feature_list_id)
Save features for the training and test sets to disk, along with their metadata. Args: train_features: A NumPy array of features for the training set. test_features: A NumPy array of features for the test set. feature_names: A list containing the names of the feature columns...
440
def restart(self, container, instances=None, map_name=None, **kwargs): return self.run_actions(, container, instances=instances, map_name=map_name, **kwargs)
Restarts instances for a container configuration. :param container: Container name. :type container: unicode | str :param instances: Instance names to stop. If not specified, will restart all instances as specified in the configuration (or just one default instance). :type inst...
441
def _format_conditions_and_actions(self, raw_data): keys = raw_data.keys() formatted_set = {} return formatted_set
This function gets a set of actions and conditionswith the following format: {'action-0': 'repeat', 'action-1': 'repeat', 'analysisservice-0': '30cd952b0bb04a05ac27b70ada7feab2', 'analysisservice-1': '30cd952b0bb04a05ac27b70ada7feab2', 'and_or-0': 'and', ...
442
def parse_genemap2(lines): LOG.info("Parsing the omim genemap2") header = [] for i,line in enumerate(lines): line = line.rstrip() if line.startswith(): if i < 10: if line.startswith(): header = line[2:].split() continue ...
Parse the omim source file called genemap2.txt Explanation of Phenotype field: Brackets, "[ ]", indicate "nondiseases," mainly genetic variations that lead to apparently abnormal laboratory test values. Braces, "{ }", indicate mutations that contribute to susceptibility to multifactorial dis...
443
def unicorn_edit(path, **kwargs): ctx = Context(**kwargs) ctx.timeout = None ctx.execute_action(, **{ : ctx.repo.create_secure_service(), : path, })
Edit Unicorn node interactively.
444
def _EvaluateExpressions(self, frame): return [self._FormatExpression(frame, expression) for expression in self._definition.get() or []]
Evaluates watched expressions into a string form. If expression evaluation fails, the error message is used as evaluated expression string. Args: frame: Python stack frame of breakpoint hit. Returns: Array of strings where each string corresponds to the breakpoint expression with th...
445
def runInactiveDeviceCleanup(self): yield self.deleteInactiveDevicesByQuota( self.__inactive_per_jid_max, self.__inactive_global_max ) yield self.deleteInactiveDevicesByAge(self.__inactive_max_age)
Runs both the deleteInactiveDevicesByAge and the deleteInactiveDevicesByQuota methods with the configuration that was set when calling create.
446
def unlink(self, request, uuid=None): service = self.get_object() service.unlink_descendants() self.perform_destroy(service) return Response(status=status.HTTP_204_NO_CONTENT)
Unlink all related resources, service project link and service itself.
447
def product(*arrays): arrays = [np.asarray(x) for x in arrays] shape = (len(x) for x in arrays) dtype = arrays[0].dtype ix = np.indices(shape) ix = ix.reshape(len(arrays), -1).T out = np.empty_like(ix, dtype=dtype) for n, _ in enumerate(arrays): out[:, n] = arrays[n][ix[:, n]...
Generate a cartesian product of input arrays. Parameters ---------- arrays : list of array-like 1-D arrays to form the cartesian product of. Returns ------- out : ndarray 2-D array of shape (M, len(arrays)) containing cartesian products formed of input arrays.
448
def _delete_unwanted_caracters(self, chain): try: chain = chain.decode(, ) except UnicodeEncodeError: pass except AttributeError: pass for char in self.illegal_macro_output_chars: chain = chain.replace(cha...
Remove not wanted char from chain unwanted char are illegal_macro_output_chars attribute :param chain: chain to remove char from :type chain: str :return: chain cleaned :rtype: str
449
def transform_txn_for_ledger(txn): txn_data = get_payload_data(txn) txn_data[AUDIT_TXN_LEDGERS_SIZE] = {int(k): v for k, v in txn_data[AUDIT_TXN_LEDGERS_SIZE].items()} txn_data[AUDIT_TXN_LEDGER_ROOT] = {int(k): v for k, v in txn_data[AUDIT_TXN_LEDGER_ROOT].items()} txn_data[AUDI...
Makes sure that we have integer as keys after possible deserialization from json :param txn: txn to be transformed :return: transformed txn
450
def paintEvent(self, event): super(XTextEdit, self).paintEvent(event) if self.document().isEmpty() and self.hint(): text = self.hint() rect = self.rect() rect.setX(4) rect.setY(4) alig...
Overloads the paint event to support rendering of hints if there are no items in the tree. :param event | <QPaintEvent>
451
def head(draw=True, show=True, max_shape=256): import ipyvolume as ipv from scipy.interpolate import interp1d colors = [[0.91, 0.7, 0.61, 0.0], [0.91, 0.7, 0.61, 80.0], [1.0, 1.0, 0.85, 82.0], [1.0, 1.0, 0.85, 256]] x = np.array([k[-1] for k in colors]) rgb = np.array([k[:3] for...
Show a volumetric rendering of a human male head.
452
def add_concept(self, concept_obj): if concept_obj is None: raise Exception("Concept object cannot be None") elif concept_obj in self.__concepts: raise Exception("Concept object is already inside") elif concept_obj.cidx in self.__concept_map: raise Ex...
Add a concept to current concept list
453
def delete(cls, resources, background=False, force=False): if not isinstance(resources, (list, tuple)): resources = [resources] ifaces = [] for item in resources: try: ip_ = cls.info(item) except UsageError: cls.error(...
Delete an ip by deleting the iface
454
def _weld_unary(array, weld_type, operation): if weld_type not in {WeldFloat(), WeldDouble()}: raise TypeError() obj_id, weld_obj = create_weld_object(array) weld_template = weld_obj.weld_code = weld_template.format(array=obj_id, type=weld_type, op=operation) return weld_obj
Apply operation on each element in the array. As mentioned by Weld, the operations follow the behavior of the equivalent C functions from math.h Parameters ---------- array : numpy.ndarray or WeldObject Data weld_type : WeldType Of the data operation : {'exp', 'log', 'sqrt', 's...
455
def add_datepart(df, fldname, drop=True, time=False, errors="raise"): fld = df[fldname] fld_dtype = fld.dtype if isinstance(fld_dtype, pd.core.dtypes.dtypes.DatetimeTZDtype): fld_dtype = np.datetime64 if not np.issubdtype(fld_dtype, np.datetime64): df[fldname] = fld = pd.to_dateti...
add_datepart converts a column of df from a datetime64 to many columns containing the information from the date. This applies changes inplace. Parameters: ----------- df: A pandas data frame. df gain several new columns. fldname: A string that is the name of the date column you wish to expand. ...
456
def h_v_t(header, key): if key not in header: key = key.title() if key not in header: raise ValueError("Unexpected header in response, missing: " + key + " headers:\n" + str(header)) return header[key]
get header value with title try to get key from header and consider case sensitive e.g. header['x-log-abc'] or header['X-Log-Abc'] :param header: :param key: :return:
457
def _proxy(self): if self._context is None: self._context = DocumentContext( self._version, service_sid=self._solution[], sid=self._solution[], ) return self._context
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: DocumentContext for this DocumentInstance :rtype: twilio.rest.preview.sync.service.document.DocumentContext
458
def printMe(self, selfKey, selfValue): text = .format(keyName=selfKey) if len(selfValue) == 0: return else: valueText = for element in selfValue: if singleOrPair(element) == : valueText += element.printMe(element...
Parse the single and its value and return the parsed str. Args: selfTag (str): The tag. Normally just ``self.tag`` selfValue (list): a list of value elements(single, subclasses, str, int). Normally just ``self.value`` Returns: str: A parsed text
459
def p_declare_list(p): if len(p) == 4: p[0] = [ast.Directive(p[1], p[3], lineno=p.lineno(1))] else: p[0] = p[1] + [ast.Directive(p[3], p[5], lineno=p.lineno(2))]
declare_list : STRING EQUALS static_scalar | declare_list COMMA STRING EQUALS static_scalar
460
def get_ssh_keys(sshdir): keys = Queue() for root, _, files in os.walk(os.path.abspath(sshdir)): if not files: continue for filename in files: fullname = os.path.join(root, filename) if (os.path.isfile(fullname) and fullname.endswith() or ...
Get SSH keys
461
def drop_layer(self, layer): if self._frozen: raise TypeError() for child in self._children.values(): child.drop_layer(layer) self._layers.remove(layer)
Removes the named layer and the value associated with it from the node. Parameters ---------- layer : str Name of the layer to drop. Raises ------ TypeError If the node is frozen KeyError If the named layer does not exist
462
def _check_not_in_finally(self, node, node_name, breaker_classes=()): if not self._tryfinallys: return _parent = node.parent _node = node while _parent and not isinstance(_parent, breaker_classes): if hasattr(_parent, "finalbody") and _n...
check that a node is not inside a finally clause of a try...finally statement. If we found before a try...finally bloc a parent which its type is in breaker_classes, we skip the whole check.
463
def remove_csv_from_json(d): logger_jsons.info("enter remove_csv_from_json") if "paleoData" in d: d = _remove_csv_from_section(d, "paleoData") if "chronData" in d: d = _remove_csv_from_section(d, "chronData") logger_jsons.info("exit remove_csv_from_json") return d
Remove all CSV data 'values' entries from paleoData table in the JSON structure. :param dict d: JSON data - old structure :return dict: Metadata dictionary without CSV values
464
def _check_filepath(changes): filename = None for change_ in changes: try: cmd, arg = change_.split(, 1) if cmd not in METHOD_MAP: error = .format(cmd) raise ValueError(error) method = METHOD_MAP[cmd] parts = salt.util...
Ensure all changes are fully qualified and affect only one file. This ensures that the diff output works and a state change is not incorrectly reported.
465
def tostring(self, inject): return inject(self, .join(document.tostring(inject) for document in self.documents))
Get the entire text content as str
466
def define_parser(self): point = Group(integer.setResultsName("x") + integer.setResultsName("y")) n_points = (integer.setResultsName("n") + OneOrMore(point).setResultsName("points")) n_bytes = Suppress(integer) + Suppress(minus) + \ ...
Defines xdot grammar. @see: http://graphviz.org/doc/info/output.html#d:xdot
467
def sort_dict_by_key(obj): sort_func = lambda x: x[0] return OrderedDict(sorted(obj.items(), key=sort_func))
Sort dict by its keys >>> sort_dict_by_key(dict(c=1, b=2, a=3, d=4)) OrderedDict([('a', 3), ('b', 2), ('c', 1), ('d', 4)])
468
def extract_args(self, data): args = [] data = data.strip() if in data: lhs, rhs = data.split(, 1) if lhs: args.extend(lhs.rstrip().split()) args.append(rhs) else: args.extend(data.split()) return tuple(args)
It extracts irc msg arguments.
469
def set_pin_retries(ctx, pw_attempts, admin_pin, force): controller = ctx.obj[] resets_pins = controller.version < (4, 0, 0) if resets_pins: click.echo( ) force or click.confirm(.format( *pw_attempts), abort=True, err=True) controller.set_pin_retries(*(pw_atte...
Manage pin-retries. Sets the number of attempts available before locking for each PIN. PW_ATTEMPTS should be three integer values corresponding to the number of attempts for the PIN, Reset Code, and Admin PIN, respectively.
470
def dt_weekofyear(x): import pandas as pd return pd.Series(x).dt.weekofyear.values
Returns the week ordinal of the year. :returns: an expression containing the week ordinal of the year, extracted from a datetime column. Example: >>> import vaex >>> import numpy as np >>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64) ...
471
def close(self): self._serial.write(b"@c") self._serial.read() self._serial.close()
Closes the connection to the serial port and ensure no pending operatoin are left
472
def launch_batch_workflow(self, batch_workflow): url = % { : self.base_url } try: r = self.gbdx_connection.post(url, json=batch_workflow) batch_workflow_id = r.json()[] return batch_workflow_id except TypeError as e: ...
Launches GBDX batch workflow. Args: batch_workflow (dict): Dictionary specifying batch workflow tasks. Returns: Batch Workflow id (str).
473
def first_consumed_mesh(self): for instruction in self.instructions: if instruction.consumes_meshes(): return instruction.first_consumed_mesh raise IndexError("{} consumes no meshes".format(self))
The first consumed mesh. :return: the first consumed mesh :rtype: knittingpattern.Mesh.Mesh :raises IndexError: if no mesh is consumed .. seealso:: :attr:`number_of_consumed_meshes`
474
def configure(self, options, conf): super(S3Logging, self).configure(options, conf) self.options = options
Get the options.
475
def detect_ts(df, max_anoms=0.10, direction=, alpha=0.05, only_last=None, threshold=None, e_value=False, longterm=False, piecewise_median_period_weeks=2, plot=False, y_log=False, xlabel = , ylabel = , title=None, verbose=False): if not isin...
Anomaly Detection Using Seasonal Hybrid ESD Test A technique for detecting anomalies in seasonal univariate time series where the input is a series of <timestamp, value> pairs. Args: x: Time series as a two column data frame where the first column consists of the timestamps and the second column c...
476
def total(self): if self._result_cache: return self._result_cache.total return self.all().total
Return the total number of records
477
def masked_local_attention_2d(q, k, v, query_shape=(8, 16), memory_flange=(8, 16), name=None): with tf.variable_scope( name, default_name="local_masked_self_at...
Strided block local self-attention. Each position in a query block can attend to all the generated queries in the query block, which are generated in raster scan, and positions that are generated to the left and top. The shapes are specified by query shape and memory flange. Note that if you're using this func...
478
def dataframe_setup(self): genesippr_dict = dict() try: sippr_matrix = pd.read_csv(os.path.join(self.reportpath, ), delimiter=, index_col=0).T.to_dict() except FileNotFoundError: sippr_matrix = dict() ...
Set-up a report to store the desired header: sanitized string combinations
479
def build_logits(data_ops, embed_layer, rnn_core, output_linear, name_prefix): embedded_input_seq = snt.BatchApply( embed_layer, name="input_embed_seq")(data_ops.sparse_obs) initial_rnn_state = nest.map_structure( lambda t: tf.get_local_variable( "{}/rnn_state/{}".format(name_prefi...
This is the core model logic. Unrolls a Bayesian RNN over the given sequence. Args: data_ops: A `sequence_data.SequenceDataOps` namedtuple. embed_layer: A `snt.Embed` instance. rnn_core: A `snt.RNNCore` instance. output_linear: A `snt.Linear` instance. name_prefix: A string to use to prefix lo...
480
def get_locations(self, locations, columns=None, **kwargs): indexes = [self._index[x] for x in locations] return self.get(indexes, columns, **kwargs)
For list of locations and list of columns return a DataFrame of the values. :param locations: list of index locations :param columns: list of column names :param kwargs: will pass along these parameters to the get() method :return: DataFrame
481
def distinct_letters(string_matrix: List[List[str]]) -> Set[str]: return set([letter for sentence in string_matrix for word in sentence for letter in word])
Diagnostic function :param string_matrix: a data matrix: a list wrapping a list of strings, with each sublist being a sentence. :return: >>> dl = distinct_letters([['the', 'quick', 'brown'],['how', 'now', 'cow']]) >>> sorted(dl) ['b', 'c', 'e', 'h', 'i', 'k', 'n', 'o', 'q', 'r', 't', 'u', 'w']
482
def batch_(self, rpc_calls): batch_data = [] for rpc_call in rpc_calls: AuthServiceProxy.__id_count += 1 m = rpc_call.pop(0) batch_data.append({"jsonrpc":"2.0", "method":m, "params":rpc_call, "id":AuthServiceProxy.__id_count}) postdata = json.dumps(b...
Batch RPC call. Pass array of arrays: [ [ "method", params... ], ... ] Returns array of results.
483
def new(cls, ns_path, script, campaign_dir, runner_type=, overwrite=False, optimized=True, check_repo=True): ns_path = os.path.abspath(ns_path) campaign_dir = os.path.abspath(campaign_dir) if Path(campaign_dir).exists() and not overwrite: ...
Create a new campaign from an ns-3 installation and a campaign directory. This method will create a DatabaseManager, which will install a database in the specified campaign_dir. If a database is already available at the ns_path described in the specified campaign_dir and its con...
484
def delete_floatingip(self, floatingip_id): ret = self.network_conn.delete_floatingip(floatingip_id) return ret if ret else True
Deletes the specified floatingip
485
def _emit_no_set_found(environment_name, product_name): sys.stdout.write(colorama.Fore.YELLOW + .format(environment_name, product_name) + colorama.Fore.RESET) sys.stdout.write() logger.warning( .f...
writes to std out and logs if no connection string is found for deployment :param environment_name: :param product_name: :return:
486
def radius_server_host_retries(self, **kwargs): config = ET.Element("config") radius_server = ET.SubElement(config, "radius-server", xmlns="urn:brocade.com:mgmt:brocade-aaa") host = ET.SubElement(radius_server, "host") hostname_key = ET.SubElement(host, "hostname") hostn...
Auto Generated Code
487
def get_wind_url(self): wind_direction = self.f_d.get(, None) if wind_direction is not None: rounded = int(5 * round(float(wind_direction)/5)) return WIND_ARROW_URL.format(rounded)
Get wind arrow url.
488
def execute(self): config.logger.debug() config.logger.debug(self.params ) if in self.params: self.params.pop(, None) if in self.params: self.params.pop(, None) create_result = config.sfdc_client.create_apex_checkpoint(self.params) if t...
self.params = { "ActionScriptType" : "None", "ExecutableEntityId" : "01pd0000001yXtYAAU", "IsDumpingHeap" : True, "Iteration" : 1, "Line" : 3, "ScopeId" : "005d00000...
489
def _complete_last_byte(self, packet): padded_size = self.get_size() padding_bytes = padded_size - len(packet) if padding_bytes > 0: packet += Pad(padding_bytes).pack() return packet
Pad until the packet length is a multiple of 8 (bytes).
490
def Division(left: vertex_constructor_param_types, right: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex: return Double(context.jvm_view().DivisionVertex, label, cast_to_double_vertex(left), cast_to_double_vertex(right))
Divides one vertex by another :param left: the vertex to be divided :param right: the vertex to divide
491
def _unparse_entry_record(self, entry): for attr_type in sorted(entry.keys()): for attr_value in entry[attr_type]: self._unparse_attr(attr_type, attr_value)
:type entry: Dict[string, List[string]] :param entry: Dictionary holding an entry
492
def example_load_data(self): self.x = constant([[0.7, 0.9]]) self.w1 = Variable(random_normal([2, 3], stddev=1, seed=1)) self.w2 = Variable(random_normal([3, 1], stddev=1, seed=1))
加载数据
493
def get_github_hostname_user_repo_from_url(url): parsed = parse.urlparse(url) if parsed.netloc == : host, sep, path = parsed.path.partition(":") if "@" in host: username, sep, host = host.partition("@") else: path = parsed.path[1:].rstrip() host = pa...
Return hostname, user and repository to fork from. :param url: The URL to parse :return: hostname, user, repository
494
def add_device_not_active_callback(self, callback): _LOGGER.debug(, callback) self._cb_device_not_active.append(callback)
Register callback to be invoked when a device is not responding.
495
def get_as_type_with_default(self, index, value_type, default_value): value = self[index] return TypeConverter.to_type_with_default(value_type, value, default_value)
Converts array element into a value defined by specied typecode. If conversion is not possible it returns default value. :param index: an index of element to get. :param value_type: the TypeCode that defined the type of the result :param default_value: the default value :retu...
496
def get_ip_prefixes_from_bird(filename): prefixes = [] with open(filename, ) as bird_conf: lines = bird_conf.read() for line in lines.splitlines(): line = line.strip() if valid_ip_prefix(line): prefixes.append(line) return prefixes
Build a list of IP prefixes found in Bird configuration. Arguments: filename (str): The absolute path of the Bird configuration file. Notes: It can only parse a file with the following format define ACAST_PS_ADVERTISE = [ 10.189.200.155/32, ...
497
def create_access_token_response(self, uri, http_method=, body=None, headers=None, credentials=None): resp_headers = {: } try: request = self._create_request(uri, http_method, body, headers) valid, processed_request = self.validate_ac...
Create an access token response, with a new request token if valid. :param uri: The full URI of the token request. :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. :param body: The request body as a string. :param headers: The request headers as a dict. :pa...
498
def chmod(self, mode): self.sftp._log(DEBUG, % (hexlify(self.handle), mode)) attr = SFTPAttributes() attr.st_mode = mode self.sftp._request(CMD_FSETSTAT, self.handle, attr)
Change the mode (permissions) of this file. The permissions are unix-style and identical to those used by python's C{os.chmod} function. @param mode: new permissions @type mode: int
499
def compute_all_sg_permutations(positions, rotations, translations, lattice, symprec): out = [] for (sym, t) in zip(rotations, translations): rotated_positions ...
Compute a permutation for every space group operation. See 'compute_permutation_for_rotation' for more info. Output has shape (num_rot, num_pos)