Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
340,700
def seek(self, offset, whence=os.SEEK_SET): if not self._is_open: raise IOError() if whence not in [os.SEEK_SET, os.SEEK_CUR, os.SEEK_END]: raise IOError() self._file_object.seek(offset, whence)
Seeks to an offset within the file-like object. Args: offset (int): offset to seek to. whence (Optional(int)): value that indicates whether offset is an absolute or relative position within the file. Raises: IOError: if the seek failed. OSError: if the seek failed.
340,701
def get_or_guess_paths_to_mutate(paths_to_mutate): if paths_to_mutate is None: this_dir = os.getcwd().split(os.sep)[-1] if isdir(): return elif isdir(): return elif isdir(this_dir): return this_dir elif isdir(this_dir.replac...
:type paths_to_mutate: str or None :rtype: str
340,702
def create(self, article, attachment, inline=False, file_name=None, content_type=None): return HelpdeskAttachmentRequest(self).post(self.endpoint.create, article=article, attachments=attachment, ...
This function creates attachment attached to article. :param article: Numeric article id or :class:`Article` object. :param attachment: File object or os path to file :param inline: If true, the attached file is shown in the dedicated admin UI for inline attachments and its url can ...
340,703
def expect(*exprs): if len(exprs) == 2 and (isinstance(exprs[0], (bool, np.bool_)) and isinstance(exprs[1], str)): if not exprs[0]: _log_failure(arg_num=0, msg=exprs[1]) else: for i, arg in enumerate(exprs): if isinstance(arg, (bool, np.bool_)): ...
Tests given sequence of conditions and stores results. Parameters ---------- exprs: bool or tuple of (bool, str) Variable number of expressions evaluated. If a tuple first element is expression evaluated, second is the message displayed on failure in the report.
340,704
def call_json(self, req_json, props=None): try: req = json.loads(req_json) except: msg = "Unable to parse JSON: %s" % req_json return json.dumps(err_response(None, -32700, msg)) return json.dumps(self.call(req, props))
Deserializes req_json as JSON, invokes self.call(), and serializes result to JSON. Returns JSON encoded string. :Parameters: req_json JSON-RPC request serialized as JSON string props Application defined properties to set on RequestContext for use with filters...
340,705
def _connect(self): if self.recvConn: if self.pid != os.getpid(): raise UseAfterFork( "do not re-use a connection after fork; open a new client instead" ) return if self.sockpath is None: self.sockpath = s...
establish transport connection
340,706
def _dump_text(self): results = self._relay_output[]; for l in results: dt = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(int(l[1][]))) print("{0} {1} {2} {3}".format(l[0], dt, l[1][], l[1][]))
Send output in textual format
340,707
def show_data_file(fname): txt = + fname + print (fname) txt += web.read_csv_to_html_table(fname, ) txt += return txt
shows a data file in CSV format - all files live in CORE folder
340,708
def addFeatureSet(self): self._openRepo() dataset = self._repo.getDatasetByName(self._args.datasetName) filePath = self._getFilePath(self._args.filePath, self._args.relativePath) name = getNameFromPath(self._args.filePath) featureSet ...
Adds a new feature set into this repo
340,709
def is_focused(self): active_el = self.browser.execute_script("return document.activeElement") query_results = self.map(lambda el: el == active_el, ).results if query_results: return any(query_results) return False
Checks that *at least one* matched element is focused. More specifically, it checks whether the element is document.activeElement. If no matching element is focused, this returns `False`. Returns: bool
340,710
def log_sum_exp(self,x, axis): x_max = np.max(x, axis=axis) if axis == 1: return x_max + np.log( np.sum(np.exp(x-x_max[:,np.newaxis]), axis=1) ) else: return x_max + np.log( np.sum(np.exp(x-x_max), axis=0) )
Compute the log of a sum of exponentials
340,711
def thing(random=random, *args, **kwargs): def noun_or_adjective_noun(): if random.choice([True, False]): return noun(random=random) else: return adjective(random=random) + " " + noun(random=random) def plural_or_adjective_plural(): if random.choice([True, ...
Return a ... thing. >>> mock_random.seed(0) >>> thing(random=mock_random) 'two secrets' >>> mock_random.seed(1) >>> thing(random=mock_random, capitalize=True) 'Mighty Poop' >>> mock_random.seed(2) >>> thing(random=mock_random, slugify=True) 'poop' >>> mock_random.seed(4) >>>...
340,712
def search_fetch_force(request, id, redirect_to): search = Search.objects.get(id=id) search.fetch(force=True) msg = _("Fetched tweets for %s" % search.criteria) messages.success(request, msg, fail_silently=True) return HttpResponseRedirect(redirect_to)
Forcibly fetch tweets for the search
340,713
def _blackbox_partial_noise(blackbox, system): node_tpms = [] for node in system.nodes: node_tpm = node.tpm_on for input_node in node.inputs: if blackbox.hidden_from(input_node, node.index): node_tpm = marginalize_out([input_n...
Noise connections from hidden elements to other boxes.
340,714
def write(self, attr_name, prefix=None): s value to a file. :param str attr_name: Attributes name that is prefixed to logging message, defaults to ``None``. :returns: message written to file :rtype: str __iter__a') as f: f.write("{}\n".format...
Write attribute's value to a file. :param str attr_name: Attribute's name to be logged :param str prefix: Optional. Attribute's name that is prefixed to logging message, defaults to ``None``. :returns: message written to file :rtype: str
340,715
def did_u_mean(name): logger.debug("%s", name) dlist = Repo.installed_list() res = [] for d in dlist: if name in d.name or d.name in name: res.append(nice_pkg_name(d.name)) if res: return "Did you mean ?" return ""
todo: Docstring for did_u_mean :param name: arg description :type name: type description :return: :rtype:
340,716
def create(self, volume_id, backup_id): backup_id = backup_id or str(uuid.uuid4()) return self.http_put( % backup_id, params={: volume_id})
create a backup
340,717
def method_name(self): if isinstance(self.view_func, str): return self.view_func return self.view_func.__name__
The string name of this route's view function.
340,718
def add_noise(data, sigma=1.0, noise_type=): r data = np.array(data) if noise_type not in (, ): raise ValueError( ) if isinstance(sigma, (list, tuple, np.ndarray)): if len(sigma) != data.shape[0]: raise ValueError( ) ...
r"""Add noise to data This method adds Gaussian or Poisson noise to the input data Parameters ---------- data : np.ndarray, list or tuple Input data array sigma : float or list, optional Standard deviation of the noise to be added ('gauss' only) noise_type : str {'gauss', 'pois...
340,719
def _order_pases(self, passes): passes = set(passes) pass_deps = {} for opt in passes: _, before, after = self._known_passes[opt] if opt not in pass_deps: pass_deps[opt] = set() for after_pass in after: pass_deps[o...
Topologically sort optimization passes. This ensures that the resulting passes are run in order respecting before/after constraints. Args: passes (iterable): An iterable of pass names that should be included in the optimization passes run.
340,720
def get_memory_percent(self): rss = self._platform_impl.get_memory_info()[0] try: return (rss / float(TOTAL_PHYMEM)) * 100 except ZeroDivisionError: return 0.0
Compare physical system memory to process resident memory and calculate process memory utilization as a percentage.
340,721
def connect(self, **kwargs): t exist it is created first via :func:`create`. **Configuration Parameters** host The host for the connection. Passed as either the config key **database.host** or the kwargs argument **host**. Defaults to **localhost**. port ...
Connect to an InfluxDB instance Connects to an InfluxDB instance and switches to a given database. If the database doesn't exist it is created first via :func:`create`. **Configuration Parameters** host The host for the connection. Passed as either the config key *...
340,722
def ekopn(fname, ifname, ncomch): fname = stypes.stringToCharP(fname) ifname = stypes.stringToCharP(ifname) ncomch = ctypes.c_int(ncomch) handle = ctypes.c_int() libspice.ekopn_c(fname, ifname, ncomch, ctypes.byref(handle)) return handle.value
Open a new E-kernel file and prepare the file for writing. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekopn_c.html :param fname: Name of EK file. :type fname: str :param ifname: Internal file name. :type ifname: str :param ncomch: The number of characters to reserve for comments. ...
340,723
def _index_put(self, idx_name, *ids_and_fcs): keys = self._index_keys_for(idx_name, *ids_and_fcs) with_vals = map(lambda k: (k, ), keys) self.kvl.put(self.INDEX_TABLE, *with_vals)
Add new index values. Adds new index values for index ``idx_name`` for the pairs given. Each pair should be a content identifier and a :class:`dossier.fc.FeatureCollection`. :type idx_name: unicode :type ids_and_fcs: ``[(content_id, FeatureCollection)]``
340,724
def run_update(self, template_name=None, service_dir=None): " Run update scripts. " LOGGER.info() print_header( % self.get_name()) map(call, self._gen_scripts( , template_name=template_name, service_dir=service_dir)) LOGGER.info() return True
Run update scripts.
340,725
def get_tx(tx_id, api_code=None): resource = + tx_id if api_code is not None: resource += + api_code response = util.call_api(resource) json_response = json.loads(response) return Transaction(json_response)
Get a single transaction based on a transaction hash. :param str tx_id: transaction hash to look up :param str api_code: Blockchain.info API code (optional) :return: an instance of :class:`Transaction` class
340,726
def rpc(cmd=None, dest=None, **kwargs): device<configuration><system/></configuration>devicelo0device conn = __proxy__[]() ret = {} ret[] = True if cmd is None: ret[] = ret[] = False return ret format_ = kwargs.pop(, ) if not format_: format_ = op = ...
This function executes the RPC provided as arguments on the junos device. The returned data can be stored in a file. cmd The RPC to be executed dest Destination file where the RPC output is stored. Note that the file will be stored on the proxy minion. To push the files to the mast...
340,727
def get_sds_by_name(self,name): for sds in self.sds: if sds.name == name: return sds raise KeyError("SDS of that name not found")
Get ScaleIO SDS object by its name :param name: Name of SDS :return: ScaleIO SDS object :raise KeyError: No SDS with specified name found :rtype: SDS object
340,728
def makefifo(self, tarinfo, targetpath): if hasattr(os, "mkfifo"): os.mkfifo(targetpath) else: raise ExtractError("fifo not supported by system")
Make a fifo called targetpath.
340,729
def maximal(iterable, comparison=operator.lt, _groupkey=operator.itemgetter(0)): iterable = set(iterable) if len(iterable) < 2: return iterable return (item for item, pairs in groupby(permutations(iterable, 2), key=_groupkey) if not any(starmap(comparison, pairs)))
Yield the unique maximal elements from ``iterable`` using ``comparison``. >>> list(maximal([1, 2, 3, 3])) [3] >>> list(maximal([1])) [1]
340,730
def delete_credit_card(self, *, customer_id, credit_card_id): fmt = .format(customer_id, credit_card_id) return self.client._delete(self.url + fmt, headers=self.get_headers())
Delete a credit card (Token) associated with a user. Args: customer_id: Identifier of the client of whom you are going to delete the token. credit_card_id: Identifier of the token to be deleted. Returns:
340,731
def _copy_project(self, project, new_project_name, path_filter): temp_directory = tempfile.mkdtemp() new_project_name_or_id = ProjectNameOrId.create_from_name(new_project_name) remote_project = self.remote_store.fetch_remote_project(new_project_name_or_id) if remote_project: ...
Copy pre-existing project with name project_name to non-existing project new_project_name. :param project: remotestore.RemoteProject project to copy from :param new_project_name: str project to copy to :param path_filter: PathFilter: filters what files are shared :return: RemoteProject n...
340,732
def calc_loss(self, embedding): Hnew = self.compute_dual_rmetric(Ynew=embedding) return self.rieman_loss(Hnew=Hnew)
Helper function to calculate rieman loss given new embedding
340,733
def order_to_dict(order): default = Order() return {field: val for field, val in vars(order).items() if val != getattr(default, field, None)}
Convert an IBPy Order object to a dict containing any non-default values.
340,734
def build_scandata_table(self): shape = self._norm_vals.shape col_norm = Column(name="norm", dtype=float) col_normv = Column(name="norm_scan", dtype=float, shape=shape) col_dll = Column(name="dloglike_scan", dtype=float, shape=...
Build an `astropy.table.Table` object from these data.
340,735
def load_symbols_elf(filename): f = open(filename, ) elffile = ELFFile(f) symbols = [] for section in elffile.iter_sections(): if not isinstance(section, SymbolTableSection): continue if section[] == 0: logger.warn("Symbol table {} has a sh_entsize of zer...
Load the symbol tables contained in the file
340,736
def compute_grouped_metric(ungrouped_metric, group_matrix): group_matrix = np.array(group_matrix, dtype=np.bool) mu_star_masked = np.ma.masked_array(ungrouped_metric * group_matrix.T, mask=(group_matrix ^ 1).T) mean_of_mu_star = np.ma.mean(mu_star_masked, axis=...
Computes the mean value for the groups of parameter values in the argument ungrouped_metric
340,737
def remove(self, elem): try: return self._collection.remove(elem) except KeyError: raise KeyError(" was not found in the {}: .".format(elem, type(self).__name__, self)) from None
Removes _elem_ from the collection, will raise a KeyError is _elem_ is missing # Parameters _elem_ : `object` > The object to be removed
340,738
def update_hit_count_ajax(request, *args, **kwargs): warnings.warn( "hitcount.views.update_hit_count_ajax is deprecated. " "Use hitcount.views.HitCountJSONView instead.", RemovedInHitCount13Warning ) view = HitCountJSONView.as_view() return view(request, *args, **kwargs)
Deprecated in 1.2. Use hitcount.views.HitCountJSONView instead.
340,739
def get_module_name(module: types.ModuleType) -> str: try: return module.__spec__.name except AttributeError: return module.__name__
Returns the name of the specified module by looking up its name in multiple ways to prevent incompatibility issues. :param module: A module object for which to retrieve the name.
340,740
def get_suite_token(self, suite_id, suite_secret, suite_ticket): return self._post( , data={ : suite_id, : suite_secret, : suite_ticket } )
获取第三方应用凭证 https://work.weixin.qq.com/api/doc#90001/90143/9060 :param suite_id: 以ww或wx开头应用id(对应于旧的以tj开头的套件id) :param suite_secret: 应用secret :param suite_ticket: 企业微信后台推送的ticket :return: 返回的 JSON 数据包
340,741
def _validate_timeout(cls, value, name): if value is _Default: return cls.DEFAULT_TIMEOUT if value is None or value is cls.DEFAULT_TIMEOUT: return value if isinstance(value, bool): raise ValueError("Timeout cannot be a boolean value. It must " ...
Check that a timeout attribute is valid. :param value: The timeout value to validate :param name: The name of the timeout attribute to validate. This is used to specify in error messages. :return: The validated and casted version of the given value. :raises ValueError: If it...
340,742
def extrema(self, t0, t1 = None, partition = 2400.0): if t1: for e in takewhile(lambda t: t[0] < t1, self.extrema(t0)): yield e else: delta = np.amin([ 90.0 / c.speed(astro(t0)) for c in self.model[] if not c.speed(astro(t0)) == 0 ]) offset = 24.0 partitions = ( Tid...
A generator for high and low tides. Arguments: t0 -- time after which extrema are sought t1 -- optional time before which extrema are sought (if not given, the generator is infinite) partition -- number of hours for which we consider the node factors to be constant (default: 2400.0)
340,743
def transfer_funds(self, to, amount, denom, msg): try: self.steem_instance().commit.transfer(to, float(amount), denom, msg, self.mainaccount) except Exception as e: self.msg.error_message(e) return False else: return True
Transfer SBD or STEEM to the given account
340,744
def calc_allowedremoterelieve_v1(self): flu = self.sequences.fluxes.fastaccess log = self.sequences.logs.fastaccess flu.allowedremoterelieve = log.loggedallowedremoterelieve[0]
Get the allowed remote relieve of the last simulation step. Required log sequence: |LoggedAllowedRemoteRelieve| Calculated flux sequence: |AllowedRemoteRelieve| Basic equation: :math:`AllowedRemoteRelieve = LoggedAllowedRemoteRelieve` Example: >>> from hydpy.models.dam imp...
340,745
def _paramschecker(self, param, newvalue): if param == : allowed = assemble.write_outfiles.OUTPUT_FORMATS.keys() if isinstance(newvalue, str): newvalue = newvalue.replace(",", "").replace(" ", "") newvalue = list(newvalue) ...
Raises exceptions when params are set to values they should not be
340,746
def getFcpDevices(rh): rh.printSysLog("Enter getHost.getFcpDevices") parms = ["-T", "dummy"] results = invokeSMCLI(rh, "System_WWPN_Query", parms) if results[] == 0: rh.printLn("N", results[]) else: rh.printLn("ES", results[]) rh.updateResults(results) ...
Lists the FCP device channels that are active, free, or offline. Input: Request Handle with the following properties: function - 'GETHOST' subfunction - 'FCPDEVICES' Output: Request Handle updated with the results. Return code - 0: ok, non-zero: error
340,747
def joint_hex(x, y, **kwargs): return sns.jointplot( x, y, kind=, stat_func=None, marginal_kws={: True}, **kwargs )
Seaborn Joint Hexplot with marginal KDE + hists.
340,748
def filter_merged_pull_requests(self, pull_requests): if self.options.verbose: print("Fetching merge date for pull requests...") closed_pull_requests = self.fetcher.fetch_closed_pull_requests() if not pull_requests: return [] pulls = copy.deepcopy(pull_...
This method filter only merged PR and fetch missing required attributes for pull requests. Using merged date is more correct than closed date. :param list(dict) pull_requests: Pre-filtered pull requests. :rtype: list(dict) :return:
340,749
def disable_gui(self): gui = self._current_gui if gui in self.apps: self.apps[gui]._in_event_loop = False return self.clear_inputhook()
Disable GUI event loop integration. If an application was registered, this sets its ``_in_event_loop`` attribute to False. It then calls :meth:`clear_inputhook`.
340,750
def pop(self): method_frame, header, body = self.server.basic_get(queue=self.key) if body: return self._decode_request(body)
Pop a request
340,751
def _dfs_usb_info(obj, parents): output = {} if ( "BSD Name" in obj and obj["BSD Name"].startswith("disk") and mbed_volume_name_match.search(obj["IORegistryEntryName"]) ): disk_id = obj["BSD Name"] usb_info = {"serial": None} for parent in [obj] + parents...
Find all of the usb info that we can from this particular IORegistry tree with depth first search (and searching the parent stack....)
340,752
def load_class(module_name, class_name): try: plugmod = import_module(module_name) except Exception as exc: warn("Importing built-in plugin %s.%s raised an exception: %r" % (module_name, class_name, repr(exc)), ImportWarning) return None else: return getattr...
Return class object specified by module name and class name. Return None if module failed to be imported. :param module_name: string module name :param class_name: string class name
340,753
def _filter_attribute(mcs, attribute_name, attribute_value): if attribute_name == : return True elif hasattr(attribute_value, ): return True return False
decides whether the given attribute should be excluded from tracing or not
340,754
def _rnaseq_checkpoints(samples): checkpoints = {} checkpoints["rnaseq"] = True checkpoints["vc"] = any([dd.get_variantcaller(d) for d in samples]) return checkpoints
Check sample configuration to identify required steps in analysis.
340,755
def open_(environment, opts): environment.require_data() addr = environment.web_address() if not addr: print "Site not currently running" else: webbrowser.open(addr)
Open web browser window to this environment Usage: datacats open [-r] [-s NAME] [ENVIRONMENT] Options: -s --site=NAME Choose a site to open [default: primary] ENVIRONMENT may be an environment name or a path to an environment directory. Default: '.'
340,756
def geometric_series(q, n): q = np.asarray(q) if n < 0: raise ValueError() else: if q.ndim == 0: if q == 1: s = (n + 1) * 1.0 return s else: s = (1.0 - q ** (n + 1)) / (1.0 - q) return s ...
Compute finite geometric series. \frac{1-q^{n+1}}{1-q} q \neq 1 \sum_{k=0}^{n} q^{k}= n+1 q = 1 Parameters ---------- q : array-like The common ratio of the geometric series. n : int The num...
340,757
def duplicate(self): instance = self.__class__(identifier=self.identifier, name=self.name, description=self.description, currency=self.currency, status=self.status, date=self.date, due_date=self.due_da...
Returns a copy of the current group, including its lines. @returns: Group
340,758
def _get_codename(self, pathname, basename): file_py = pathname + ".py" file_pyc = pathname + ".pyc" file_pyo = pathname + ".pyo" if os.path.isfile(file_pyo) and \ os.stat(file_pyo).st_mtime >= os.stat(file_py).st_mtime: fname = file_pyo ...
Return (filename, archivename) for the path. Given a module name path, return the correct file path and archive name, compiling if necessary. For example, given /python/lib/string, return (/python/lib/string.pyc, string).
340,759
def get(self): self.clean() for _ in range(len(self.queue)): (conn, _) = self.queue.pop(0) if self._conn_ready(conn): return conn else: self.put(conn) return None
Returns the next connection in this pool that is ready to be reused. Returns None of there aren't any.
340,760
def get_rfc3339(when): microseconds = format(when.microsecond, )[:4] rfc3339 = return when.strftime(rfc3339.format(microseconds))
Return an RFC 3339 timestamp. :param datetime.datetime when: a datetime in UTC :return: RFC 3339 timestamp :rtype: str
340,761
def sort(ctx): head = ctx.parent.head vcf_handle = ctx.parent.handle outfile = ctx.parent.outfile silent = ctx.parent.silent print_headers(head, outfile=outfile, silent=silent) for line in sort_variants(vcf_handle): print_variant(variant_line=line, outfile=outfile, silent=silent)
Sort the variants of a vcf file
340,762
def of(cls, *documents: BioCDocument): if len(documents) <= 0: raise ValueError("There has to be at least one document.") c = BioCCollection() for document in documents: if document is None: raise ValueError() c.add_document(document) ...
Returns a collection documents
340,763
def delete(key, service=None, profile=None): client = _get_conn(profile) try: client.delete(key) return True except Exception: return False
Get a value from the etcd service
340,764
def simple_logger( name=, config=, log_level=logging.INFO, log_config_path=None, handler_name=, handlers_dict=None, enable_splunk=False, splunk_user=None, splunk_password=None, splunk_address=None, splunk_api_address=None, s...
simple_logger Build a colorized logger for just the message - Used by command line tools. :param name: name that shows in the logger :param config: name of the config file :param log_level: level to log :param log_config_path: path to log config file :param handler_name: handler name in th...
340,765
def dskgd(handle, dladsc): handle = ctypes.c_int(handle) dskdsc = stypes.SpiceDSKDescr() libspice.dskgd_c(handle, ctypes.byref(dladsc), ctypes.byref(dskdsc)) return dskdsc
Return the DSK descriptor from a DSK segment identified by a DAS handle and DLA descriptor. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskgd_c.html :param handle: Handle assigned to the opened DSK file. :type handle: int :param dladsc: DLA segment descriptor. :type dladsc: spicey...
340,766
def refresh_token(self, client_id, client_secret, refresh_token, grant_type=): return self.post( .format(self.domain), data={ : client_id, : client_secret, : refresh_token, : grant_type }, h...
Calls oauth/token endpoint with refresh token grant type Use this endpoint to refresh an access token, using the refresh token you got during authorization. Args: grant_type (str): Denotes the flow you're using. For refresh token use refresh_token client_id (str): ...
340,767
def qteAbort(self, msgObj): self.qteWidget.setCursorPosition(*self.cursorPosOrig) self.qteMain.qtesigAbort.disconnect(self.qteAbort)
Restore the original cursor position because the user hit abort.
340,768
def calc_bin(self, _bin=None): if _bin is None: try: _bin = bins.bins(self.start, self.end, one=True) except TypeError: _bin = None return _bin
Calculate the smallest UCSC genomic bin that will contain this feature.
340,769
def create_from_hash(self, stream, name, output_type, output_params, initial_status=None, start=None, end=None): return self._create(True, stream, name, output_type, output_params, initial_status, start, end)
Create a new push subscription using a live stream. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushcreate :param stream: The hash of a DataSift stream. :type stream: str :param name: The name to give the newly created subscription ...
340,770
def fill_traversals(traversals, edges, edges_hash=None): edges = np.asanyarray(edges, dtype=np.int64) edges.sort(axis=1) if len(traversals) == 0: return edges.copy() if edges_hash is None: edges_hash = grouping.hashable_rows(edges) splits = [] for node...
Convert a traversal of a list of edges into a sequence of traversals where every pair of consecutive node indexes is an edge in a passed edge list Parameters ------------- traversals : sequence of (m,) int Node indexes of traversals of a graph edges : (n, 2) int Pairs of connected...
340,771
def do_mailfy(self, query): from bs4 import BeautifulSoup r = br.open() br.select_form(nr=0) br.form["session_key"] = query br.form["session_password"] = "123456" br.submit() respuestaURL = br.response().geturl() if "captcha" in respuesta...
Verifying a mailfy query in this platform. This might be redefined in any class inheriting from Platform. The only condition is that any of this should return an equivalent array. Args: ----- query: The element to be searched. Return: ------- A ...
340,772
def string(self) -> bytes: if self._raw is not None: return self._raw self._raw = raw = BytesFormat(b).join( [b, b] + self.capabilities) return raw
The capabilities string without the enclosing square brackets.
340,773
def load_balancers_list_all(**kwargs): result = {} netconn = __utils__[](, **kwargs) try: load_balancers = __utils__[](netconn.load_balancers.list_all()) for load_balancer in load_balancers: result[load_balancer[]] = load_balancer except CloudError as exc: __uti...
.. versionadded:: 2019.2.0 List all load balancers within a subscription. CLI Example: .. code-block:: bash salt-call azurearm_network.load_balancers_list_all
340,774
def _get_order_by(order, orderby, order_by_fields): try: db_fieldnames = order_by_fields[orderby] except KeyError: raise ValueError("Invalid value for : , supported values are: {1}".format(orderby, .join(sorted(order_by_fields.keys())))) is_desc = (not order and orderby i...
Return the order by syntax for a model. Checks whether use ascending or descending order, and maps the fieldnames.
340,775
def is_empty(self): ps = self.p_lst if len(ps) > 1: return False if not ps: raise InvalidXmlError() if ps[0].text != : return False return True
True if only a single empty `a:p` element is present.
340,776
def execute(self, override_wf_json=None): r = self.gbdx.post( self.URL, json=self.json if override_wf_json is None else override_wf_json ) try: r.raise_for_status() except: print("GBDX API Status Code: %s" % r.status_code) ...
Execute the cloud_harness task.
340,777
def f_delete_item(self, item, *args, **kwargs): self.f_delete_items([item], *args, **kwargs)
Deletes a single item, see :func:`~pypet.trajectory.Trajectory.f_delete_items`
340,778
def _unstructure_mapping(self, mapping): dispatch = self._unstructure_func.dispatch return mapping.__class__( (dispatch(k.__class__)(k), dispatch(v.__class__)(v)) for k, v in mapping.items() )
Convert a mapping of attr classes to primitive equivalents.
340,779
def compact(vertices, indices, tolerance=1e-3): n = len(vertices) V = np.zeros(n, dtype=[("pos", np.float32, 3)]) V["pos"][:, 0] = vertices[:, 0] V["pos"][:, 1] = vertices[:, 1] V["pos"][:, 2] = vertices[:, 2] epsilon = 1e-3 decimals = int(np.log(epsilon)/np.log(1/10.)) ...
Compact vertices and indices within given tolerance
340,780
def parse_net_kwargs(kwargs): if not kwargs: return kwargs resolved = {} for k, v in kwargs.items(): resolved[k] = _resolve_dotted_name(v) return resolved
Parse arguments for the estimator. Resolves dotted names and instantiated classes. Examples -------- >>> kwargs = {'lr': 0.1, 'module__nonlin': 'torch.nn.Hardtanh(-2, max_val=3)'} >>> parse_net_kwargs(kwargs) {'lr': 0.1, 'module__nonlin': Hardtanh(min_val=-2, max_val=3)}
340,781
def stream_chats_missed_chats_list(self, window=None, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/apis api_path = "/stream/chats/missed_chats" api_query = {} if "query" in kwargs.keys(): api_query.update(kwargs["query"]) del kwargs["query"] ...
https://developer.zendesk.com/rest_api/docs/chat/apis#example-response
340,782
def draw(self): self.guess_header() self.add_left_space( ) if self._title and self._descr: pre = self._title + + self._descr + elif self._title: pre = self._title + elif self._descr: pre = + + self._descr...
generate texttable formatted string
340,783
def properties(obj): return dict((attr, getattr(obj, attr)) for attr in dir(obj) if not attr.startswith())
Returns a dictionary with one entry per attribute of the given object. The key being the attribute name and the value being the attribute value. Attributes starting in two underscores will be ignored. This function is an alternative to vars() which only returns instance variables, not properties. Note that ...
340,784
def mod(x, y, context=None): return _apply_function_in_current_context( BigFloat, mpfr_mod, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
Return the remainder of x divided by y, with sign matching that of y.
340,785
def patchFile(filename, replacements): patched = Utility.readFile(filename) for key in replacements: patched = patched.replace(key, replacements[key]) Utility.writeFile(filename, patched)
Applies the supplied list of replacements to a file
340,786
def has_chosen(state, correct, msgs): ctxt = {} exec(state.student_code, globals(), ctxt) sel_indx = ctxt["selected_option"] if sel_indx != correct: state.report(Feedback(msgs[sel_indx - 1])) else: state.reporter.success_msg = msgs[correct - 1] return state
Verify exercises of the type MultipleChoiceExercise Args: state: State instance describing student and solution code. Can be omitted if used with Ex(). correct: index of correct option, where 1 is the first option. msgs : list of feedback messages corresponding to each option. ...
340,787
def datasets_insert(self, dataset_name, friendly_name=None, description=None): url = Api._ENDPOINT + (Api._DATASETS_PATH % (dataset_name.project_id, )) data = { : , : { : dataset_name.project_id, : dataset_name.dataset_id }, } if friendly_name: ...
Issues a request to create a dataset. Args: dataset_name: the name of the dataset to create. friendly_name: (optional) the friendly name for the dataset description: (optional) a description for the dataset Returns: A parsed result object. Raises: Exception if there is an erro...
340,788
def get_vlan_brief_output_vlan_vlan_id(self, **kwargs): config = ET.Element("config") get_vlan_brief = ET.Element("get_vlan_brief") config = get_vlan_brief output = ET.SubElement(get_vlan_brief, "output") vlan = ET.SubElement(output, "vlan") vlan_id = ET.SubEleme...
Auto Generated Code
340,789
def before_render(self): super(FolderView, self).before_render() self.request.set("disable_border", 1) self.selected_state = self.get_selected_state() self.allow_edit = self.is_edit_allowed() self.can_manage = self.is_manage_allowed() ...
Before render hook of the listing base view
340,790
def delete(self, url, headers=None, kwargs=None): return self._request( method=, url=url, headers=headers, kwargs=kwargs )
Make a DELETE request. To make a DELETE request pass, ``url`` :param url: ``str`` :param headers: ``dict`` :param kwargs: ``dict``
340,791
async def post_publish(request): args = await request.json() try: await get_publisher(request.app).publish( args[], args[], args[] ) return web.Response() except Exception as ex: warnings.warn(f) return web.Response(body=, sta...
--- tags: - Events summary: Publish event. description: Publish a new event message to the event bus. operationId: events.publish produces: - text/plain parameters: - in: body name: body description: Event message required: true schema: ...
340,792
def to_bool(s, fallback=None): if not s: return fallback s = s.lower() if s in ["1", "true", "yes", "y"]: return True if s in ["0", "false", "no", "n"]: return False return fallback
:param str s: str to be converted to bool, e.g. "1", "0", "true", "false" :param T fallback: if s is not recognized as a bool :return: boolean value, or fallback :rtype: bool|T
340,793
async def get_local_version(self): self._version_data["source"] = "Local" try: from homeassistant.const import __version__ as localversion self._version = localversion _LOGGER.debug("Version: %s", self.version) _LOGGER.debug("Version data: %s", ...
Get the local installed version.
340,794
def rebuild_app(app_name, quiet=False, force=True, without_exec=False, restart=False): user = .format(app_name=app_name) home = .format(prefix=PREFIX, app_name=app_name) command_line = .format(home=home) command_line += if force: command_line += command_line +=...
Rebuild cozy apps with deletion of npm directory & new npm build
340,795
def model_vis(self, context): column = self._vis_column msshape = None try: coldesc = self._manager.column_descriptors[column] except KeyError as e: coldesc = None if coldesc is not None: try: msshap...
model visibility data sink
340,796
def restore_db_cluster_from_snapshot(AvailabilityZones=None, DBClusterIdentifier=None, SnapshotIdentifier=None, Engine=None, EngineVersion=None, Port=None, DBSubnetGroupName=None, DatabaseName=None, OptionGroupName=None, VpcSecurityGroupIds=None, Tags=None, KmsKeyId=None, EnableIAMDatabaseAuthentication=None): ...
Creates a new DB cluster from a DB cluster snapshot. The target DB cluster is created from the source DB cluster restore point with the same configuration as the original source DB cluster, except that the new DB cluster is created with the default security group. For more information on Amazon Aurora, see Aurora o...
340,797
def nmap(a, b, c, d, curvefn=None, normfn=None): if not curvefn: curvefn = lambda x: x def map(n): r = 1.0 * (n - a) / (b - a) out = curvefn(r) * (d - c) + c if not normfn: return out return normfn(out) return map
Returns a function that maps a number n from range (a, b) onto a range (c, d). If no curvefn is given, linear mapping will be used. Optionally a normalisation function normfn can be provided to transform output.
340,798
def _get_index(self): glyph = self.glyph if glyph is None: return None return glyph.anchors.index(self)
Get the anchor's index. This must return an ``int``. Subclasses may override this method.
340,799
def check_valid_keys(self, obj): invalid_keys = [ x for x in obj if x not in self.defaults ] if invalid_keys: raise ValueError( "No such model parameters: %s. Valid parameters are: %s" % (" ".join(invalid_keys), ...
Given a dict of hyperparameter settings, throw an exception if any keys are not defined in this HyperparameterDefaults instance.