Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
6,200
def memory_usage(self): data = super(Field, self).memory_usage() values = 0 for value in self.field_values: values += value.memory_usage() data[] = values return data
Get the combined memory usage of the field data and field values.
6,201
def _query_nsot(url, headers, device=None): url = urlparse.urljoin(url, ) ret = {} if not device: query = salt.utils.http.query(url, header_dict=headers, decode=True) else: url = urlparse.urljoin(url, device) query = salt.utils.http.query(url, header_dict=headers, ...
if a device is given, query nsot for that specific device, otherwise return all devices :param url: str :param headers: dict :param device: None or str :return:
6,202
def error_perturbation(C, S): r if issparse(C): warnings.warn("Error-perturbation will be dense for sparse input") C = C.toarray() return dense.covariance.error_perturbation(C, S)
r"""Error perturbation for given sensitivity matrix. Parameters ---------- C : (M, M) ndarray Count matrix S : (M, M) ndarray or (K, M, M) ndarray Sensitivity matrix (for scalar observable) or sensitivity tensor for vector observable Returns ------- X : float or (K,...
6,203
async def disable(self, reason=None): params = {"enable": True, "reason": reason} response = await self._api.put("/v1/agent/maintenance", params=params) return response.status == 200
Enters maintenance mode Parameters: reason (str): Reason of disabling Returns: bool: ``True`` on success
6,204
def get_cookies_for_class(session, class_name, cookies_file=None, username=None, password=None): if cookies_file: cookies = find_cookies_for_class(cookies_file, class_name) session.cookies.update(cookies) logg...
Get the cookies for the given class. We do not validate the cookies if they are loaded from a cookies file because this is intended for debugging purposes or if the coursera authentication process has changed.
6,205
def register_chooser(self, chooser, **kwargs): if not issubclass(chooser, Chooser): return self.register_simple_chooser(chooser, **kwargs) self.choosers[chooser.model] = chooser(**kwargs) return chooser
Adds a model chooser definition to the registry.
6,206
def tz_convert(dt, to_tz, from_tz=None) -> str: logger = logs.get_logger(tz_convert, level=) f_tz, t_tz = get_tz(from_tz), get_tz(to_tz) from_dt = pd.Timestamp(str(dt), tz=f_tz) logger.debug(f) return str(pd.Timestamp(str(from_dt), tz=t_tz))
Convert to tz Args: dt: date time to_tz: to tz from_tz: from tz - will be ignored if tz from dt is given Returns: str: date & time Examples: >>> dt_1 = pd.Timestamp('2018-09-10 16:00', tz='Asia/Hong_Kong') >>> tz_convert(dt_1, to_tz='NY') '2018-09-1...
6,207
def _set_size_code(self): if not self._op.startswith(self.SIZE): self._size_code = None return if len(self._op) == len(self.SIZE): self._size_code = self.SZ_EQ else: suffix = self._op[len(self.SIZE):] self._size_code = self.SZ...
Set the code for a size operation.
6,208
def get(self, path): key = tuple(map(id, path)) item = self._cache.get(key, None) if item is None: logger.debug("Transform cache miss: %s", key) item = [0, self._create(path)] self._cache[key] = item item[0] = 0 ...
Get a transform from the cache that maps along *path*, which must be a list of Transforms to apply in reverse order (last transform is applied first). Accessed items have their age reset to 0.
6,209
def doMove(self, orgresource, dstresource, dummy = 56184, stresource = , bShareFireCopy = ): url = nurls[] data = {: self.user_id, : self.useridx, : dummy, : orgresource, : dstresource, : overwrite, ...
DoMove Args: dummy: ??? orgresource: Path for a file which you want to move dstresource: Destination path bShareFireCopy: ??? Returns: True: Move success False: Move failed
6,210
def home_wins(self): try: wins, losses = re.findall(r, self._home_record) return wins except ValueError: return 0
Returns an ``int`` of the number of games the home team won after the conclusion of the game.
6,211
def from_string(cls, s, name=None, modules=None, active=None): r = cls(name=name, modules=modules, active=active) _parse_repp(s.splitlines(), r, None) return r
Instantiate a REPP from a string. Args: name (str, optional): the name of the REPP module modules (dict, optional): a mapping from identifiers to REPP modules active (iterable, optional): an iterable of default module activations
6,212
def magic_write(ofile, Recs, file_type): if len(Recs) < 1: print(.format(ofile)) return False, "" if os.path.split(ofile)[0] != "" and not os.path.isdir(os.path.split(ofile)[0]): os.mkdir(os.path.split(ofile)[0]) pmag_out = open(ofile, , errors="backslashreplace") outstring ...
Parameters _________ ofile : path to output file Recs : list of dictionaries in MagIC format file_type : MagIC table type (e.g., specimens) Return : [True,False] : True if successful ofile : same as input Effects : writes a MagIC formatted file from Recs
6,213
def occupied_by_sort(self, address): idx = self._search(address) if len(self._list) <= idx: return None if self._list[idx].start <= address < self._list[idx].end: return self._list[idx].sort if idx > 0 and address < self._list[idx - 1].end: ...
Check if an address belongs to any segment, and if yes, returns the sort of the segment :param int address: The address to check :return: Sort of the segment that occupies this address :rtype: str
6,214
def simBirth(self,which_agents): N = np.sum(which_agents) aNrmNow_new = drawLognormal(N,mu=self.aNrmInitMean,sigma=self.aNrmInitStd,seed=self.RNG.randint(0,2**31-1)) self.pLvlNow[which_agents] = drawLognormal(N,mu=self.pLvlInitMean,sigma=self.pLvlInitStd,seed=self.RNG.randint(...
Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as well as time variables t_age and t_cycle. Normalized assets and persistent income levels are drawn from lognormal distributions given by aNrmInitMean and aNrmInitStd (etc). Parameters ----------...
6,215
def loads(cls, s: str) -> : try: currency, amount = s.strip().split() return cls(amount, currency) except ValueError as err: raise ValueError("failed to parse string " " : {}".format(s, err))
Parse from a string representation (repr)
6,216
def main(arguments=None): su = tools( arguments=arguments, docString=__doc__, logLevel="ERROR", options_first=True ) arguments, settings, log, dbConn = su.setup() readline.set_completer_delims() readline.parse_and_bind("tab: complete") readline.set...
*The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command*
6,217
def create_response_object(self, service_id, version_number, name, status="200", response="OK", content="", request_condition=None, cache_condition=None): body = self._formdata({ "name": name, "status": status, "response": response, "content": content, "request_condition": request_condition, "cac...
Creates a new Response Object.
6,218
def guessFormat(self): c = [ord(x) for x in self.quals] mi, ma = min(c), max(c) r = [] for entry_format, v in iteritems(RANGES): m1, m2 = v if mi >= m1 and ma < m2: r.append(entry_format) return r
return quality score format - might return several if ambiguous.
6,219
def export_sleep_stats(self, filename, lights_off, lights_on): epochs = self.get_epochs() ep_starts = [i[] for i in epochs] hypno = [i[] for i in epochs] n_ep_per_min = 60 / self.epoch_length first = {} latency = {} for stage in [, , , ]: fir...
Create CSV with sleep statistics. Parameters ---------- filename: str Filename for csv export lights_off: float Initial time when sleeper turns off the light (or their phone) to go to sleep, in seconds from recording start lights_on: float ...
6,220
def __clear_break(self, pid, address): if type(address) not in (int, long): unknown = True label = address try: deferred = self.__deferredBP[pid] del deferred[label] unknown = False except KeyError: ...
Used by L{dont_break_at} and L{dont_stalk_at}. @type pid: int @param pid: Process global ID. @type address: int or str @param address: Memory address of code instruction to break at. It can be an integer value for the actual address or a string with a label ...
6,221
async def play(self, author, text_channel, query, index=None, stop_current=False, shuffle=False): if self.state == : self.state = self.prev_queue = [] await self.set_topic("") await self.msetup(text_channel) await s...
The play command Args: author (discord.Member): The member that called the command text_channel (discord.Channel): The channel where the command was called query (str): The argument that was passed with the command index (str): Whether to play next or at the end ...
6,222
def vote_cast(vote: Vote, choice_index: int, inputs: dict, change_address: str) -> bytes: network_params = net_query(vote.deck.network) vote_cast_addr = vote.vote_choice_address[choice_index] tx_fee = network_params.min_tx_fee for utxo in inputs[]: utxo[] = unhexlify(utxo...
vote cast transaction
6,223
def _generate_style(self): return generate_style(self.code_styles[self._current_code_style_name], self.ui_styles[self._current_ui_style_name])
Create new Style instance. (We don't want to do this on every key press, because each time the renderer receives a new style class, he will redraw everything.)
6,224
def StreamingCommand(cls, usb, service, command=, timeout_ms=None): if not isinstance(command, bytes): command = command.encode() connection = cls.Open( usb, destination=b % (service, command), timeout_ms=timeout_ms) for data in connection.ReadUntilCl...
One complete set of USB packets for a single command. Sends service:command in a new connection, reading the data for the response. All the data is held in memory, large responses will be slow and can fill up memory. Args: usb: USB device handle with BulkRead and BulkWrite me...
6,225
def get_published_events(self, process=True) -> List[Event]: LOG.debug(, self._pub_key) if process: LOG.debug() DB.watch(self._pub_key, pipeline=True) event_ids = DB.get_list(self._pub_key, pipeline=True) if event_ids: DB.delete(se...
Get a list of published (pending) events. Return a list of Event objects which have been published and are therefore pending to be processed. If the process argument is set to true, any events returned from this method will also be marked as processed by moving them to the processed eve...
6,226
def move_dir( src_fs, src_path, dst_fs, dst_path, workers=0, ): def src(): return manage_fs(src_fs, writeable=False) def dst(): return manage_fs(dst_fs, create=True) with src() as _src_fs, dst() as _dst_fs: with _src_fs.lock(), _dst_fs.lock(...
Move a directory from one filesystem to another. Arguments: src_fs (FS or str): Source filesystem (instance or URL). src_path (str): Path to a directory on ``src_fs`` dst_fs (FS or str): Destination filesystem (instance or URL). dst_path (str): Path to a directory on ``dst_fs``. ...
6,227
def get(self,url, headers=None, token=None, data=None, return_json=True, default_headers=True, quiet=False): bot.debug("GET %s" %url) return self._call(url, headers=headers, func=reque...
get will use requests to get a particular url
6,228
def m_c(mcmc, scale, f, alphasMZ=0.1185, loop=3): r if scale == mcmc: return mcmc _sane(scale, f) crd = rundec.CRunDec() alphas_mc = alpha_s(mcmc, 4, alphasMZ=alphasMZ, loop=loop) if f == 4: alphas_scale = alpha_s(scale, f, alphasMZ=alphasMZ, loop=loop) return crd.mMS2m...
r"""Get running c quark mass in the MSbar scheme at the scale `scale` in the theory with `f` dynamical quark flavours starting from $m_c(m_c)$
6,229
def Save(self, token=None): graph_series_by_label = {} for active_time in self.active_days: for label in self.categories[active_time]: graphs_for_label = graph_series_by_label.setdefault( label, rdf_stats.ClientGraphSeries(report_type=self._report_type)) graph = rdf_stats....
Generate a histogram object and store in the specified attribute.
6,230
def add_cli_to_bel(main: click.Group) -> click.Group: @main.command() @click.option(, , type=click.File(), default=sys.stdout) @click.option(, , default=, show_default=True, help=) @click.pass_obj def write(manager: BELManagerMixin, output: TextIO, fmt: str): graph = manager...
Add several command to main :mod:`click` function related to export to BEL.
6,231
async def update(self): keys = self.extras.keys() self.extras = {} for key in keys: try: func = getattr(self, key, None) if callable(func): func() except: pass
reload all cached information |coro| Notes ----- This is a slow process, and will remove the cache before updating. Thus it is recomended to use the `*_force` properties, which will only update the cache after data is retrived.
6,232
def find_central_module(self): mf = ModuleFinder(self.file_opener) candidates = mf.find_by_any_method() sub_modules = [] root_modules = [] for candidate in candidates: if "." in candidate: sub_modules.append(candidate) ...
Get the module that is the sole module, or the module that matches the package name/version :return:
6,233
def _clones(self): vbox = VirtualBox() machines = [] for machine in vbox.machines: if machine.name == self.machine_name: continue if machine.name.startswith(self.machine_name): machines.append(machine) return machines
Yield all machines under this pool
6,234
def _get_prepare_env(self, script, job_descriptor, inputs, outputs, mounts): docker_paths = sorted([ var.docker_path if var.recursive else os.path.dirname(var.docker_path) for var in inputs | outputs | mounts if var.va...
Return a dict with variables for the 'prepare' action.
6,235
def update(self, friendly_name=values.unset, target_workers=values.unset, reservation_activity_sid=values.unset, assignment_activity_sid=values.unset, max_reserved_workers=values.unset, task_order=values.unset): return self._proxy.update( friendl...
Update the TaskQueueInstance :param unicode friendly_name: Human readable description of this TaskQueue :param unicode target_workers: A string describing the Worker selection criteria for any Tasks that enter this TaskQueue. :param unicode reservation_activity_sid: ActivitySID that will be ass...
6,236
def get_player(self, name=None, platform=None, uid=None): results = yield from self.get_players(name=name, platform=platform, uid=uid) return results[0]
|coro| Calls get_players and returns the first element, exactly one of uid and name must be given, platform must be given Parameters ---------- name : str the name of the player you're searching for platform : str the name of the platform you're ...
6,237
def get(self, **options): sub_query = self.with_limit(1) options = QueryOptions(sub_query).replace(batch_size=1) for result in sub_query.run(**options): return result return None
Run this query and get the first result. Parameters: \**options(QueryOptions, optional) Returns: Model: An entity or None if there were no results.
6,238
def get_notifications(self, all=github.GithubObject.NotSet, participating=github.GithubObject.NotSet, since=github.GithubObject.NotSet, before=github.GithubObject.NotSet): assert all is github.GithubObject.NotSet or isinstance(all, bool), all assert participating is github.GithubObject.NotSet ...
:calls: `GET /notifications <http://developer.github.com/v3/activity/notifications>`_ :param all: bool :param participating: bool :param since: datetime.datetime :param before: datetime.datetime :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Notification.No...
6,239
def graft(func=None, *, namespace=None): if not func: return functools.partial(graft, namespace=namespace) if isinstance(func, Graft): return func return Graft(func, namespace=namespace)
Decorator for marking a function as a graft. Parameters: namespace (str): namespace of data, same format as targeting. Returns: Graft For example, these grafts:: @graft def foo_data: return {'foo', True} @graft(namespace='bar') def bar_data: ...
6,240
def create_time_from_text(text): text = text.replace(, ) if not re.match(, text): raise ValueError("Time must be numeric") minutes = int(text[-2:]) hours = int(text[0:2] if len(text) > 3 else text[0]) return datetime.time(hours, minutes)
Parse a time in the form ``hh:mm`` or ``hhmm`` (or even ``hmm``) and return a :class:`datetime.time` object. If no valid time can be extracted from the given string, :exc:`ValueError` will be raised.
6,241
def process(self, candidates): high_score_candidates = [c for c in candidates if c.score >= self.min_score] if high_score_candidates != []: return high_score_candidates return candidates
:arg list candidates: list of Candidates :returns: list of Candidates where score is at least min_score, if and only if one or more Candidates have at least min_score. Otherwise, returns original list of Candidates.
6,242
def _line_iter(self, in_handle): reader = csv.reader(in_handle, dialect="excel-tab") for line in reader: if len(line) > 0 and line[0]: if line[0].upper() == line[0] and "".join(line[1:]) == "": line = [line[0]] yie...
Read tab delimited file, handling ISA-Tab special case headers.
6,243
def to_graphviz(booster, fmap=, num_trees=0, rankdir=, yes_color=, no_color=, condition_node_params=None, leaf_node_params=None, **kwargs): if condition_node_params is None: condition_node_params = {} if leaf_node_params is None: leaf_node_params = {} t...
Convert specified tree to graphviz instance. IPython can automatically plot the returned graphiz instance. Otherwise, you should call .render() method of the returned graphiz instance. Parameters ---------- booster : Booster, XGBModel Booster or XGBModel instance fmap: str (optional) ...
6,244
def _list_records_in_zone(self, zone, rdtype=None, name=None, content=None): records = [] rrsets = zone.iterate_rdatasets() if zone else [] for rname, rdataset in rrsets: rtype = dns.rdatatype.to_text(rdataset.rdtype) if ((not rdtype or rdtype == rtype) ...
Iterates over all records of the zone and returns a list of records filtered by record type, name and content. The list is empty if no records found.
6,245
def main(argv=None): ap = argparse.ArgumentParser( description=, ) ap.add_argument(, action=, help=) ap.add_argument(, metavar=, help=) args = ap.parse_args(argv) mgr = Layouts() if args.list: for name in mgr.list_layouts(): print(name)...
Main entry-point for calling layouts directly as a program.
6,246
def get(self): if not PyFunceble.CONFIGURATION["local"]: if self.domain_extension not in self.ignored_extension: referer = None if self.domain_extension in PyFunceble.INTERN["iana_db"]: ...
Return the referer aka the WHOIS server of the current domain extension.
6,247
def warn( callingClass, astr_key, astr_extraMsg="" ): b_exitToOS = False report( callingClass, astr_key, b_exitToOS, astr_extraMsg )
Convenience dispatcher to the error_exit() method. Will raise "warning" error, i.e. script processing continues.
6,248
def _reproject(self, eopatch, src_raster): height, width = src_raster.shape dst_raster = np.ones((height, width), dtype=self.raster_dtype) src_bbox = transform_bbox(eopatch.bbox, CRS.POP_WEB) src_transform = rasterio.transform.from_bounds(*src_bbox, width=width, height=height)...
Reprojects the raster data from Geopedia's CRS (POP_WEB) to EOPatch's CRS.
6,249
def validate_permission(self, key, permission): if permission.perm_name not in self.__possible_permissions__: raise AssertionError( "perm_name is not one of {}".format(self.__possible_permissions__) ) return permission
validates if group can get assigned with permission
6,250
def list_templates(self, extensions=None, filter_func=None): x = self.loader.list_templates() if extensions is not None: if filter_func is not None: raise TypeError( ) filter_func = lambda x: in x and \ ...
Returns a list of templates for this environment. This requires that the loader supports the loader's :meth:`~BaseLoader.list_templates` method. If there are other files in the template folder besides the actual templates, the returned list can be filtered. There are two ways:...
6,251
def search_customer(self, limit=100, offset=0, email_pattern=None, last_name_pattern=None, company_name_pattern=None, with_additional_data=False): response = self.request(E.searchCustomerRequest( E.limit(limit), E.offset(offset), E.emailPattern(email_pat...
Search the list of customers.
6,252
def red_workshift(request, message=None): if message: messages.add_message(request, messages.ERROR, message) return HttpResponseRedirect(reverse())
Redirects to the base workshift page for users who are logged in
6,253
def provideObjectsToLearn(self, objectNames=None): if objectNames is None: objectNames = self.objects.keys() objects = {} for name in objectNames: objects[name] = [self._getSDRPairs([pair] * self.numColumns) \ for pair in self.objects[name]] self._checkObjectsTo...
Returns the objects in a canonical format to be sent to an experiment. The returned format is a a dictionary where the keys are object names, and values are lists of sensations, each sensation being a mapping from cortical column index to a pair of SDR's (one location and one feature). returnDict = { ...
6,254
def is_prelinked_bytecode(bytecode: bytes, link_refs: List[Dict[str, Any]]) -> bool: for link_ref in link_refs: for offset in link_ref["offsets"]: try: validate_empty_bytes(offset, link_ref["length"], bytecode) except ValidationError: return True ...
Returns False if all expected link_refs are unlinked, otherwise returns True. todo support partially pre-linked bytecode (currently all or nothing)
6,255
def _parse(self, timestr, dayfirst=None, yearfirst=None, fuzzy=False, fuzzy_with_tokens=False): if fuzzy_with_tokens: fuzzy = True info = self.info if dayfirst is None: dayfirst = info.dayfirst if yearfirst is None: yearfirst...
Private method which performs the heavy lifting of parsing, called from ``parse()``, which passes on its ``kwargs`` to this function. :param timestr: The string to parse. :param dayfirst: Whether to interpret the first value in an ambiguous 3-integer date (e...
6,256
def runner(parallel, config): def run_parallel(fn_name, items): items = [x for x in items if x is not None] if len(items) == 0: return [] items = diagnostics.track_parallel(items, fn_name) fn, fn_name = (fn_name, fn_name.__name__) if callable(fn_name) else (get_fn(fn...
Run functions, provided by string name, on multiple cores on the current machine.
6,257
def updated_topology_description(topology_description, server_description): address = server_description.address topology_type = topology_description.topology_type set_name = topology_description.replica_set_name max_set_version = topology_description.max_set_version max_election_id ...
Return an updated copy of a TopologyDescription. :Parameters: - `topology_description`: the current TopologyDescription - `server_description`: a new ServerDescription that resulted from an ismaster call Called after attempting (successfully or not) to call ismaster on the server at se...
6,258
def process(self, ast): id_classifier = IdentifierClassifier() attached_ast = id_classifier.attach_identifier_attributes(ast) self._scope_tree_builder.enter_new_scope(ScopeVisibility.SCRIPT_LOCAL) traverse(attached_ast, on_enter=self._enter_handler,...
Build a scope tree and links between scopes and identifiers by the specified ast. You can access the built scope tree and the built links by .scope_tree and .link_registry.
6,259
def dataset_create_new_cli(self, folder=None, public=False, quiet=False, convert_to_csv=True, dir_mode=): folder = folder or os.getcwd() res...
client wrapper for creating a new dataset Parameters ========== folder: the folder to initialize the metadata file in public: should the dataset be public? quiet: suppress verbose output (default is False) convert_to_csv: if True, convert data to ...
6,260
def value(self): originalPrice = self.lineItem.totalPrice if self.flatRate == 0: return originalPrice * self.percent return self.flatRate
Returns the positive value to subtract from the total.
6,261
def _make_compile_argv(self, compile_request): sources_minus_headers = list(self._iter_sources_minus_headers(compile_request)) if len(sources_minus_headers) == 0: raise self._HeaderOnlyLibrary() compiler = compile_request.compiler compiler_options = compile_request.compiler_options ...
Return a list of arguments to use to compile sources. Subclasses can override and append.
6,262
def parse_input_samples(job, inputs): job.fileStore.logToMaster() samples = [] if inputs.config: with open(inputs.config, ) as f: for line in f.readlines(): if not line.isspace(): sample = line.strip().split() assert len(sample...
Parses config file to pull sample information. Stores samples as tuples of (uuid, URL) :param JobFunctionWrappingJob job: passed by Toil automatically :param Namespace inputs: Stores input arguments (see main)
6,263
def overlay_gateway_access_lists_ipv6_in_cg_ipv6_acl_in_name(self, **kwargs): config = ET.Element("config") overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(overlay_gateway, "name") name_key.text = ...
Auto Generated Code
6,264
def _is_text_data(self, data_type): dt = DATA_TYPES[data_type] if type(self.data) is dt[] and len(self.data) < dt[] and all(type(char) == str for char in self.data): self.type = data_type.upper() self.len = len(self.data) return True
Private method for testing text data types.
6,265
def _parse_xml(self, xml): from re import split vms("Parsing <cron> XML child tag.", 2) self.frequency = get_attrib(xml, "frequency", default=5, cast=int) self.emails = split(",\s*", get_attrib(xml, "emails", default="")) self.notify = split(",\s*", get_attrib(xml, "noti...
Extracts the attributes from the XMLElement instance.
6,266
def swipe(self): @param_to_property(direction=["up", "down", "right", "left"]) def _swipe(direction="left", steps=10, percent=1): if percent == 1: return self.jsonrpc.swipe(self.selector, direction, steps) else: return self.jsonrpc.swipe(s...
Perform swipe action. if device platform greater than API 18, percent can be used and value between 0 and 1 Usages: d().swipe.right() d().swipe.left(steps=10) d().swipe.up(steps=10) d().swipe.down() d().swipe("right", steps=20) d().swipe("right", steps=20, percent...
6,267
def tag_ner(lang, input_text, output_type=list): _check_latest_data(lang) assert lang in NER_DICT.keys(), \ .format(.join(NER_DICT.keys())) types = [str, list] assert type(input_text) in types, .format(.join(types)) assert output_type in types, .format(.join(types)) if type(input...
Run NER for chosen language. Choosing output_type=list, returns a list of tuples: >>> tag_ner('latin', input_text='ut Venus, ut Sirius, ut Spica', output_type=list) [('ut',), ('Venus',), (',',), ('ut',), ('Sirius', 'Entity'), (',',), ('ut',), ('Spica', 'Entity')]
6,268
def _get_phi_al_regional(self, C, mag, vs30measured, rrup): phi_al = np.ones((len(vs30measured))) idx = rrup < 30 phi_al[idx] *= C[] idx = ((rrup <= 80) & (rrup >= 30.)) phi_al[idx] *= C[] + (C[] - C[]) / 50. * (rrup[idx] - 30.) idx = rrup > 80 phi_al[...
Returns intra-event (Tau) standard deviation (equation 26, page 1046)
6,269
def generate_tokens(readline): lnum = parenlev = continued = 0 namechars, numchars = string.ascii_letters + , contstr, needcont = , 0 contline = None indents = [0] while 1: try: line = readline() except StopIteration: ...
The generate_tokens() generator requires one argment, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string. Alternately, readline can be a callable function te...
6,270
def create(cls, path_name=None, name=None, project_id=None, log_modified_at=None, crawlable=True): result = cls(path_name, name, project_id, log_modified_at, crawlable) db.session.add(result) db.session.commit() crawl_result(result, True) return result
Initialize an instance and save it to db.
6,271
def list_gemeenten_by_provincie(self, provincie): try: gewest = provincie.gewest prov = provincie except AttributeError: prov = self.get_provincie_by_id(provincie) gewest = prov.gewest gewest.clear_gateway() def creator(): ...
List all `gemeenten` in a `provincie`. :param provincie: The :class:`Provincie` for which the \ `gemeenten` are wanted. :rtype: A :class:`list` of :class:`Gemeente`.
6,272
def create_paired_dir(output_dir, meta_id, static=False, needwebdir=True): root_path = os.path.abspath(output_dir) else: output_path = root_path else: return meta_dir
Creates the meta or static dirs. Adds an "even" or "odd" subdirectory to the static path based on the meta-id.
6,273
def writeFITSTable(filename, table): def FITSTableType(val): if isinstance(val, bool): types = "L" elif isinstance(val, (int, np.int64, np.int32)): types = "J" elif isinstance(val, (float, np.float64, np.float32)): types = "E" elif is...
Convert a table into a FITSTable and then write to disk. Parameters ---------- filename : str Filename to write. table : Table Table to write. Returns ------- None Notes ----- Due to a bug in numpy, `int32` and `float32` are converted to `int64` and `float64` ...
6,274
def send_error(self, code, message=None): message = message.strip() self.log_error("code %d, message %s", code, message) self.send_response(code) self.send_header("Content-Type", "text/plain") self.send_header(, ) self.end_headers() if message: ...
Send and log plain text error reply. :param code: :param message:
6,275
def _create_fw_fab_dev(self, tenant_id, drvr_name, fw_dict): if fw_dict.get() == fw_constants.FW_TENANT_EDGE: self._create_fw_fab_dev_te(tenant_id, drvr_name, fw_dict)
This routine calls the Tenant Edge routine if FW Type is TE.
6,276
def add_callbacks(self, future, callback, errback): def done(f): try: res = f.result() if callback: callback(res) except Exception: if errback: errback(create_failure()) return future...
callback or errback may be None, but at least one must be non-None.
6,277
def _parse_feature(self, info): parts = info.split(b, 1) name = parts[0] if len(parts) > 1: value = self._path(parts[1]) else: value = None self.features[name] = value return commands.FeatureCommand(name, value, lineno=self.lineno)
Parse a feature command.
6,278
def connect_functions(self): self.cfg_load_pushbutton.clicked.connect(lambda: self.load_overall_config()) self.cfg_save_pushbutton.clicked.connect(lambda: self.save_overall_config()) self.blue_listwidget.itemSelectionChanged.connect(self.load_selected_bot) self.orange_...
Connects all events to the functions which should be called :return:
6,279
def complete_previous(self, count=1, disable_wrap_around=False): if self.complete_state: if self.complete_state.complete_index == 0: index = None if disable_wrap_around: return elif self.complete_state.complete_index is None: ...
Browse to the previous completions. (Does nothing if there are no completion.)
6,280
def ucast_ip_mask(ip_addr_and_mask, return_tuple=True): regex_ucast_ip_and_mask = __re.compile("^((22[0-3])|(2[0-1][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-...
Function to check if a address is unicast and that the CIDR mask is good Args: ip_addr_and_mask: Unicast IP address and mask in the following format 192.168.1.1/24 return_tuple: Set to True it returns a IP and mask in a tuple, set to False returns True or False Returns: see return_tuple for ret...
6,281
def append_data(self, len_tag, val_tag, data, header=False): self.append_pair(len_tag, len(data), header=header) self.append_pair(val_tag, data, header=header) return
Append raw data, possibly including a embedded SOH. :param len_tag: Tag number for length field. :param val_tag: Tag number for value field. :param data: Raw data byte string. :param header: Append to header if True; default to body. Appends two pairs: a length pair, followed b...
6,282
def build_query_uri(self, uri=None, start=0, count=-1, filter=, query=, sort=, view=, fields=, scope_uris=): if filter: filter = self.make_query_filter(filter) if query: query = "&query=" + quote(query) if sort: sort = "&sort=" + quote(sort) ...
Builds the URI from given parameters. More than one request can be send to get the items, regardless the query parameter 'count', because the actual number of items in the response might differ from the requested count. Some types of resource have a limited number of items returned on each call...
6,283
def option(name, help=""): def decorator(func): options = getattr(func, "options", []) _option = Param(name, help) options.insert(0, _option) func.options = options return func return decorator
Decorator that add an option to the wrapped command or function.
6,284
def political_views(self) -> str: views = self._data[] return self.random.choice(views)
Get a random political views. :return: Political views. :Example: Liberal.
6,285
def do_proxy_failover(self, proxy_url, for_url): self._proxy_resolver.ban_proxy(proxy_url) return self._proxy_resolver.get_proxy_for_requests(for_url)
:param str proxy_url: Proxy to ban. :param str for_url: The URL being requested. :returns: The next proxy config to try, or 'DIRECT'. :raises ProxyConfigExhaustedError: If the PAC file provided no usable proxy configuration.
6,286
def showOperandLines(rh): if rh.function == : rh.printLn("N", " For the GetHost function:") else: rh.printLn("N", "Sub-Functions(s):") rh.printLn("N", " diskpoolnames - " + "Returns the names of the directory manager disk pools.") rh.printLn("N", " diskpoolspace ...
Produce help output related to operands. Input: Request Handle
6,287
def get_valid_examples(self): path = os.path.join(self._get_schema_folder(), "examples", "valid") return list(_get_json_content_from_folder(path))
Return a list of valid examples for the given schema.
6,288
def tradepileDelete(self, trade_id): method = url = % trade_id self.__request__(method, url) return True
Remove card from tradepile. :params trade_id: Trade id.
6,289
def read(self, num_bytes=None): res = self.get_next(num_bytes) self.skip(len(res)) return res
Read and return the specified bytes from the buffer.
6,290
def set_file_path(self, filePath): if filePath is not None: assert isinstance(filePath, basestring), "filePath must be None or string" filePath = str(filePath) self.__filePath = filePath
Set the file path that needs to be locked. :Parameters: #. filePath (None, path): The file that needs to be locked. When given and a lock is acquired, the file will be automatically opened for writing or reading depending on the given mode. If None is given, the locker...
6,291
def merge_selected_cells(self, selection): tab = self.grid.current_table bbox = selection.get_bbox() if bbox is None: row, col, tab = self.grid.actions.cursor (bb_top, bb_left), (bb_bottom, bb_right) = (row, col), (row, col) else: (...
Merges or unmerges cells that are in the selection bounding box Parameters ---------- selection: Selection object \tSelection for which attr toggle shall be returned
6,292
def load_steps_impl(self, registry, path, module_names=None): if not module_names: module_names = [] path = os.path.abspath(path) for module_name in module_names: mod = self.modules.get((path, module_name)) if mod is None: ...
Load the step implementations at the given path, with the given module names. If module_names is None then the module 'steps' is searched by default.
6,293
def execute(func: types.FunctionType): spec = getfullargspec(func) default = spec.defaults arg_cursor = 0 def get_item(name): nonlocal arg_cursor ctx = func.__globals__ value = ctx.get(name, _undef) if value is _undef: try: value = defaul...
>>> from Redy.Magic.Classic import execute >>> x = 1 >>> @execute >>> def f(x = x) -> int: >>> return x + 1 >>> assert f is 2
6,294
def aggregate_count_over_time(self, metric_store, groupby_name, aggregate_timestamp): all_qps = metric_store[] qps = all_qps[groupby_name] if aggregate_timestamp in qps: qps[aggregate_timestamp] += 1 else: qps[aggregate_timestamp] = 1 return None
Organize and store the count of data from the log line into the metric store by columnm, group name, timestamp :param dict metric_store: The metric store used to store all the parsed the log data :param string groupby_name: the group name that the log line belongs to :param string aggregate_timestamp: time...
6,295
def get_request_feature(self, name): if in name: return self.request.query_params.getlist( name) if name in self.features else None elif in name: return self._extract_object_params( name) if name in self.feature...
Parses the request for a particular feature. Arguments: name: A feature name. Returns: A feature parsed from the URL if the feature is supported, or None.
6,296
def get_themes(templates_path): themes = os.listdir(templates_path) if in themes: themes.remove() return themes
Returns available themes list.
6,297
def log_request(handler): block = + _format_headers_log(handler.request.headers) if handler.request.arguments: block += for k, v in handler.request.arguments.items(): block += .format(repr(k), repr(v)) app_log.info(block)
Logging request is opposite to response, sometime its necessary, feel free to enable it.
6,298
def fault_sets(self): self.connection._check_login() response = self.connection._do_get("{}/{}".format(self.connection._api_url, "types/FaultSet/instances")).json() all_faultsets = [] for fs in response: all_faultsets.append( SIO_Fault_Set.from_dict(f...
You can only create and configure Fault Sets before adding SDSs to the system, and configuring them incorrectly may prevent the creation of volumes. An SDS can only be added to a Fault Set during the creation of the SDS. :rtype: list of Faultset objects
6,299
def _parse_depot_section(f): depots = [] for line in f: line = strip(line) if line == or line == : break else: depots.append(line) if len(depots) != 1: raise ParseException() return int(depots[0])
Parse TSPLIB DEPOT_SECTION data part from file descriptor f Args ---- f : str File descriptor Returns ------- int an array of depots