Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
346,700 | def _track_changes(self):
if self._field and getattr(self._parent, ,
None) is not None:
self._parent._track_changes.add(self._field) | Update the track_changes on the parent to reflect a
needed update on this field |
346,701 | def update_service_endpoints(self, endpoints, project):
route_values = {}
if project is not None:
route_values[] = self._serialize.url(, project, )
content = self._serialize.body(endpoints, )
response = self._send(http_method=,
location_... | UpdateServiceEndpoints.
[Preview API] Update the service endpoints.
:param [ServiceEndpoint] endpoints: Names of the service endpoints to update.
:param str project: Project ID or project name
:rtype: [ServiceEndpoint] |
346,702 | def iterRun(self, sqlTail = , raw = False) :
sql, sqlValues = self.getSQLQuery()
cur = self.con.execute(% (sql, sqlTail), sqlValues)
for v in cur :
if not raw :
yield RabaPupa(self.rabaClass, v[0])
else :
yield v | Compile filters and run the query and returns an iterator. This much more efficient for large data sets but
you get the results one element at a time. One thing to keep in mind is that this function keeps the cursor open, that means that the sqlite databae is locked (no updates/inserts etc...) until all
the element... |
346,703 | def get_assignment(self, assignment_id):
try:
response = self.mturk.get_assignment(AssignmentId=assignment_id)
except ClientError as ex:
if "does not exist" in str(ex):
return None
raise
return self._translate_assignment(response["Assi... | Get an assignment by ID and reformat the response. |
346,704 | def cufflinks(args):
p = OptionParser(cufflinks.__doc__)
p.add_option("--gtf", help="Reference annotation [default: %default]")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
folder, reference = args
cpus = opts.cpus
gtf = opts... | %prog cufflinks folder reference
Run cufflinks on a folder containing tophat results. |
346,705 | def get_transcript_lengths(ensembl, transcript_ids):
transcripts = {}
for transcript_id in transcript_ids:
try:
seq = ensembl.get_protein_seq_for_transcript(transcript_id)
except ValueError:
continue
transcripts[transcript_id] = len(seq... | finds the protein length for ensembl transcript IDs for a gene
Args:
ensembl: EnsemblRequest object to request sequences and data
from the ensembl REST API
transcript_ids: list of transcript IDs for a single gene
Returns:
dictionary of lengths (in amino acids), inde... |
346,706 | def do_send_mail(self, is_ssl, mail_to_list, subject, content, file_name_list):
if is_ssl:
smtp = smtplib.SMTP_SSL(self.smtp_server, self.smtp_port)
else:
smtp = smtplib.SMTP(self.smtp_server, self.smtp_port)
smtp.ehlo(name=)
smtp.login(... | 发送邮件
:param is_ssl: 使用SSL的方式发生
:param mail_to_list: 收件人列表
:param subject: 邮件主题
:param content: 邮件正文
:param file_name_list: 附近的文件路径列表
:return: |
346,707 | def strip_comments(code):
single_comment = compile()
multi_comment = compile(, re.DOTALL)
code = sub(single_comment, , code)
code = sub(multi_comment, , code)
return .join([c for c in code.splitlines() if c.strip()]) | Returns the headers with comments removed. |
346,708 | def snapshot(self) -> Tuple[Hash32, UUID]:
return self.state_root, self._account_db.record() | Perform a full snapshot of the current state.
Snapshots are a combination of the :attr:`~state_root` at the time of the
snapshot and the id of the changeset from the journaled DB. |
346,709 | def get_ilx2superclass(self, clean:bool=True):
ilx2superclass = defaultdict(list)
header = [] + list(self.fetch_superclasses().columns)
for row in self.fetch_superclasses().itertuples():
row = {header[i]:val for i, val in enumerate(row)}
if clean:
... | clean: for list of literals only |
346,710 | def permissions(self, course_id, permissions=None):
path = {}
data = {}
params = {}
path["course_id"] = course_id
if permissions is not None:
params["permissions"] = permissions
self.logger.debug("GE... | Permissions.
Returns permission information for provided course & current_user |
346,711 | def taax(mt, x, t, m=1):
return mt.Nx[x + t] / mt.Dx[x] - ((float(m - 1) / float(m * 2)) * (1 - nEx(mt, x, t))) | n/äx : Return the actuarial present value of a deferred annuity (deferred n years):
n-year deferred whole life annuity-anticipatory. Payable 'm' per year at the beginning of the period |
346,712 | def exec_request(self, URL):
interval = time.time() - self.__ts_last_req
if (interval < self.__min_req_interval):
time.sleep( self.__min_req_interval - interval )
headers = {
"X-ELS-APIKey" : self.api_key,
"User-Agent" ... | Sends the actual request; returns response. |
346,713 | def execute(cls, executable, *arguments, **kwargs):
echo = kwargs.pop(, False)
return cls(ProcessChannel(executable, *arguments, **kwargs), echo=echo) | execute(executable, argument..., redirect_stderr=False, echo=False):
Set up a :class:`ProcessChannel` and create a :class:`Flow` instance
for it.
Args:
executable(str): The executable to start.
argument...(list of str): The arguments to pass to the executable.
... |
346,714 | def get_samples(self, init_points_count, criterion=):
samples = np.empty((init_points_count, self.space.dimensionality))
random_design = RandomDesign(self.space)
random_design.fill_noncontinous_variables(samples)
if self.space.has_continuous():
bounds = se... | Generates required amount of sample points
:param init_points_count: Number of samples to generate
:param criterion: For details of the effect of this parameter, please refer to pyDOE.lhs documentation
Default: 'center'
:returns: Generated samples |
346,715 | def from_dict(cls, raw_data, **kwargs):
instance = cls()
instance.populate(raw_data, **kwargs)
instance.validate(**kwargs)
return instance | This factory for :class:`Model` creates a Model from a dict object. |
346,716 | def get_all_ids(idVendor = GrizzlyUSB.ID_VENDOR, idProduct=GrizzlyUSB.ID_PRODUCT):
all_dev = GrizzlyUSB.get_all_usb_devices(idVendor, idProduct)
if len(all_dev) <= 0:
raise usb.USBError("Could not find any GrizzlyBear device (idVendor=%d, idProduct=%d)" % (idVendor, idP... | Scans for grizzlies that have not been bound, or constructed, and returns a list
of their id's, or motor number. |
346,717 | def GSSAuth(auth_method, gss_deleg_creds=True):
if _API == "MIT":
return _SSH_GSSAPI(auth_method, gss_deleg_creds)
elif _API == "SSPI" and os.name == "nt":
return _SSH_SSPI(auth_method, gss_deleg_creds)
else:
raise ImportError("Unable to import a GSS-API / SSPI module!") | Provide SSH2 GSS-API / SSPI authentication.
:param str auth_method: The name of the SSH authentication mechanism
(gssapi-with-mic or gss-keyex)
:param bool gss_deleg_creds: Delegate client credentials or not.
We delegate credentials by default.
:... |
346,718 | def ds_extent(ds, t_srs=None):
ul, ll, ur, lr = gt_corners(ds.GetGeoTransform(), ds.RasterXSize, ds.RasterYSize)
ds_srs = get_ds_srs(ds)
if t_srs is not None and not ds_srs.IsSame(t_srs):
ct = osr.CoordinateTransformation(ds_srs, t_srs)
ul ... | Return min/max extent of dataset based on corner coordinates
xmin, ymin, xmax, ymax
If t_srs is specified, output will be converted to specified srs |
346,719 | def files(self):
return [
os.path.join(self.root, label, name)
for label in self.labels
for name in os.listdir(os.path.join(self.root, label))
] | Returns the list of file names for all documents. |
346,720 | def read_by_name(adr, data_name, plc_datatype, return_ctypes=False):
if port is not None:
return adsSyncReadByNameEx(port, adr, data_name, plc_datatype, return_ctypes)
return None | Read data synchronous from an ADS-device from data name.
:param AmsAddr adr: local or remote AmsAddr
:param string data_name: data name
:param int plc_datatype: type of the data given to the PLC, according to
PLCTYPE constants
:param bool return_ctypes: return ctypes instead of python typ... |
346,721 | def model_m2m_changed(sender, instance, action, **kwargs):
if sender._meta.app_label == :
return
def notify():
table = sender._meta.db_table
if action == :
notify_observers(table, ORM_NOTIFY_KIND_CREATE)
elif action in (, ):
notify_observer... | Signal emitted after any M2M relation changes via Django ORM.
:param sender: M2M intermediate model
:param instance: The actual instance that was saved
:param action: M2M action |
346,722 | def logical_chassis_fwdl_sanity_input_user(self, **kwargs):
config = ET.Element("config")
logical_chassis_fwdl_sanity = ET.Element("logical_chassis_fwdl_sanity")
config = logical_chassis_fwdl_sanity
input = ET.SubElement(logical_chassis_fwdl_sanity, "input")
user = ET.Su... | Auto Generated Code |
346,723 | def DemangleName(self, name):
"Applies some simple heuristics to split names into (city, name)."
return (nam, SPECIAL_CITIES.get(city, city)) | Applies some simple heuristics to split names into (city, name). |
346,724 | def records0(self, tag=None):
_log.debug("in records0")
for offset, xtag in self.index0:
_log.debug(" records0: offset: %s; xtag: %s", offset, xtag)
if tag is None or tag == xtag:
yield self.read_record(offset) | Iterator over all level=0 records.
:param str tag: If ``None`` is given (default) then return all level=0
records, otherwise return level=0 records with the given tag. |
346,725 | def build(self):
self.sim = Simulation()
for component_id in self.model.targets:
if component_id not in self.model.components:
raise SimBuildError("Unable to find target component ",
component_id)
component = self.mod... | Build the simulation components from the model.
@return: A runnable simulation object
@rtype: lems.sim.sim.Simulation |
346,726 | def to_dict(self):
result = super(OptionHandler, self).to_dict()
result["type"] = "OptionHandler"
result["options"] = join_options(self.options)
return result | Returns a dictionary that represents this object, to be used for JSONification.
:return: the object dictionary
:rtype: dict |
346,727 | def eval_str(s: str, ctx: compiler.CompilerContext, module: types.ModuleType, eof: Any):
last = eof
for form in reader.read_str(s, resolver=runtime.resolve_alias, eof=eof):
last = compiler.compile_and_exec_form(form, ctx, module)
return last | Evaluate the forms in a string into a Python module AST node. |
346,728 | def has_connection(cls, pid, connection):
with cls._lock:
cls._ensure_pool_exists(pid)
return connection in cls._pools[pid] | Check to see if a pool has the specified connection
:param str pid: The pool ID
:param connection: The connection to check for
:type connection: psycopg2.extensions.connection
:rtype: bool |
346,729 | def alias_exists(aliases, indices=None, hosts=None, profile=None):
es = _get_instance(hosts, profile)
try:
return es.indices.exists_alias(name=aliases, index=indices)
except elasticsearch.exceptions.NotFoundError:
return False
except elasticsearch.TransportError as e:
raise ... | Return a boolean indicating whether given alias exists
indices
Single or multiple indices separated by comma, use _all to perform the operation on all indices.
aliases
Alias names separated by comma
CLI example::
salt myminion elasticsearch.alias_exists None testindex |
346,730 | def get(self):
t do this in production environments.
'
self.write("Memory Session Object Demo:")
if "sv" in self.session:
current_value = self.session["sv"]
self.write("current sv value is %s, and system will delete this value.<br/>" % self.session["sv"])
... | Please don't do this in production environments. |
346,731 | def case_mme_delete(self, case_obj, user_obj):
institute_obj = self.institute(case_obj[])
for individual in case_obj[]:
if individual[] == 2:
self.create_event(institute=institute_obj, case=case_obj, user=user_obj,
link=... | Delete a MatchMaker submission from a case record
and creates the related event.
Args:
case_obj(dict): a scout case object
user_obj(dict): a scout user object
Returns:
updated_case(dict): the updated scout case |
346,732 | def _iter_from_annotations_dict(graph: BELGraph,
annotations_dict: AnnotationsDict,
) -> Iterable[Tuple[str, Set[str]]]:
for key, names in annotations_dict.items():
if key in graph.annotation_url:
url = ... | Iterate over the key/value pairs in this edge data dictionary normalized to their source URLs. |
346,733 | def is_in_expr(expr, find):
return expr == find or (isinstance(expr, ExprNode) and expr.is_in(find)) | Returns True if `find` is a subtree of `expr`. |
346,734 | def read_length_block(fp, fmt=, padding=1):
length = read_fmt(fmt, fp)[0]
data = fp.read(length)
assert len(data) == length, (len(data), length)
read_padding(fp, length, padding)
return data | Read a block of data with a length marker at the beginning.
:param fp: file-like
:param fmt: format of the length marker
:return: bytes object |
346,735 | def iscsi_resource(self):
return iscsi.ISCSIResource(
self._conn, utils.get_subresource_path_by(
self, ["Oem", "Hpe", "Links", "iScsi"]),
redfish_version=self.redfish_version) | Property to provide reference to bios iscsi resource instance
It is calculated once when the first time it is queried. On refresh,
this property gets reset. |
346,736 | def init_app(self, app, **kwargs):
self.kwargs.update(kwargs)
self.settings = self.dynaconf_instance or LazySettings(**self.kwargs)
app.config = self.make_config(app)
app.dynaconf = self.settings | kwargs holds initial dynaconf configuration |
346,737 | def set_ylimits_for_all(self, row_column_list=None, min=None, max=None):
if row_column_list is None:
self.limits[] = min
self.limits[] = max
else:
for row, column in row_column_list:
self.set_ylimits(row, column, min, max) | Set y-axis limits of specified subplots.
:param row_column_list: a list containing (row, column) tuples to
specify the subplots, or None to indicate *all* subplots.
:type row_column_list: list or None
:param min: minimal axis value
:param max: maximum axis value |
346,738 | def blocked(self):
r
return [r.user for r in self._relationships.values() if r.type is RelationshipType.blocked] | r"""Returns a :class:`list` of :class:`User`\s that the user has blocked.
.. note::
This only applies to non-bot accounts. |
346,739 | def from_file(cls, fn, *args, **kwargs):
return AmiraHeader(get_parsed_data(fn, *args, **kwargs)) | Constructor to build an AmiraHeader object from a file
:param str fn: Amira file
:return ah: object of class ``AmiraHeader`` containing header metadata
:rtype: ah: :py:class:`ahds.header.AmiraHeader` |
346,740 | def eagle(args):
p = OptionParser(eagle.__doc__)
p.add_option("--share", default="/usr/local/share/EAGLE/",
help="Default EAGLE share path")
add_sim_options(p)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
fastafile, = args
sh... | %prog eagle fastafile |
346,741 | def energy(q, v):
N: int = len(q)
T: np.ndarray = np.zeros(N)
U: np.ndarray = np.zeros(N)
for i in range(B):
m = mass[i]
vi = v[:, slices[i]]
T += 0.5 * m * np.sum(vi * vi, axis=1)
for i in range(B):
for j in r... | Compute the kinetic and potential energy of the planetary system |
346,742 | def remove_callback(self, name, before=None, after=None):
if isinstance(name, (list, tuple)):
for name in name:
self.remove_callback(name, before, after)
elif before is None and after is None:
del self._callback_registry[name]
else:
if... | Remove a beforeback, and afterback pair from this Spectator
If ``before`` and ``after`` are None then all callbacks for
the given method will be removed. Otherwise, only the exact
callback pair will be removed.
Parameters
----------
name: str
The name of the... |
346,743 | def get_number_of_agents_for_scheduling(self, context):
num_agents = len(self.get_l3_agents(context, active=True,
filters={: [bc.constants.L3_AGENT_MODE_LEGACY,
bc.constants.L3_AGENT_MODE_DVR_SNAT]}))
max_agents = cfg.CONF.max_l3_agents_per_rout... | Return number of agents on which the router will be scheduled. |
346,744 | def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_port_state(self, **kwargs):
config = ET.Element("config")
fcoe_get_interface = ET.Element("fcoe_get_interface")
config = fcoe_get_interface
output = ET.SubElement(fcoe_get_interface, "output")
fcoe_intf_list = ET.Sub... | Auto Generated Code |
346,745 | def _build_row(cells, padding, begin, sep, end):
"Return a string which represents a row of data cells."
pad = " " * padding
padded_cells = [pad + cell + pad for cell in cells]
rendered_cells = (begin + sep.join(padded_cells) + end).rstrip()
if len(rendered_cells) > TTY_COLS:
if ... | Return a string which represents a row of data cells. |
346,746 | def _rest_request_to_json(self, url, instance, object_path, tags, *args, **kwargs):
service_check_tags = [.format(self._get_url_base(url))] + tags
service_check_tags = list(set(service_check_tags))
if object_path:
url = self._join_url_dir(url, object_path)
... | Query the given URL and return the JSON response |
346,747 | def check(self, pointer, expected, raise_onerror=False):
obj = self.document
for token in Pointer(pointer):
try:
obj = token.extract(obj, bypass_ref=True)
except ExtractError as error:
if raise_onerror:
raise Error(*err... | Check if value exists into object.
:param pointer: the path to search in
:param expected: the expected value
:param raise_onerror: should raise on error?
:return: boolean |
346,748 | def _search_uid(self, query):
try:
yield self.contacts[query]
except KeyError:
for uid in self.contacts:
if uid.startswith(query):
yield self.contacts[uid] | Search for contacts with a matching uid.
:param query: the query to search for
:type query: str
:yields: all found contacts
:rtype: generator(carddav_object.CarddavObject) |
346,749 | def mute_string(text):
start = text.index(text[-1]) + 1
end = len(text) - 1
if text[-3:] in (, "x' * (end - start) + text[end:] | Replace contents with 'xxx' to prevent syntax matching.
>>> mute_string('"abc"')
'"xxx"'
>>> mute_string("'''abc'''")
"'''xxx'''"
>>> mute_string("r'abc'")
"r'xxx'" |
346,750 | def dump_json(testcase, json_file):
logging.info("dump testcase to JSON format.")
with io.open(json_file, , encoding="utf-8") as outfile:
my_json_str = json.dumps(testcase, ensure_ascii=ensure_ascii, indent=4)
if isinstance(my_json_str, bytes):
my_json_str = my_json_str.decode(... | dump HAR entries to json testcase |
346,751 | def set_level(level=1, logger="TaskLogger"):
tasklogger = get_tasklogger(logger)
tasklogger.set_level(level)
return tasklogger | Set the logging level
Convenience function to set the logging level
Parameters
----------
level : `int` or `bool` (optional, default: 1)
If False or 0, prints WARNING and higher messages.
If True or 1, prints INFO and higher messages.
If 2 or higher, prints all messages.
R... |
346,752 | def _legacy_upload_archive(self, data_collected, duration):
file_name = os.path.basename(data_collected)
try:
from insights.contrib import magic
m = magic.open(magic.MAGIC_MIME)
m.load()
mime_type = m.file(data_collected)
except ImportErro... | Do an HTTPS upload of the archive |
346,753 | def MobileDevice(self, data=None, subset=None):
return self.factory.get_object(jssobjects.MobileDevice, data, subset) | {dynamic_docstring} |
346,754 | def url_encode(obj, charset=, encode_keys=False, sort=False, key=None,
separator=):
return separator.join(_url_encode_impl(obj, charset, encode_keys, sort, key)) | URL encode a dict/`MultiDict`. If a value is `None` it will not appear
in the result string. Per default only values are encoded into the target
charset strings. If `encode_keys` is set to ``True`` unicode keys are
supported too.
If `sort` is set to `True` the items are sorted by `key` or the defaul... |
346,755 | def threshold(values, threshold):
values = nominal_values(values)
return (values < threshold, values >= threshold) | Return boolean arrays where a >= and < threshold.
Parameters
----------
values : array-like
Array of real values.
threshold : float
Threshold value
Returns
-------
(below, above) : tuple or boolean arrays |
346,756 | def readInternalC(self):
v = self._read32()
v >>= 4
internal = v & 0x7FF
if v & 0x800:
internal -= 4096
return internal * 0.0625 | Return internal temperature value in degrees celsius. |
346,757 | def _make_details_from_stat(self, stat_result):
details = {
: [, ],
: stat_result.st_atime,
: stat_result.st_mtime,
: stat_result.st_size,
: int(OSFS._get_type_from_stat(stat_result)),
}
details[] = getattr(stat_result, , None... | Make a *details* dictionnary from a stat result. |
346,758 | def parse_args_kwargs(parser, token):
bits = token.contents.split()
if len(bits) <= 1:
raise template.TemplateSyntaxError(" takes at least one argument" % bits[0])
if token.contents[13] == :
end_quote = token.contents.index(, 14) + 1
args = [template.Variable(token.contents[13... | Parse uniformly args and kwargs from a templatetag
Usage::
For parsing a template like this:
{% footag my_contents,height=10,zoom=20 as myvar %}
You simply do this:
@register.tag
def footag(parser, token):
args, kwargs = parse_args_kwargs(parser, token) |
346,759 | def patch(self, container: Container, patch: Patch) -> bool:
path = "containers/{}".format(container.uid)
payload = str(patch)
r = self.__api.patch(path, payload)
return r.status_code == 204 | Attempts to apply a given patch to the source code for a program inside
a given container. All patch applications are guaranteed to be atomic;
if the patch fails to apply, no changes will be made to the relevant
source code files.
Returns:
true if patch application was succe... |
346,760 | def _expand_endpoint_name(endpoint_name, flags):
return tuple(flag.format(endpoint_name=endpoint_name) for flag in flags) | Populate any ``{endpoint_name}`` tags in the flag names for the given
handler, based on the handlers module / file name. |
346,761 | def potential_jumps( self ):
jumps = []
if self.number_of_occupied_sites <= self.number_of_sites / 2:
for occupied_site in self.occupied_sites():
unoccupied_neighbours = [ site for site in [ self.site_with_id( n ) for n in occupied_site.neighbours ] if not site.is_oc... | All nearest-neighbour jumps not blocked by volume exclusion
(i.e. from occupied to neighbouring unoccupied sites).
Args:
None
Returns:
(List(Jump)): List of possible jumps. |
346,762 | def get_auto_login():
*
cmd = [,
,
,
]
ret = __salt__[](cmd, ignore_retcode=True)
return False if ret[] else ret[] | .. versionadded:: 2016.3.0
Gets the current setting for Auto Login
:return: If enabled, returns the user name, otherwise returns False
:rtype: str, bool
CLI Example:
.. code-block:: bash
salt '*' user.get_auto_login |
346,763 | def get_proteins_from_psm(line):
proteins = line[mzidtsvdata.HEADER_PROTEIN].split()
outproteins = []
for protein in proteins:
prepost_protein = re.sub(, , protein).strip()
outproteins.append(prepost_protein)
return outproteins | From a line, return list of proteins reported by Mzid2TSV. When unrolled
lines are given, this returns the single protein from the line. |
346,764 | def parse_headers_link(headers):
header = CaseInsensitiveDict(headers).get()
l = {}
if header:
links = parse_link(header)
for link in links:
key = link.get() or link.get()
l[key] = link
return l | Returns the parsed header links of the response, if any. |
346,765 | def push_subscription_set(self, endpoint, encrypt_params, follow_events=None,
favourite_events=None, reblog_events=None,
mention_events=None):
endpoint = Mastodon.__protocolize(endpoint)
push_pubkey_b64 = base64.b64encode(en... | Sets up or modifies the push subscription the logged-in user has for this app.
`endpoint` is the endpoint URL mastodon should call for pushes. Note that mastodon
requires https for this URL. `encrypt_params` is a dict with key parameters that allow
the server to encrypt data for you: A ... |
346,766 | def select_extended(cat_table):
try:
l = [len(row.strip()) > 0 for row in cat_table[].data]
return np.array(l, bool)
except KeyError:
return cat_table[] | Select only rows representing extended sources from a catalog table |
346,767 | def to_jsondict(self):
if self._composed_with_old_api():
o2 = OFPMatch()
o2.fields = self.fields[:]
buf = bytearray()
o2.serialize(buf, 0)
o = OFPMatch.parser(six.binary_type(buf), 0)
else:
... | Returns a dict expressing the flow match. |
346,768 | def _read_coll(
ctx: ReaderContext,
f: Callable[[Collection[Any]], Union[llist.List, lset.Set, vector.Vector]],
end_token: str,
coll_name: str,
):
coll: List = []
reader = ctx.reader
while True:
token = reader.peek()
if token == "":
raise SyntaxError(f"Unexpe... | Read a collection from the input stream and create the
collection using f. |
346,769 | def synchronize_labels(new_bound_idxs, old_bound_idxs, old_labels, N):
assert len(old_bound_idxs) - 1 == len(old_labels)
unfold_labels = np.zeros(N)
for i, (bound_idx, label) in enumerate(
zip(old_bound_idxs[:-1], old_labels)):
unfold_labels[bound_idx:old_bound_idxs[i + 1]] = ... | Synchronizes the labels from the old_bound_idxs to the new_bound_idxs.
Parameters
----------
new_bound_idxs: np.array
New indeces to synchronize with.
old_bound_idxs: np.array
Old indeces, same shape as labels + 1.
old_labels: np.array
Labels associated to the old_bound_idxs... |
346,770 | def set_log_file_extension(self, logFileExtension):
assert isinstance(logFileExtension, basestring), "logFileExtension must be a basestring"
assert len(logFileExtension), "logFileExtension can't be empty"
if logFileExtension[0] == ".":
logFileExtension = logFileExtension[1:]... | Set the log file extension.
:Parameters:
#. logFileExtension (string): Logging file extension. A logging file full name is
set as logFileBasename.logFileExtension |
346,771 | def set_history_file(self, path):
if path:
self.history = prompt_toolkit.history.FileHistory(fixpath(path))
else:
self.history = prompt_toolkit.history.InMemoryHistory() | Set path to history file. "" produces no file. |
346,772 | def status_to_string(dbus_status):
*
status_tuple = (
dbus_status & 0b000000001, dbus_status & 0b000000010, dbus_status & 0b000000100,
dbus_status & 0b000001000, dbus_status & 0b000010000, dbus_status & 0b000100000,
dbus_status & 0b001000000, dbus_status & 0b010000000, dbus_status & 0b10... | Converts a numeric dbus snapper status into a string
CLI Example:
.. code-block:: bash
salt '*' snapper.status_to_string <dbus_status> |
346,773 | def run_guest():
_user_input_properties()
_run_guest(GUEST_USERID, IMAGE_PATH, IMAGE_OS_VERSION, GUEST_PROFILE,
GUEST_VCPUS, GUEST_MEMORY, NETWORK_INFO, VSWITCH_NAME, DISKS_LIST) | A sample for quickly deploy and start a virtual guest. |
346,774 | def to_dict(_dict, onts, mdb_safe=False):
res = {}
if isinstance(_dict, SamlBase):
res["__class__"] = "%s&%s" % (_dict.c_namespace, _dict.c_tag)
for key in _dict.keyswv():
if key in IMP_SKIP:
continue
val = getattr(_dict, key)
if key == "e... | Convert a pysaml2 SAML2 message class instance into a basic dictionary
format.
The export interface.
:param _dict: The pysaml2 metadata instance
:param onts: List of schemas to use for the conversion
:return: The converted information |
346,775 | def to_csv(self, filename, stimuli=None, inhibitors=None, prepend=""):
self.to_dataframe(stimuli, inhibitors, prepend).to_csv(filename, index=False) | Writes the list of clampings to a CSV file
Parameters
----------
filename : str
Absolute path where to write the CSV file
stimuli : Optional[list[str]]
List of stimuli names. If given, stimuli are converted to {0,1} instead of {-1,1}.
inhibitors : Optio... |
346,776 | def make_secret(form_instance, secret_fields=None):
warn_untested()
if secret_fields is None:
secret_fields = [, ]
data = ""
for name in secret_fields:
if hasattr(form_instance, ):
if name in form_instance.cleaned_data:
data += ... | Returns a secret for use in a EWP form or an IPN verification based on a
selection of variables in params. Should only be used with SSL. |
346,777 | def split_strings_in_list_retain_spaces(orig_list):
temp_list = list()
for line in orig_list:
line_split = __re.split(r, line)
temp_list.append(line_split)
return temp_list | Function to split every line in a list, and retain spaces for a rejoin
:param orig_list: Original list
:return:
A List with split lines |
346,778 | def online(zpool, *vdevs, **kwargs):
*
flags = []
target = []
if kwargs.get(, False):
flags.append()
target.append(zpool)
if vdevs:
target.extend(vdevs)
flags = []
target = []
if kwargs.get(, False):
flags.append()
ta... | .. versionadded:: 2015.5.0
Ensure that the specified devices are online
zpool : string
name of storage pool
vdevs : string
one or more devices
expand : boolean
Expand the device to use all available space.
.. note::
If the device is part of a mirror or r... |
346,779 | def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None):
if not urlconf:
urlconf = get_urlconf()
resolver = get_resolver(urlconf)
args = args or []
kwargs = kwargs or {}
prefix = get_script_prefix()
if not isinstance(viewname, six.string_types):
view... | monkey patched reverse
path supports easy patching 3rd party urls
if 3rd party app has namespace for example ``catalogue`` and
you create FeinCMS plugin with same name as this namespace reverse
returns url from ApplicationContent ! |
346,780 | def is_socket_closed(sock):
if not sock:
return True
try:
if not poll:
if not select:
return False
try:
return bool(select([sock], [], [], 0.0)[0])
except socket.error:
return True
... | Check if socket ``sock`` is closed. |
346,781 | def with_rank(self, rank):
try:
return self.merge_with(unknown_shape(ndims=rank))
except ValueError:
raise ValueError("Shape %s must have rank %d" % (self, rank)) | Returns a shape based on `self` with the given rank.
This method promotes a completely unknown shape to one with a
known rank.
Args:
rank: An integer.
Returns:
A shape that is at least as specific as `self` with the given rank.
Raises:
ValueError... |
346,782 | def read_vpcs_stdout(self):
output = ""
if self._vpcs_stdout_file:
try:
with open(self._vpcs_stdout_file, "rb") as file:
output = file.read().decode("utf-8", errors="replace")
except OSError as e:
log.warn("Could not r... | Reads the standard output of the VPCS process.
Only use when the process has been stopped or has crashed. |
346,783 | def set_mag_offsets_send(self, target_system, target_component, mag_ofs_x, mag_ofs_y, mag_ofs_z, force_mavlink1=False):
return self.send(self.set_mag_offsets_encode(target_system, target_component, mag_ofs_x, mag_ofs_y, mag_ofs_z), force_mavlink1=force_mavlink1) | Deprecated. Use MAV_CMD_PREFLIGHT_SET_SENSOR_OFFSETS instead. Set the
magnetometer offsets
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
mag_ofs_x : magnetometer X offset (int16_t)
... |
346,784 | def filter(sqmassfiles, infile, max_precursor_pep, max_peakgroup_pep, max_transition_pep):
filter_sqmass(sqmassfiles, infile, max_precursor_pep, max_peakgroup_pep, max_transition_pep) | Filter sqMass files |
346,785 | def add_edges_from(self, ebunch, attr_dict=None, **attr):
if attr_dict is None:
attr_dict = attr
else:
try:
attr_dict.update(attr)
except AttributeError:
raise NetworkXError(
"The attr_dict argument must be ... | Version of add_edges_from that only writes to the database once |
346,786 | def versions_available(self):
if self.version:
spec = "%s==%s" % (self.project_name, self.version)
else:
spec = self.project_name
if self.all_versions and self.version in self.all_versions:
print_pkg_versions(self.project_name, [self.version])
... | Query PyPI for a particular version or all versions of a package
@returns: 0 if version(s) found or 1 if none found |
346,787 | def save_feedback(rdict):
if not os.path.exists(_feedback_dir):
os.makedirs(_feedback_dir)
jcont = json.dumps(rdict)
f = open(_feedback_file, )
f.write(jcont)
f.close() | Save feedback file |
346,788 | def __filter(filterable, filter_, logic_operation=):
condition = []
if not filter_:
return filterable
elif filter_.get() == :
return filterable
else:
for key, value in filter_.items():
condition.append(.format(key=key, value=va... | filtering DataFrame using filter_ key-value conditions applying logic_operation
only find rows strictly fitting the filter_ criterion |
346,789 | def send_request(self, target: str, *args, **kwargs):
address = self._get_address_from_source(target)
if address is None:
return
args = json.dumps(args).encode()
kwargs = json.dumps(kwargs).encode()
frame = (*address, b, b, args, ... | address must a list instance. Or a string which will be transformed into a address |
346,790 | def wrap(text, width=70, **kwargs):
w = TextWrapper(width=width, **kwargs)
return w.wrap(text) | Wrap a single paragraph of text, returning a list of wrapped lines.
Reformat the single paragraph in 'text' so it fits in lines of no
more than 'width' columns, and return a list of wrapped lines. By
default, tabs in 'text' are expanded with string.expandtabs(), and
all other whitespace characters (in... |
346,791 | def acquire(self):
self._condition.acquire()
try:
if self._maxsize is not None and self._block:
while not self._pool and self._nconnections == self._maxsize:
self._condition.wait(timeout=None)
while self._p... | Get a new connection from the pool.
This will return an existing connection, if one is available in the
pool, or create a new connection.
.. warning:: If the pool was created with `maxsize` and `block=True`,
this method may block until a connection is available in the pool. |
346,792 | def _calculate_column_widths(self):
table_width = self.get_table_width()
lpw, rpw = self._left_padding_widths, self._right_padding_widths
pad_widths = [(lpw[i] + rpw[i]) for i in range(self._column_count)]
max_widths = [0 for index in range(self._column_count)]
offset = ... | Calculate width of column automatically based on data. |
346,793 | def create_aeff(event_class, event_type, egy, cth):
irf = create_irf(event_class, event_type)
irf.aeff().setPhiDependence(False)
theta = np.degrees(np.arccos(cth))
m = np.zeros((len(egy), len(cth)))
for i, x in enumerate(egy):
for j, y in enumerate(theta):
m[i, j... | Create an array of effective areas versus energy and incidence
angle. Binning in energy and incidence angle is controlled with
the egy and cth input parameters.
Parameters
----------
event_class : str
Event class string (e.g. P8R2_SOURCE_V6).
event_type : list
egy : array_like
... |
346,794 | def synchronised(func):
def Wrapper(main_obj, *args, **kwargs):
main_obj._lock.acquire()
try:
return func(main_obj, *args, **kwargs)
finally:
main_obj._lock.release()
return Wrapper | Synchronisation decorator. |
346,795 | def get_factory_bundle(self, name):
with self.__factories_lock:
try:
factory = self.__factories[name]
except KeyError:
raise ValueError("Unknown factory ".format(name))
else:
factory_context = ... | Retrieves the Pelix Bundle object that registered the given factory
:param name: The name of a factory
:return: The Bundle that registered the given factory
:raise ValueError: Invalid factory |
346,796 | def parse_params(self,
layer=None,
eps=0.3,
eps_iter=0.05,
nb_iter=10,
ord=np.inf,
clip_min=None,
clip_max=None,
**kwargs):
self.layer = layer
self.e... | Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param layer: (required str) name of the layer to target.
:param eps: (optional float) maximum distortion of adversarial example
compared to original inpu... |
346,797 | def get_links_of_type(self, link_type):
return (link for link in self.links if link.get(, ) == link_type) | Returns list of additional links of specific type.
:Returns:
As tuple returns list of links. |
346,798 | def accept_response(self,
response_header,
content=EmptyValue,
content_type=EmptyValue,
accept_untrusted_content=False,
localtime_offset_in_seconds=0,
timestamp_skew_in_seconds... | Accept a response to this request.
:param response_header:
A `Hawk`_ ``Server-Authorization`` header
such as one created by :class:`mohawk.Receiver`.
:type response_header: str
:param content=EmptyValue: Byte string of the response body received.
:type content=E... |
346,799 | def notify_batches_finished(self, statuses):
with self._wait_condition:
self._statuses = statuses
self._wait_condition.notify() | Called by the BatchTracker the _BatchWaiter is observing. Should not
be called by handlers.
Args:
statuses (dict of int): A dict with keys of batch ids, and values
of status enums |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.