Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
358,300
def add_agent(self, *args, **kwargs): el_metsHdr = self._tree.getroot().find(, NS) if el_metsHdr is None: el_metsHdr = ET.Element(TAG_METS_METSHDR) self._tree.getroot().insert(0, el_metsHdr) el_agent = ET.SubElement(el_metsHdr, TAG_METS_AGENT) ...
Add an `OcrdAgent </../../ocrd_models/ocrd_models.ocrd_agent.html>`_ to the list of agents in the metsHdr.
358,301
def _collapse_postconditions(base_postconditions: List[Contract], postconditions: List[Contract]) -> List[Contract]: return base_postconditions + postconditions
Collapse function postconditions with the postconditions collected from the base classes. :param base_postconditions: postconditions collected from the base classes :param postconditions: postconditions of the function (before the collapse) :return: collapsed sequence of postconditions
358,302
def fill_missing_attributes_from_default_parameter(self, param): if not self.exists(param.name) or not ParameterScenarioSet.default_scenario in self.parameter_sets[ param.name].scenarios.keys(): logger.warning( f) return default = self.paramet...
Empty fields in Parameter definitions in scenarios are populated with default values. E.g. in the example below, the source for the Power_TV variable in the 8K scenario would also be EnergyStar. | name | scenario | val | tags | source | |----------|----------|-----|--------|---------...
358,303
def schedule_forced_host_svc_checks(self, host, check_time): for service_id in host.services: service = self.daemon.services[service_id] self.schedule_forced_svc_check(service, check_time) self.send_an_element(service.get_update_status_brok())
Schedule a forced check on all services of a host Format of the line that triggers function call:: SCHEDULE_FORCED_HOST_SVC_CHECKS;<host_name>;<check_time> :param host: host to check :type host: alignak.object.host.Host :param check_time: time to check :type check_time:...
358,304
def process_image(self, image, image_format, save_kwargs, width, height): imagefile = BytesIO() image.thumbnail( (width, height), Image.ANTIALIAS ) image.save( imagefile, **save_kwargs ) return...
Return a BytesIO instance of `image` that fits in a bounding box. Bounding box dimensions are `width`x`height`.
358,305
def choose_tag(self: object, tokens: List[str], index: int, history: List[str]): keys = self.lemmas.keys() if tokens[index] in keys: return self.lemmas[tokens[index]]
Looks up token in ``lemmas`` dict and returns the corresponding value as lemma. :rtype: str :type tokens: list :param tokens: List of tokens to be lemmatized :type index: int :param index: Int with current token :type history: list :param history: List wit...
358,306
def indices(self, fit): lam_reev = 1.0 * (self.lam_reeval if self.lam_reeval else 2 + len(fit) / 20) lam_reev = int(lam_reev) + ((lam_reev % 1) > np.random.rand()) choice = 1 if choice == 1: n_first = lam_ree...
return the set of indices to be reevaluated for noise measurement. Given the first values are the earliest, this is a useful policy also with a time changing objective.
358,307
def set_defaults(self): for key, value in self.spec.items(): setattr(self, key.upper(), value.get("default", None))
Add each model entry with it's default
358,308
def save_info_df(self): logger.debug("running save_info_df") info_df = self.info_df top_level_dict = {: info_df, : self._prm_packer()} jason_string = json.dumps(top_level_dict, default=lambda info_df: json.loads( ...
Saves the DataFrame with info about the runs to a JSON file
358,309
def raw(self): qs = self.build_search() es = self.get_es() index = self.get_indexes() doc_type = self.get_doctypes() if doc_type and not index: raise BadSearch( ) extra_search_kwargs = {} if self.search_type: ext...
Build query and passes to Elasticsearch, then returns the raw format returned.
358,310
def to_capabilities(self): caps = self._caps chrome_options = self.experimental_options.copy() chrome_options["extensions"] = self.extensions if self.binary_location: chrome_options["binary"] = self.binary_location chrome_options["args"] = self.arguments ...
Creates a capabilities with all the options that have been set :Returns: A dictionary with everything
358,311
def rho_rec(self, g2): return (self.expnorm / np.sqrt(1 + self.gamma2 * g2) + ( 1 - self.expnorm) * np.exp(-0.25 * self.beta2 * g2))
Reciprocal space model charge value for input squared reciprocal vector. Args: g2: Square of reciprocal vector Returns: Charge density at the reciprocal vector magnitude
358,312
def plot_energy_signature( meter_data, temperature_data, temp_col=None, ax=None, title=None, figsize=None, **kwargs ): try: import matplotlib.pyplot as plt except ImportError: raise ImportError("matplotlib is required for plotting.") temperature_mean ...
Plot meter and temperature data in energy signature. Parameters ---------- meter_data : :any:`pandas.DataFrame` A :any:`pandas.DatetimeIndex`-indexed DataFrame of meter data with the column ``value``. temperature_data : :any:`pandas.Series` A :any:`pandas.DatetimeIndex`-indexed Series o...
358,313
def set_marked(self, name: str, marked: bool = False, unmarked: bool = False) -> None: if marked: self._marked[name] = True elif unmarked: self._marked[name] = False else: self._marked.pop(name, None)
Add or remove the ``\\Marked`` and ``\\Unmarked`` mailbox attributes. Args: name: The name of the mailbox. marked: True if the ``\\Marked`` attribute should be added. unmarked: True if the ``\\Unmarked`` attribute should be added.
358,314
def _get_all_merges(routing_table): considered_entries = set() for i, entry in enumerate(routing_table): if i in considered_entries: continue merge = set([i]) merge.update( j for j, other_entry in enumerate(routing_table[i+1:...
Get possible sets of entries to merge. Yields ------ :py:class:`~.Merge`
358,315
def _gen_figure(nxplot=1, nyplot=1, figargs=None, projection=None, sharex=, joinx=False, sharey=, joiny=False, x=None, nxlabel=None, xlabels=None, nxdecimal=None, xmin=None, xmax=None, y=None, nylabel=None, ylabels=None, nydecimal=None, ymin=None, ymax=None, ...
Returns a figure object with as much customization as provided.
358,316
def save(self, p_todolist): self._trim() current_hash = hash_todolist(p_todolist) list_todo = (self.todolist.print_todos()+).splitlines(True) try: list_archive = (self.archive.print_todos()+).splitlines(True) except AttributeError: list_archive =...
Saves a tuple with archive, todolist and command with its arguments into the backup file with unix timestamp as the key. Tuple is then indexed in backup file with combination of hash calculated from p_todolist and unix timestamp. Backup file is closed afterwards.
358,317
def finish(self): for obj in self.current_tweens: for tween in self.current_tweens[obj]: tween.finish() self.current_tweens = {}
jump the the last frame of all tweens
358,318
def hoverLeaveEvent(self, event): self._hovered = False if self.toolTip(): QToolTip.hideText() return self.style() == XNodeHotspot.Style.Icon
Processes when this hotspot is entered. :param event | <QHoverEvent> :return <bool> | processed
358,319
def _set_sub_interface_statistics_state(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=sub_interface_statistics_state.sub_interface_statistics_state, is_container=, presence=False, yang_name="sub-interface-statistics-state", rest_name="sub-interface-...
Setter method for sub_interface_statistics_state, mapped from YANG variable /sub_interface_statistics_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_sub_interface_statistics_state is considered as a private method. Backends looking to populate this variabl...
358,320
def _extract_dependencies_by_root(cls, result): flat_result = defaultdict(list) for artifact in result[]: flat_result[artifact[]].extend(artifact[]) return flat_result
Only extracts the transitive dependencies for the given coursier resolve. Note the "dependencies" field is already transitive. Example: { "conflict_resolution": {}, "dependencies": [ { "coord": "a", "dependencies": ["b", "c"] "file": ... }, ...
358,321
def _plain_authentication(self, login, password, authz_id=b""): if isinstance(login, six.text_type): login = login.encode("utf-8") if isinstance(password, six.text_type): password = password.encode("utf-8") params = base64.b64encode(b.join([authz_id, login, passw...
SASL PLAIN authentication :param login: username :param password: clear password :return: True on success, False otherwise.
358,322
def string_to_uuid(value, strict=True): try: return None if is_undefined(value) else uuid.UUID(value) except ValueError, error: if strict: raise error
Return a Universally Unique Identifier (UUID) object represented by the specified string. @param value: a string representation of a UUID. @param strict: indicate whether the specified string MUST be of a valid UUID representation. @return: a UUID object.
358,323
def generate_unique_name(self, basename): counts = self.__counts try: count = counts[basename] counts[basename] += 1 except KeyError: count = 0 counts[basename] = 1 prefix = self.Naming_prefix if count == 0: ...
Generates a unique name for a child given a base name.
358,324
def load(filename=None, url=r"https://raw.githubusercontent.com/googlei18n/emoji4unicode/master/data/emoji4unicode.xml", loader_class=None): u if not has_loaded(): reload(filename, url, loader_class)
u"""load google's `emoji4unicode` project's xml file. must call this method first to use `e4u` library. this method never work twice if you want to reload, use `e4u.reload()` insted.
358,325
def getDependencySpecs(self, target=None): deps = [] def specForDependency(name, version_spec, istest): shrinkwrap = self.getShrinkwrapMapping() shrinkwrap_version_req = None if name in shrinkwrap: shrinkwrap_version_req = sh...
Returns [DependencySpec] These are returned in the order that they are listed in the component description file: this is so that dependency resolution proceeds in a predictable way.
358,326
def add(self, stream_id, task_ids, grouping, source_comp_name): if stream_id not in self.targets: self.targets[stream_id] = [] self.targets[stream_id].append(Target(task_ids, grouping, source_comp_name))
Adds the target component :type stream_id: str :param stream_id: stream id into which tuples are emitted :type task_ids: list of str :param task_ids: list of task ids to which tuples are emitted :type grouping: ICustomStreamGrouping object :param grouping: custom grouping to use :type sourc...
358,327
def GetLastChildControl(self) -> : ele = _AutomationClient.instance().ViewWalker.GetLastChildElement(self.Element) return Control.CreateControlFromElement(ele)
Return `Control` subclass or None.
358,328
def _get_device_by_key(devices, key): device_keys = [d for d in devices if d.key == key] if device_keys: return device_keys[0] else: raise salt.exceptions.VMwareObjectNotFoundError( .format(key))
Returns the device with the given key, raises error if the device is not found. devices list of vim.vm.device.VirtualDevice objects key Unique key of device
358,329
def predict_step(F, covX, filt): pred_mean = np.matmul(filt.mean, F.T) pred_cov = dotdot(F, filt.cov, F.T) + covX return MeanAndCov(mean=pred_mean, cov=pred_cov)
Predictive step of Kalman filter. Parameters ---------- F: (dx, dx) numpy array Mean of X_t | X_{t-1} is F * X_{t-1} covX: (dx, dx) numpy array covariance of X_t | X_{t-1} filt: MeanAndCov object filtering distribution at time t-1 Returns ------- pred: MeanAn...
358,330
def create_self_signed(cls, name, common_name, public_key_algorithm=, signature_algorithm=, key_length=4096): tls = TLSServerCredential.create_csr(name=name, common_name=common_name, public_key_algorithm=public_key_algorithm, signature_algorithm=signature_algorithm, ...
Create a self signed certificate. This is a convenience method that first calls :meth:`~create_csr`, then calls :meth:`~self_sign` on the returned TLSServerCredential object. :param str name: name of TLS Server Credential :param str rcommon_name: common name for certificate. An ...
358,331
def _ip_setter(self, ipaddr_name, ipaddrs_name, ips): if isinstance(ips, six.string_types): setattr(self, ipaddr_name, ips) elif isinstance(ips, (list, tuple)) and isinstance(ips[0], IP): setattr(self, ipaddr_name, ips[0].ip) setattr(self, ipaddrs_name, ips) ...
Setter for ip fields Accept as input string or list of IP instances. String case: only ipvXaddr is going to be filled, that is enough to perform host record search using ip List of IP instances case: ipvXaddrs is going to be filled with ips content, ...
358,332
def readall_fast(stm, size): buf, offset = stm.read_fast(size) if len(buf) - offset < size: buf = buf[offset:] buf += stm.recv(size - len(buf)) return buf, 0 return buf, offset
Slightly faster version of readall, it reads no more than two chunks. Meaning that it can only be used to read small data that doesn't span more that two packets. :param stm: Stream to read from, should have read method. :param size: Number of bytes to read. :return:
358,333
def moments_match_ep(self, Y_i, tau_i, v_i, Y_metadata_i=None): if Y_i == 1: sign = 1. elif Y_i == 0 or Y_i == -1: sign = -1 else: raise ValueError("bad value for Bernoulli observation (0, 1)") if isinstance(self.gp_link, link_functions.Probit...
Moments match of the marginal approximation in EP algorithm :param i: number of observation (int) :param tau_i: precision of the cavity distribution (float) :param v_i: mean/variance of the cavity distribution (float)
358,334
def add_scalebar(ax, matchx=True, matchy=True, hidex=True, hidey=True, unitsx=, unitsy=, scalex=1, scaley=1, **kwargs): def f(axis): l = axis.get_majorticklocs() return len(l)>1 and (l[1] - l[0]) if matchx: kwargs[] = f(ax.xaxis) if matchy: kwargs[] = f(ax.yaxis) if not...
Add scalebars to axes Adds a set of scale bars to *ax*, matching the size to the ticks of the plot and optionally hiding the x and y axes - ax : the axis to attach ticks to - matchx,matchy : if True, set size of scale bars to spacing between ticks if False, size should be set using s...
358,335
def _to_dict(self): _dict = {} if hasattr(self, ) and self.global_ is not None: _dict[] = self.global_._to_dict() if hasattr(self, ) and self.skills is not None: _dict[] = self.skills._to_dict() return _dict
Return a json dictionary representing this model.
358,336
def update_links(self, request, admin_site=None): if admin_site: bundle = admin_site.get_bundle_for_model(self.model.to) if bundle: self._api_link = self._get_bundle_link(bundle, self.view, request.user) ...
Called to update the widget's urls. Tries to find the bundle for the model that this foreign key points to and then asks it for the urls for adding and listing and sets them on this widget instance. The urls are only set if request.user has permissions on that url. :param reques...
358,337
def sample(records, k, random_seed=None): if random_seed is not None: random.seed(random_seed) result = [] for i, record in enumerate(records): if len(result) < k: result.append(record) else: r = random.randint(0, i) if r < k: ...
Choose a length-``k`` subset of ``records``, retaining the input order. If k > len(records), all are returned. If an integer ``random_seed`` is provided, sets ``random.seed()``
358,338
def division_content(self, election_day, division, special=False): from electionnight.models import PageType division_type = ContentType.objects.get_for_model(division) page_type = PageType.objects.get( model_type=division_type, election_day=election_day, ...
Return serialized content for a division page.
358,339
def main(): parser = argparse.ArgumentParser( description="[v" + __version__ + "] " + __doc__, prog="w3c_validator", ) parser.add_argument( "--log", default="INFO", help=("log level: DEBUG, INFO or INFO " "(default: INFO)")) parser.add_argument(...
Parser the command line and run the validator.
358,340
def lime_tabular_regression_1000(model, data): return lambda X: other.LimeTabularExplainer(model.predict, data, mode="regression").attributions(X, nsamples=1000)
LIME Tabular 1000
358,341
def getSendPath(self, volume): try: return self._fullPath(next(iter(self.getPaths(volume)))) except StopIteration: return None
Get a path appropriate for sending the volume from this Store. The path may be relative or absolute in this Store.
358,342
def delete_older(self): logger.info( "Deleting all mails strictly older than the {} timestamp..." "".format(self.newest_timestamp)) candidates = [ mail for mail in self.pool if mail.timestamp < self.newest_timestamp] if len(candid...
Delete all older duplicates. Only keeps the subset sharing the most recent timestamp.
358,343
def apns_send_message(registration_id, alert, application_id=None, certfile=None, **kwargs): try: _apns_send( registration_id, alert, application_id=application_id, certfile=certfile, **kwargs ) except apns2_errors.APNsException as apns2_exception: if isinstance(apns2_exception, apns2_errors.Unregister...
Sends an APNS notification to a single registration_id. This will send the notification as form data. If sending multiple notifications, it is more efficient to use apns_send_bulk_message() Note that if set alert should always be a string. If it is not set, it won"t be included in the notification. You will need ...
358,344
def createuser(email, password, role=None, name=None, first_name=None): if User.query.filter(User.email == email).count() > 0: print(f"A user with email already exists, aborting.") return user = User( email=email, password=password, last_name=name, ...
Create new user.
358,345
def value_after(self, x): try: try: i = self.all.index(x) except ValueError: return None return self.all[i + 1] except IndexError: return None
Returns value of argument after given found argument (or list thereof).
358,346
def _ResponseToClientsFullInfo(self, response): c_full_info = None prev_cid = None for row in response: (cid, fs, crt, ping, clk, ip, foreman, first, last_client_ts, last_crash_ts, last_startup_ts, client_obj, client_startup_obj, last_startup_obj, label_owner, label_name) = row ...
Creates a ClientFullInfo object from a database response.
358,347
def updateActiveMarkupClass(self): previousMarkupClass = self.activeMarkupClass self.activeMarkupClass = find_markup_class_by_name(globalSettings.defaultMarkup) if self._fileName: markupClass = get_markup_for_file_name( self._fileName, return_class=True) if markupClass: self.activeMarkupClass =...
Update the active markup class based on the default class and the current filename. If the active markup class changes, the highlighter is rerun on the input text, the markup object of this tab is replaced with one of the new class and the activeMarkupChanged signal is emitted.
358,348
def generate_candidates(freq_set, k): single_set = {(i,) for i in set(flatten(freq_set))} cands = [flatten(f) for f in combinations(single_set, k)] return [cand for cand in cands if validate_candidate(cand, freq_set, k)]
Generate candidates for an iteration. Use this only for k >= 2.
358,349
async def start_child(): logger.info() loop = asyncio.get_event_loop() watcher = aionotify.Watcher() flags = ( aionotify.Flags.MODIFY | aionotify.Flags.DELETE | aionotify.Flags.ATTRIB | aionotify.Flags.MOVED_TO | aionotify.Flags.MOVED_FROM | aionot...
Start the child process that will look for changes in modules.
358,350
def create_stack(name=None, template_file=None, environment=None, parameters=None, poll=0, rollback=False, timeout=60, profile=None, enviroment=None): * if environment is None and enviroment is not None: salt.utils.versions.warn_until(, ( "Please use the pa...
Create a stack (heat stack-create) name Name of the new stack template_file File of template environment File of environment parameters Parameter dict used to create the stack poll Poll and report events until stack complete rollback Enable r...
358,351
def to_dict(self): return { "node": [v.to_dict() for v in self.vertices], "edge": [e.to_dict() for e in self.edges] }
Returns a simplified dictionary representing the Graph. Returns: A dictionary that can easily be serialized to JSON.
358,352
def _fuzzy_time_parse(self, value): value = value.lower().strip() today = datetime.date.today() if value in (, ): return today else: kwargs = {} if value in (, ): kwargs[] = -1 elif value in (, , , ): ...
Parses a fuzzy time value into a meaningful interpretation. `value` String value to parse.
358,353
def destroy_plugin(plugin_name, conn=None): results = {} if plugin_exists(plugin_name, conn=conn): results = RPX.table_drop(plugin_name).run(conn) return results
Creates a new plugin :param plugin_name: <str> :param conn: :return: <dict> rethinkdb response
358,354
def _alt_ac_for_tx_ac(self, tx_ac): alt_acs = [ e["alt_ac"] for e in self.hdp.get_tx_mapping_options(tx_ac) if e["alt_aln_method"] == self.alt_aln_method and e["alt_ac"] in self._assembly_accessions ] if not alt_acs: raise HGVSDataNotAvailableError("...
return chromosomal accession for given transcript accession (and the_assembly and aln_method setting used to instantiate this AssemblyMapper)
358,355
def getPhysicalDisplayInfo(self): self.__checkTransport() phyDispRE = re.compile(, re.DOTALL) m = phyDispRE.search(self.shell()) if m: displayInfo = {} for prop in [, ]: displayInfo[prop] = int(m.group(prop)...
Gets C{mPhysicalDisplayInfo} values from dumpsys. This is a method to obtain display dimensions and density
358,356
def detect_language_filename(cls, filename): log.debug(.format(filename)) root, _ = os.path.splitext(filename) fn_lang = cls.DETECT_LANGUAGE_REGEX.findall(root) if fn_lang: language_part = fn_lang[0] try: lang = Language.from_unknown(langu...
Detect the language of a subtitle filename :param filename: filename of a subtitle :return: Language object, None if language could not be detected.
358,357
def validate_obj(keys, obj): msg = for k in keys: if isinstance(k, str): if k not in obj or (not isinstance(obj[k], list) and not obj[k]): if msg: msg = "%s," % msg msg = "%s%s" % (msg, k) elif isinstance(k, list): ...
Super simple "object" validation.
358,358
def _to_dict(self): _dict = {} if hasattr(self, ) and self.response_type is not None: _dict[] = self.response_type if hasattr(self, ) and self.values is not None: _dict[] = [x._to_dict() for x in self.values] if hasattr(self, ) and self...
Return a json dictionary representing this model.
358,359
def to_checksum_address(value: AnyStr) -> ChecksumAddress: norm_address = to_normalized_address(value) address_hash = encode_hex(keccak(text=remove_0x_prefix(norm_address))) checksum_address = add_0x_prefix( "".join( ( norm_address[i].upper() if int(...
Makes a checksum address given a supported format.
358,360
def _serialiseExistingJob(self, jobGraph, jobStore, returnValues): self._serialiseJobGraph(jobGraph, jobStore, returnValues, False) jobGraph.command = None assert len(jobGraph.stack) >= 4 combinedChildren = jobGraph.stack[-1] + jobGraph.stack[-3] ...
Serialise an existing job.
358,361
def diff(a, b): delta = diff(a, b) if not a: return delta for item in delta: if isinstance(a[item], list): if delta[item] == []: delta[item] = {JSONUtils.DIFF_DELETE : a[item]} elif isinstance(delta[item], dict)...
Compares JSON objects :param a: :param b: :return: difference object a vs b
358,362
def removeProfile(self, profile, silent=False): if not profile: return if not silent: title = .format(self.profileText()) opts = QMessageBox.Yes | QMessageBox.No quest = quest %= profile.name() if isinstance(profile...
Removes the given profile from the toolbar. :param profile | <projexui.widgets.xviewwidget.XViewProfile>
358,363
def readObject(self, innode): names=innode.getElementsByTagName()[0].childNodes[0].data.strip() pointType = if len(innode.getElementsByTagName()) == 0 and len(innode.getElementsByTagName()) == 0: pointType = elif len(innode.getElementsByT...
reads in a node and returns as a tuple: (type, name, points[])
358,364
def stop(self): if self._done_event.is_set(): return self._done_event.set() with self.__lock: try: for _ in self._threads: self._queue.put(self._done_event, True, self._timeout) ...
Stops the thread pool. Does nothing if the pool is already stopped.
358,365
def directory_is_present(self, directory_path): p = self.p(directory_path) if not os.path.exists(p): return False if not os.path.isdir(p): raise IOError("%s is not a directory" % directory_path) return True
check if directory 'directory_path' is present, raise IOError if it's not a directory :param directory_path: str, directory to check :return: True if directory exists, False if directory does not exist
358,366
def pp(self): for src, dst, data in self.graph.edges(data=True): print("%s <-- %s, %s" % (src, dst, data))
Pretty printing.
358,367
def _setDatasets(self, metadata): cols = list(self.getCSVReader(metadata)) cols.sort(key=lambda x: [x[], int(x[])]) for key, grp in groupby(cols, key=lambda x: x["viewname"]): self.datasets[key] = list(grp)
Extract dataset definitions from CSV metadata
358,368
def validate_mixture(supports_mixture: SupportsMixture): mixture_tuple = mixture(supports_mixture, None) if mixture_tuple is None: raise TypeError(.format( supports_mixture)) def validate_probability(p, p_str): if p < 0: raise ValueError(.format(p_str)) ...
Validates that the mixture's tuple are valid probabilities.
358,369
def load_ext(self): try: sequencemanager = hydpy.pub.sequencemanager except AttributeError: raise RuntimeError( % objecttools.devicephrase(self)) sequencemanager.load_file(self)
Read the internal data from an external data file.
358,370
def separateKeywords(kwArgsDict): standardKws = {} ourKws = {} for k in kwArgsDict: if k in STANDARD_KEYS: standardKws[k]=kwArgsDict[k] else: ourKws[k]=kwArgsDict[k] return (standardKws, ourKws)
Look through the keywords passed and separate the special ones we have added from the legal/standard ones. Return both sets as two dicts (in a tuple), as (standardKws, ourKws)
358,371
def bind_unix_socket(file_, mode=0o600, backlog=_DEFAULT_BACKLOG): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setblocking(0) try: st = os.stat(file_) except OSError as err: if err.errno != errno.ENOENT...
Creates a listening unix socket. If a socket with the given name already exists, it will be deleted. If any other file with that name exists, an exception will be raised. Returns a socket object (not a list of socket objects like `bind_sockets`)
358,372
def _compute_integral_x(self): right_triangle_vols = self.cell_partitions node_edges = self.idx_hierarchy corner = self.node_coords[node_edges] edge_midpoints = 0.5 * (corner[0] + corner[1]) cc = self.cell_circumcenters average = (co...
Computes the integral of x, \\int_V x, over all atomic "triangles", i.e., areas cornered by a node, an edge midpoint, and a circumcenter.
358,373
def derivative(self, point): r point = self.domain.element(point) diff = point - self.vector dist = self.vector.dist(point) if dist == 0: raise ValueError( .format(self.vector)) return InnerProductOperator(diff / dist)
r"""The derivative operator. ``DistOperator(y).derivative(z)(x) == ((y - z) / y.dist(z)).inner(x)`` This is only applicable in inner product spaces. Parameters ---------- x : `domain` `element-like` Point in which to take the derivative. Re...
358,374
def get_organisations(self, **query_params): organisations = self.get_organisations_json(self.base_uri, query_params=query_params) organisations_list = [] for organisation_json in organisations: organisations_list.append( ...
Get all organisations this member is attached to. Return a list of Organisation objects. Returns: list(Organisation): Return all organisations this member is attached to
358,375
def hexists(self, key, field): fut = self.execute(b, key, field) return wait_convert(fut, bool)
Determine if hash field exists.
358,376
def raw_command(self, lun, netfn, raw_bytes): return self.interface.send_and_receive_raw(self.target, lun, netfn, raw_bytes)
Send the raw command data and return the raw response. lun: the logical unit number netfn: the network function raw_bytes: the raw message as bytestring Returns the response as bytestring.
358,377
def revnet_110_cifar(): hparams = revnet_cifar_base() hparams.bottleneck = False hparams.num_channels = [16, 32, 64] hparams.num_layers_per_block = [8, 8, 8] return hparams
Tiny hparams suitable for CIFAR/etc.
358,378
def create_category(self, category): content = self._serialize.body(category, ) response = self._send(http_method=, location_id=, version=, content=content) return self._deserialize(, response)
CreateCategory. [Preview API] :param :class:`<ExtensionCategory> <azure.devops.v5_1.gallery.models.ExtensionCategory>` category: :rtype: :class:`<ExtensionCategory> <azure.devops.v5_1.gallery.models.ExtensionCategory>`
358,379
def _truncateend(self, bits): assert 0 <= bits <= self.len if not bits: return if bits == self.len: self._clear() return newlength_in_bytes = (self._offset + self.len - bits + 7) // 8 self._setbytes_unsafe(self._datastore.getbyteslice(...
Truncate bits from the end of the bitstring.
358,380
def static_sum(values, limit_n=1000): if len(values) < limit_n: return sum(values) else: half = len(values) // 2 return add( static_sum(values[:half], limit_n), static_sum(values[half:], limit_n))
Example of static sum routine.
358,381
def insert_fft_option_group(parser): fft_group = parser.add_argument_group("Options for selecting the" " FFT backend and controlling its performance" " in this program.") fft_group.add_argument("--fft-backend...
Adds the options used to choose an FFT backend. This should be used if your program supports the ability to select the FFT backend; otherwise you may simply call the fft and ifft functions and rely on default choices. This function will also attempt to add any options exported by available backends thr...
358,382
def echo( message=None, file=None, nl=True, err=False, color=None, carriage_return=False ): message = message or "" if carriage_return and nl: click_echo(message + "\r\n", file, False, err, color) elif carriage_return and not nl: click_echo(message + "\r", file, False, err, color) ...
Patched click echo function.
358,383
def destructive_inject(self, filename, content): content = _unicode(content) backup_file(filename) full_path = self.__generate_file(filename) with codecs.open(full_path, , encoding="utf-8") as f: new_content = self.inject_content(f.read(), content) with codec...
Injects the injections desired immediately. This should generally be run only during the commit phase, when no future injections will be done.
358,384
def prepare(_next, self): _next(self) if not self.roles_support: return if not self.request.has_permission(, self.model.parent): return value = [] if self.action_resource == : value = self.model.model.roles roles_w...
Hook after prepare and set 'principal_roles' as selection to ``self.form``.
358,385
def make_table(self): num_records = int(np.sum([1 for frame in self.timeseries])) dtype = [ ("frame",float),("time",float),("proteinring",list), ("ligand_ring_ids",list),("distance",float),("angle",float), ("offset",float),("type","|U4"),("resid",...
Make numpy array from timeseries data.
358,386
def get_slider_items(context, amount=None): req = context.get() qs = SliderItem.objects.published(req).order_by() if amount: qs = qs[:amount] return qs
Returns the published slider items.
358,387
def delete(self): if lib.EnvDeleteActivation(self._env, self._act) != 1: raise CLIPSError(self._env) self._env = None
Remove the activation from the agenda.
358,388
def show_category(self): url = r = requests.get(url) check_error(r) return r.json()
doc: http://open.youku.com/docs/doc?id=93
358,389
def prettyln(text, fill=, align=, prefix=, suffix=, length=69): text = .format(text, prefix=prefix, suffix=suffix) print( "{0:{fill}{align}{length}}".format( text, fill=fill, align=align, length=length ) )
Wrap `text` in a pretty line with maximum length.
358,390
def visitNodeConstraintNonLiteral(self, ctx: ShExDocParser.NodeConstraintNonLiteralContext): self.nodeconstraint.nodeKind = if ctx.nonLiteralKind().KW_IRI() \ else if ctx.nonLiteralKind().KW_BNODE() \ else if ctx.nonLiteralKind().KW_NONLITERAL() \ else se...
nodeConstraint: nonLiteralKind stringFacet* # nodeConstraintNonLiteral
358,391
def lambda_vpc_execution_statements(): return [ Statement( Effect=Allow, Resource=[], Action=[ ec2.CreateNetworkInterface, ec2.DescribeNetworkInterfaces, ec2.DeleteNetworkInterface, ] ) ]
Allow Lambda to manipuate EC2 ENIs for VPC support.
358,392
def array(input, separator=, strip=True, empty=False): if input is None: return [] if isinstance(input, list): if not empty: return [i for i in input if i] return input if not isinstance(input, (binary, unicode)): if not empty: ...
Convert the given input to a list. Intelligently handles list and non-string values, returning as-is and passing to the list builtin respectively. The default optional keyword arguments allow for lists in the form:: "foo,bar, baz , diz" -> ['foo', 'bar', 'baz', 'diz'] For a...
358,393
def stop_ppp_link(self): if self.ppp_fd == -1: return try: self.mpself.select_extra.pop(self.ppp_fd) os.close(self.ppp_fd) os.waitpid(self.pid, 0) except Exception: pass self.pid = -1 self.ppp_fd = -1 pr...
stop the link
358,394
def plot_all(self, t=0, f_start=None, f_stop=None, logged=False, if_id=0, kurtosis=True, **kwargs): if self.header[b] <=2: logged = False nullfmt = NullFormatter() left, width = 0.35, 0.5 bottom, height = 0.45, 0.5 width2, height2 = 0.1125, 0.15 ...
Plot waterfall of data as well as spectrum; also, placeholder to make even more complicated plots in the future. Args: f_start (float): start frequency, in MHz f_stop (float): stop frequency, in MHz logged (bool): Plot in linear (False) or dB units (True), t (int...
358,395
def max_display_width(myDict): 你们大家好ABCDE1234567 maxValueWidth = 0 for each in myDict: eachValueWidth = str_display_width(myDict[each]) if(eachValueWidth > maxValueWidth): maxValueWidth = eachValueWidth return(maxValueWidth)
currd = {0:'你们大家好', 125:'ABCDE', 6:'1234567'} dict_get_max_word_displaywidth(currd)
358,396
def download_file(self, url, download_dir, sceneName): try: logger.info() print() req = urllib.request.urlopen(url) try: if req.info().get_content_type() == : logger.error("error : the file f...
Downloads large files in pieces
358,397
def collections(cloud=None, api_key=None, version=None, **kwargs): url_params = {"batch": False, "api_key": api_key, "version": version, "method": "collections"} return api_handler(None, cloud=cloud, api="custom", url_params=url_params, **kwargs)
This is a status report endpoint. It is used to get the status on all of the collections currently trained, as well as some basic statistics on their accuracies. Inputs api_key (optional) - String: Your API key, required only if the key has not been declared elsewhere. This allows the API to recogniz...
358,398
def brighten(self, amount=10): lch = self.to("lch") l, c, h = lch.values new_lch = self.__class__("lch", l + amount, c, h) return new_lch.to(self.space)
Brighten this color by `amount` luminance. Converts this color to the LCH color space, and then increases the `L` parameter by `amount`. :param float amount: Amount to increase the luminance. :rtype: Color :returns: A new spectra.Color
358,399
def expression_filter(self, name, **kwargs): def decorator(func): self.filters[name] = ExpressionFilter(name, func, **kwargs) return decorator
Returns a decorator function for adding an expression filter. Args: name (str): The name of the filter. **kwargs: Variable keyword arguments for the filter. Returns: Callable[[Callable[[AbstractExpression, Any], AbstractExpression]]]: A decorator fun...