Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
341,200 | def put(self, destination):
if not self._fetched:
self._fetch()
DirectoryArchive.put(self, destination) | Copy the referenced directory to this path
Args:
destination (str): path to put this directory (which must NOT already exist) |
341,201 | def check_requirements():
if not os.path.exists(REQUIREMENTS):
sys.exit(
ansi.error() + % ansi.underline(REQUIREMENTS)
)
with open(REQUIREMENTS, , encoding=) as f:
dependencies = f.readlines()
vcs = [d for d in dependencies if re.match(r, d)]
dependencies = l... | Make sure all listed packages from requirements.txt have been installed into the virtualenv at boot. |
341,202 | def package(self, name):
if isinstance(name, dict):
name = name.get(, name.get())
j, _ = self.request(, + str(name))
return j | ::
GET /:login/packages/:package
:param name: the name identifying the package
:type dataset_id: :py:class:`basestring` or :py:class:`dict`
:rtype: :py:class:`dict`
Gets a dict representing resource values for a package by name. If
... |
341,203 | def list_logs(self, source, entry_id=None, start_time=None, end_time=None):
route_values = {}
if source is not None:
route_values[] = self._serialize.url(, source, )
if entry_id is not None:
route_values[] = self._serialize.url(, entry_id, )
query_paramet... | ListLogs.
[Preview API] List diagnostic logs this service.
:param str source:
:param str entry_id:
:param datetime start_time:
:param datetime end_time:
:rtype: [INotificationDiagnosticLog] |
341,204 | def url_unescape(
value: Union[str, bytes], encoding: Optional[str] = "utf-8", plus: bool = True
) -> Union[str, bytes]:
if encoding is None:
if plus:
value = to_basestring(value).replace("+", " ")
return urllib.parse.unquote_to_bytes(value)
else:
unqu... | Decodes the given value from a URL.
The argument may be either a byte or unicode string.
If encoding is None, the result will be a byte string. Otherwise,
the result is a unicode string in the specified encoding.
If ``plus`` is true (the default), plus signs will be interpreted
as spaces (litera... |
341,205 | def decrypt(self, password_encrypted):
if not password_encrypted or not self._crypter:
return password_encrypted or b
return self._crypter.decrypt(password_encrypted) | Decrypt the password. |
341,206 | def copy(self):
new_cj = RequestsCookieJar()
new_cj.set_policy(self.get_policy())
new_cj.update(self)
return new_cj | Return a copy of this RequestsCookieJar. |
341,207 | def revert_snapshot(name, snap_name, runas=None):
*
name = salt.utils.data.decode(name)
snap_name = _validate_snap_name(name, snap_name, runas=runas)
args = [name, , snap_name]
return prlctl(, args, runas=runas) | Revert a VM to a snapshot
:param str name:
Name/ID of VM to revert to a snapshot
:param str snap_name:
Name/ID of snapshot to revert to
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.revert_snap... |
341,208 | def request_x11(
self,
screen_number=0,
auth_protocol=None,
auth_cookie=None,
single_connection=False,
handler=None,
):
if auth_protocol is None:
auth_protocol = "MIT-MAGIC-COOKIE-1"
if auth_cookie is None:
auth_cookie ... | Request an x11 session on this channel. If the server allows it,
further x11 requests can be made from the server to the client,
when an x11 application is run in a shell session.
From :rfc:`4254`::
It is RECOMMENDED that the 'x11 authentication cookie' that is
sent be... |
341,209 | def create_conversation(self, recipients, body, **kwargs):
from canvasapi.conversation import Conversation
kwargs[] = recipients
kwargs[] = body
response = self.__requester.request(
,
,
_kwargs=combine_kwargs(**kwargs)
)
retu... | Create a new Conversation.
:calls: `POST /api/v1/conversations \
<https://canvas.instructure.com/doc/api/conversations.html#method.conversations.create>`_
:param recipients: An array of recipient ids.
These may be user ids or course/group ids prefixed
with 'course\\_' o... |
341,210 | def gen403(request, baseURI, reason, project=None):
orgas = None
public_ask = False
if not settings.PIAPI_STANDALONE:
from organizations.models import Organization
if project and project.plugItLimitOrgaJoinable:
orgas = project.plugItOrgaJoinable.order_by().all()
e... | Return a 403 error |
341,211 | def relative_path(path, from_file):
if path is None:
return None
abs_path_target = absolute_path(path, from_file)
abs_path_cwd = os.getcwd()
if is_windows():
t_drive, t_tail = os.path.splitdrive(abs_path_target)
c_drive, c_tail = os.path.splitdrive... | Return the relative path of a file or directory, specified
as ``path`` relative to (the parent directory of) ``from_file``.
This method is intented to be called with ``__file__``
as second argument.
The returned path is relative to the current working directory.
If ``path`` is ``None``, return ``... |
341,212 | def energy(self, x, y):
r
pooler = self
W = pooler.connections.visible_to_hidden
H = pooler.connections.hidden_to_hidden
b = pooler.connections.hidden_bias
n, m = pooler.output_size, pooler.input_size
w = pooler.code_weight
size_pena... | r"""
Numenta's energy with an additional term (the H-term)
to decorrelate pairwise column activity:
$$
E(x,y) = - \sum_i y_i \cdot \exp( - b_i - \sum_j H_{ij} \ y_j ) \cdot (\sum_j W_{ij} \ x_j ) + S(y)
$$
where the size size penalty is given by
$$
... |
341,213 | def ParseObjs(self, objs, type_names):
for obj in objs:
for type_name in self._RDFTypes(type_names):
if isinstance(obj, self._GetClass(type_name)):
yield obj | Parse one or more objects by testing if it is a known RDF class. |
341,214 | def calculate_progress(self, scan_id):
t_prog = dict()
for target in self.get_scan_target(scan_id):
t_prog[target] = self.get_scan_target_progress(scan_id, target)
return sum(t_prog.values())/len(t_prog) | Calculate the total scan progress from the
partial target progress. |
341,215 | def _usage_overall(raw):
data = {}
for line in raw.split("\n")[1:]:
keyset = [item.strip() for item in re.sub(r"\s+", " ", line).split(":", 1) if item.strip()]
if len(keyset) == 2:
key = re.sub(r"[()]", "", keyset[0]).replace(" ", "_").lower()
if key in [, ]:
... | Parse usage/overall. |
341,216 | def advance(self, inputs, advance_time, time_step=None):
final_time_seconds = self.time_seconds + advance_time
if time_step is None:
time_step = 0.5 * self.get_max_time_step()
if len(self.input_nodes) != len(inputs):
raise RuntimeError("Expected {0} ... | Advance the simulation by the given amount of time, assuming that inputs are
constant at the given values during the simulated time. |
341,217 | def createEvent(self, state, description, metric, prefix=None,
hostname=None, aggregation=None, evtime=None):
if prefix:
service_name = self.service + "." + prefix
else:
service_name = self.service
return Event(state, service_name, description, metri... | Creates an Event object from the Source configuration |
341,218 | def _get_lt_from_user_by_id(self, user, lt_id):
req = meta.Session.query(LayerTemplate).select_from(join(LayerTemplate, User))
try:
return req.filter(and_(User.login==user, LayerTemplate.id==lt_id)).one()
except Exception, e:
return None | Get a layertemplate owned by a user from the database by lt_id. |
341,219 | def stripArgs(args, blacklist):
blacklist = [b.lower() for b in blacklist]
return list([arg for arg in args if arg.lower() not in blacklist]) | Removes any arguments in the supplied list that are contained in the specified blacklist |
341,220 | def count_by_time(self):
out = np.empty((len(self.timesteps),), dtype=[(, float), (, int)])
for cursor,timestep in enumerate(self.timesteps):
out[cursor] = (timestep,len([x for x in self.timeseries if x.time==timestep]))
return out.view(np.recarray) | Count how many salt bridges occured in each frame.
Returns numpy array. |
341,221 | def evaluaterforces(Pot,R,z,phi=None,t=0.,v=None):
isList= isinstance(Pot,list)
nonAxi= _isNonAxi(Pot)
if nonAxi and phi is None:
raise PotentialError("The (list of) Potential instances is non-axisymmetric, but you did not provide phi")
dissipative= _isDissipative(Pot)
if dissipative an... | NAME:
evaluaterforces
PURPOSE:
convenience function to evaluate a possible sum of potentials
INPUT:
Pot - a potential or list of potentials
R - cylindrical Galactocentric distance (can be Quantity)
z - distance above the plane (can be Quantity)
phi - azimuth (op... |
341,222 | def as_html(self, path=""):
if path not in self.top_level_links:
raise StateError("Unknown path")
header =
footer =
rep = self.get_state_repr(path)
def make_links(rep):
for e, v in rep.items():
if e == "_href":
... | Return a rendering of the current state in HTML. |
341,223 | def load(cls, copula_path):
with open(copula_path) as f:
copula_dict = json.load(f)
return cls.from_dict(copula_dict) | Create a new instance from a file.
Args:
copula_path: `str` file with the serialized copula.
Returns:
Bivariate: Instance with the parameters stored in the file. |
341,224 | def get_public_members():
if bezier is None:
return []
local_members = []
all_members = set()
for name in dir(bezier):
if name.startswith("_") and name not in SPECIAL_MEMBERS:
continue
value = getattr(bezier, name)
if isinstance(value,... | Get public members in :mod:`bezier` package.
Also validates the contents of ``bezier.__all__``.
Returns:
list: List of all public members **defined** in the
main package (i.e. in ``__init__.py``).
Raises:
ValueError: If ``__all__`` has repeated elements.
ValueError: If the... |
341,225 | def files(self):
for _f in self.searchresult.files.iterchildren():
yield ProtoFile.factory(_f, jfs=self.jfs, parentpath=unicode(_f.abspath)) | iterate over found files |
341,226 | def _step2(self, word):
if len(word) <= 1:
return word
ch = word[-2]
if ch == :
if word.endswith("ational"):
return word[:-7] + "ate" if self._m(word, len(word)-8) > 0 else word
elif word.endswith("tional"):
return w... | step2() maps double suffices to single ones.
so -ization ( = -ize plus -ation) maps to -ize etc. note that the
string before the suffix must give m() > 0. |
341,227 | def compute_qu(self):
Kuf = features.Kuf(self.feature, self.kern, self.X)
Kuu = features.Kuu(self.feature, self.kern, jitter=settings.jitter)
Sig = Kuu + (self.likelihood.variance ** -1) * tf.matmul(Kuf, Kuf, transpose_b=True)
Sig_sqrt = tf.cholesky(Sig)
Sig_sqrt_Kuu =... | Computes the mean and variance of q(u), the variational distribution on
inducing outputs. SVGP with this q(u) should predict identically to
SGPR.
:return: mu, A |
341,228 | def _usage_specific(raw):
get_key = lambda val: dict([tuple(val.split(":")), ])
raw = raw.split("\n")
section, size, used = raw[0].split(" ")
section = section.replace(",", "_").replace(":", "").lower()
data = {}
data[section] = {}
for val in [size, used]:
data[section].update... | Parse usage/specific. |
341,229 | def nanpercentile(values, q, axis, na_value, mask, ndim, interpolation):
if not lib.is_scalar(mask) and mask.any():
if ndim == 1:
return _nanpercentile_1d(values, mask, q, na_value,
interpolation=interpolation)
else:
if m... | Wraper for np.percentile that skips missing values.
Parameters
----------
values : array over which to find quantiles
q : scalar or array of quantile indices to find
axis : {0, 1}
na_value : scalar
value to return for empty or all-null values
mask : ndarray[bool]
locations i... |
341,230 | def namedb_get_history( cur, history_id, offset=None, count=None, reverse=False ):
history_rows = namedb_get_history_rows( cur, history_id, offset=offset, count=count, reverse=reverse )
return namedb_history_extract( history_rows ) | Get all of the history for a name or namespace.
Returns a dict keyed by block heights, paired to lists of changes (see namedb_history_extract) |
341,231 | def add_robot(self, controller):
controller.on_mode_change(self._on_robot_mode_change)
self.robots.append(controller) | Add a robot controller |
341,232 | def Cleanse(obj, encoding=):
if isinstance(obj, int):
return obj
elif isinstance(obj, float):
if obj == _INFINITY:
return
elif obj == _NEGATIVE_INFINITY:
return
elif math.isnan(obj):
return
else:
return obj
elif isinstance(obj, bytes):
return tf.compat.as_text... | Makes Python object appropriate for JSON serialization.
- Replaces instances of Infinity/-Infinity/NaN with strings.
- Turns byte strings into unicode strings.
- Turns sets into sorted lists.
- Turns tuples into lists.
Args:
obj: Python data structure.
encoding: Charset used to decode byte strings.
... |
341,233 | def get_deployment_targets(self, project, deployment_group_id, tags=None, name=None, partial_name_match=None, expand=None, agent_status=None, agent_job_result=None, continuation_token=None, top=None, enabled=None, property_filters=None):
route_values = {}
if project is not None:
rou... | GetDeploymentTargets.
[Preview API] Get a list of deployment targets in a deployment group.
:param str project: Project ID or project name
:param int deployment_group_id: ID of the deployment group.
:param [str] tags: Get only the deployment targets that contain all these comma separted ... |
341,234 | def solve_simple_captcha(self, pathfile=None, filedata=None, filename=None):
captcha_id = self._submit(pathfile, filedata, filename)
return self._getresult(captcha_id=captcha_id) | Upload a image (from disk or a bytearray), and then
block until the captcha has been solved.
Return value is the captcha result.
either pathfile OR filedata AND filename should be specified.
Failure will result in a subclass of WebRequest.CaptchaSolverFailure being
thrown. |
341,235 | def convert(context, panel):
adapter = context.obj[]
new_header = ["hgnc_id","hgnc_symbol","disease_associated_transcripts",
"reduced_penetrance", "genetic_disease_models", "mosaicism",
"database_entry_version"]
genes = parse_genes(panel)
adapter.add_hgnc... | Convert a gene panel with hgnc symbols to a new one with hgnc ids. |
341,236 | def waitUntilMaybeAvailable(self, owner, access):
debuglog("%s waitUntilAvailable(%s)" % (self, owner))
assert isinstance(access, LockAccess)
if self.isAvailable(owner, access):
return defer.succeed(self)
d = defer.Deferred()
w = [i for i, w in enum... | Fire when the lock *might* be available. The caller will need to
check with isAvailable() when the deferred fires. This loose form is
used to avoid deadlocks. If we were interested in a stronger form,
this would be named 'waitUntilAvailable', and the deferred would fire
after the lock ha... |
341,237 | def search(query, catalog=_marker):
if not isinstance(query, dict):
fail("Catalog query needs to be a dictionary")
portal_types = query.get("portal_type", [])
if not isinstance(portal_types, (tuple, list)):
portal_types = [portal_types]
catalogs = []
... | Search for objects.
:param query: A suitable search query.
:type query: dict
:param catalog: A single catalog id or a list of catalog ids
:type catalog: str/list
:returns: Search results
:rtype: List of ZCatalog brains |
341,238 | def valid_starter_settings(self):
if self.gasheli_settings.ignition_chan <= 0 or self.gasheli_settings.ignition_chan > 8:
print("Invalid ignition channel %d" % self.gasheli_settings.ignition_chan)
return False
if self.gasheli_settings.starter_chan <= 0 or self.gasheli_se... | check starter settings |
341,239 | def get_children_from_path(node, *path):
cur = node
for index, child in enumerate(path):
if isinstance(child, _strtype):
next = _MinidomXmlToObject.get_child_nodes(cur, child)
else:
next = _MinidomXmlToObject._get_child_nodesNS(cur, *child... | descends through a hierarchy of nodes returning the list of children
at the inner most level. Only returns children who share a common parent,
not cousins. |
341,240 | def update(self, friendly_name=values.unset,
default_service_role_sid=values.unset,
default_channel_role_sid=values.unset,
default_channel_creator_role_sid=values.unset,
read_status_enabled=values.unset, reachability_enabled=values.unset,
typing... | Update the ServiceInstance
:param unicode friendly_name: Human-readable name for this service instance
:param unicode default_service_role_sid: The default_service_role_sid
:param unicode default_channel_role_sid: Channel role assigned on channel join
:param unicode default_channel_crea... |
341,241 | def devices(self):
self.verify_integrity()
if session.get(, False):
if request.method == :
return jsonify(self.get_devices()), 200
elif request.method == :
response = self.remove_device(request.json)
if response[] == :
... | Manages users enrolled u2f devices |
341,242 | def get_shell_code(self, shell=None, parent_environ=None, style=OutputStyle.file):
executor = self._create_executor(interpreter=create_shell(shell),
parent_environ=parent_environ)
if self.load_path and os.path.isfile(self.load_path):
executo... | Get the shell code resulting from intepreting this context.
Args:
shell (str): Shell type, for eg 'bash'. If None, the current shell
type is used.
parent_environ (dict): Environment to interpret the context within,
defaults to os.environ if None.
... |
341,243 | def rev_comp(seq):
rev_seq = seq[::-1]
rev_comp_seq = .join([base_pairing[s] for s in rev_seq])
return rev_comp_seq | Get reverse complement of sequence.
rev_comp will maintain the case of the sequence.
Parameters
----------
seq : str
nucleotide sequence. valid {a, c, t, g, n}
Returns
-------
rev_comp_seq : str
reverse complement of sequence |
341,244 | def _try_get_solutions(self, address, size, access, max_solutions=0x1000, force=False):
assert issymbolic(address)
solutions = solver.get_all_values(self.constraints, address, maxcnt=max_solutions)
crashing_condition = False
for base in solutions:
if not self.acces... | Try to solve for a symbolic address, checking permissions when reading/writing size bytes.
:param Expression address: The address to solve for
:param int size: How many bytes to check permissions for
:param str access: 'r' or 'w'
:param int max_solutions: Will raise if more solutions ar... |
341,245 | def encrypt(self, plaintext, encoder=encoding.RawEncoder):
ciphertext = nacl.bindings.crypto_box_seal(
plaintext,
self._public_key
)
encoded_ciphertext = encoder.encode(ciphertext)
return encoded_ciphertext | Encrypts the plaintext message using a random-generated ephemeral
keypair and returns a "composed ciphertext", containing both
the public part of the keypair and the ciphertext proper,
encoded with the encoder.
The private part of the ephemeral key-pair will be scrubbed before
r... |
341,246 | def resolve_remote(self):
for idx, target in enumerate(self._targets):
if isinstance(target, remote):
resolved = target.resolve()
if isinstance(resolved, str):
resolved = interpolate(resolved, env.sos_dict.dict())
self._tar... | If target is of remote type, resolve it |
341,247 | def infer_genome(genome_object_string_or_int):
if isinstance(genome_object_string_or_int, Genome):
return genome_object_string_or_int
if is_integer(genome_object_string_or_int):
return cached_release(genome_object_string_or_int)
elif is_string(genome_object_string_or_int):
... | If given an integer, return associated human EnsemblRelease for that
Ensembl version.
If given a string, return latest EnsemblRelease which has a reference
of the same name.
If given a PyEnsembl Genome, simply return it. |
341,248 | def setRecordSet(self, recordSet):
if not self.tableType():
self.setTableType(recordSet.table())
self._currentRecordSet = None
self._recordSet = recordSet
try:
self.setDatabase(recordSet.database())
except AttributeErro... | Defines the record set that will be used to lookup the information for
this tree.
:param records | [<Table>, ..] || None |
341,249 | def declare_array(self, id_, lineno, type_, bounds, default_value=None):
assert isinstance(type_, symbols.TYPEREF)
assert isinstance(bounds, symbols.BOUNDLIST)
if not self.check_class(id_, CLASS.array, lineno, scope=self.current_scope):
return None
entry = self.get... | Declares an array in the symbol table (VARARRAY). Error if already
exists. |
341,250 | def get_friendly_title(err):
if isinstance(err, basestring):
string = err
else:
try:
string = err.__name__
except AttributeError:
string = err.__class__.__name__
split = _SPLITCASE_RE.findall(string)
if not split:
split.append(string)
if l... | Turn class, instance, or name (str) into an eyeball-friendly title.
E.g. FastfoodStencilSetNotListed --> 'Stencil Set Not Listed' |
341,251 | def rprof(self):
if self.istep not in self.sdat.rprof.index.levels[0]:
return None
return self.sdat.rprof.loc[self.istep] | Radial profiles data of the time step.
Set to None if no radial profiles data is available for this time step. |
341,252 | def run(command, parser, cl_args, unknown_args):
configcommand = cl_args.get(, None)
if configcommand == :
return _set(cl_args)
elif configcommand == :
return _unset(cl_args)
else:
return _list(cl_args) | :param command:
:param parser:
:param args:
:param unknown_args:
:return: |
341,253 | def crypt(password, cost=2):
salt = _generate_salt(cost)
hashed = pbkdf2.pbkdf2_hex(password, salt, cost * 500)
return "$pbkdf2-256-1$" + str(cost) + "$" + salt.decode("utf-8") + "$" + hashed | Hash a password
result sample:
$pbkdf2-256-1$8$FRakfnkgpMjnqs1Xxgjiwgycdf68be9b06451039cc\
0f7075ec1c369fa36f055b1705ec7a
The returned string is broken down into
- The algorithm and version used
- The cost factor, number of iterations over the hash
- The salt
- ... |
341,254 | def market(self, accountID, **kwargs):
return self.create(
accountID,
order=MarketOrderRequest(**kwargs)
) | Shortcut to create a Market Order in an Account
Args:
accountID : The ID of the Account
kwargs : The arguments to create a MarketOrderRequest
Returns:
v20.response.Response containing the results from submitting
the request |
341,255 | def update_records(self, domain, records):
if not isinstance(records, list):
raise TypeError("Expected records of type list")
uri = "/domains/%s/records" % utils.get_id(domain)
resp, resp_body = self._async_call(uri, method="PUT",
body={"records": records},
... | Modifies an existing records for a domain. |
341,256 | def send_rgb(dev, red, green, blue, dimmer):
cv = [0 for v in range(0, 512)]
cv[0] = red
cv[1] = green
cv[2] = blue
cv[6] = dimmer
sent = dev.send_multi_value(1, cv)
return sent | Send a set of RGB values to the light |
341,257 | def load_yaml_config_file(path):
result = None
with open(path, ) as steam:
result = yaml.safe_load(steam)
return result | Returns the parsed structure from a yaml config file.
:param path: Path where the yaml file is located.
:return: The yaml configuration represented by the yaml file. |
341,258 | def read_ring_images_index():
meta = read_cumulative_iss_index()
ringfilter = meta.TARGET_DESC.str.contains("ring", case=False)
return meta[ringfilter] | Filter cumulative index for ring images.
This is done by matching the column TARGET_DESC to contain the string 'ring'
Returns
-------
pandas.DataFrame
data table containing only meta-data for ring images |
341,259 | def setup_regex(self):
self._RX_INTERFACE = (r"\n\s*interface\s+(?P<name>[a-z0-9_]+)(\s\((?P<symbol>[.\w+*=/-]+)\))?"
r"(?P<contents>.+?)"
r"end\s*interface\s+(?P=name)?")
self.RE_INTERFACE = re.compile(self._RX_INTERFACE, re.I | re.DO... | Regex definitions for parsing the code elements. |
341,260 | def findall(self, title=None):
if title is None:
return list(self._sheets)
if title not in self._titles:
return []
return list(self._titles[title]) | Return a list of worksheets with the given title.
Args:
title(str): title/name of the worksheets to return, or ``None`` for all
Returns:
list: list of contained worksheet instances (possibly empty) |
341,261 | def call_historic(self, result_callback=None, kwargs=None, proc=None):
if proc is not None:
warnings.warn(
"Support for `proc` argument is now deprecated and will be"
"removed in an upcoming release.",
DeprecationWarning,
)
... | Call the hook with given ``kwargs`` for all registered plugins and
for all plugins which will be registered afterwards.
If ``result_callback`` is not ``None`` it will be called for for each
non-None result obtained from a hook implementation.
.. note::
The ``proc`` argument... |
341,262 | def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_transmit_hold_count(self, **kwargs):
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")... | Auto Generated Code |
341,263 | def initiate_multipart_upload(self, key_name, headers=None,
reduced_redundancy=False,
metadata=None, encrypt_key=False):
query_args =
provider = self.connection.provider
if headers is None:
headers = {}
... | Start a multipart upload operation.
:type key_name: string
:param key_name: The name of the key that will ultimately result from
this multipart upload operation. This will be exactly
as the key appears in the bucket after the upload
... |
341,264 | def _serialize(
self,
element,
value,
state
):
xml_value = _hooks_apply_before_serialize(self._hooks, state, value)
if xml_value is None:
if self._default is None:
serializ... | Serialize the value to the element. |
341,265 | def create_content_addressed_github_uri(uri: URI) -> URI:
if not is_valid_api_github_uri(uri):
raise CannotHandleURI(f"{uri} does not conform to Githuburlfiletype']}."
)
return contents["git_url"] | Returns a content-addressed Github "git_url" that conforms to this scheme.
https://api.github.com/repos/:owner/:repo/git/blobs/:file_sha
Accepts Github-defined "url" that conforms to this scheme
https://api.github.com/repos/:owner/:repo/contents/:path/:to/manifest.json |
341,266 | def promise(cls, fn, *args, **kwargs):
task = cls.task(target=fn, args=args, kwargs=kwargs)
task.start()
return task | Used to build a task based on a callable function and the arguments.
Kick it off and start execution of the task.
:param fn: callable
:param args: tuple
:param kwargs: dict
:return: SynchronousTask or AsynchronousTask |
341,267 | def _save(self):
if os.path.isfile(self._full_filename):
shutil.copyfile(self._full_filename, self._full_backup_filename)
with open(self._full_filename, ) as file:
writer = csv.DictWriter(file, fieldnames=self._headers)
writer.writeheader()... | Save the model to a .csv file |
341,268 | def _type_convert(self, value):
if value is None:
return value
try:
return datetime.datetime.strptime(value, )
except ValueError:
pass
try:
return int(value)
except ValueError:
pass
try:
r... | Converts the value returned by the XMl parse into the equivalent
Python type |
341,269 | def reads_to_variant_sequences(
variant,
reads,
preferred_sequence_length,
min_alt_rna_reads=MIN_ALT_RNA_READS,
min_variant_sequence_coverage=MIN_VARIANT_SEQUENCE_COVERAGE,
variant_sequence_assembly=VARIANT_SEQUENCE_ASSEMBLY):
variant_reads = list(filter_non... | Collapse variant-supporting RNA reads into consensus sequences of
approximately the preferred length (may differ at the ends of transcripts),
filter consensus sequences by length and number of supporting RNA reads.
Parameters
----------
variant : varcode.Variant
reads : list of AlleleRead obje... |
341,270 | def fromString( cls, strdata ):
if ( not strdata ):
return None
from xml.etree import ElementTree
xelem = ElementTree.fromstring(str(strdata))
output = cls(xelem.get(), xelem.get().split())
for xcolor in xelem:
color... | Restores a color set instance from the inputed string data.
:param strdata | <str> |
341,271 | def _prepare_pattern(self, pattern):
regex, _, rest = pattern.partition()
try:
return re.compile(regex, re.I)
except re.error as e:
warnings.warn(
"Caught compiling regex: {regex}"
.format(error=e, regex=regex)
)
... | Strip out key:value pairs from the pattern and compile the regular
expression. |
341,272 | def parameters(self):
parameters = []
for k, v in self.__dict__.items():
if k.startswith("_"):
continue
is_function = False
is_set = False
if callable(v):
value = pickle.dumps(func_dump(v))
is_func... | Get the tool parameters
:return: The tool parameters along with additional information (whether they are functions or sets) |
341,273 | def merge_overlapping_predictions(tags1: List[str], tags2: List[str]) -> List[str]:
ret_sequence = []
prev_label = "O"
elif label1 != "O":
cur_label = label1
else:
cur_label = label2
cur_tag = get_coherent_next_tag(prev_label, cur_label)
... | Merge two predictions into one. Assumes the predicate in tags1 overlap with
the predicate of tags2. |
341,274 | def get_box_id(logger):
try:
box_id = None
config_file = settings.settings[]
with open(config_file) as a_file:
for a_line in a_file:
a_line = a_line.strip()
if a_line.startswith():
continue
tokens = a_line.... | retrieves box id from the /etc/synergy.conf configuration file
:raise EnvironmentError: if the configuration file could not be opened
:raise LookupError: if the configuration file does not define BOX_ID variable |
341,275 | def new_from_tokens(self, *args, **kwargs):
if kwargs.get():
args = [ x.strip() for x in args if not re.match(r, x) ]
else:
args = [ x.strip() for x in args if not re.match(r, x) ]
if len(args) > 2:
self.detect_and_fix_two_part_surname(args)
... | Takes in a name that has been split by spaces.
Names which are in [last, first] format need to be preprocessed.
The nickname must be in double quotes to be recognized as such.
This can take name parts in in these orders:
first, middle, last, nick, suffix, honorific
... |
341,276 | def batch_norm(self,
input_layer=None,
decay=0.999,
scale=False,
epsilon=0.001):
if input_layer is None:
input_layer = self.top_layer
else:
self.top_size = None
name = "batchnorm" + str(s... | Adds a Batch Normalization layer. |
341,277 | def close(key):
figure_registry = _context[]
if key not in figure_registry:
return
if _context[] == figure_registry[key]:
figure()
fig = figure_registry[key]
if hasattr(fig, ):
fig.pyplot.close()
fig.close()
del figure_registry[key]
del _context[][key] | Closes and unregister the context figure corresponding to the key.
Parameters
----------
key: hashable
Any variable that can be used as a key for a dictionary |
341,278 | def getblock(lines):
try:
tokenize.tokenize(ListReader(lines).readline, BlockFinder().tokeneater)
except EndOfBlock, eob:
return lines[:eob.args[0]]
return lines[:1] | Extract the block of code at the top of the given list of lines. |
341,279 | def update_bundle(self, work_spec, work_units, nice=0):
name
self.validate_work_spec(work_spec)
work_spec_name = work_spec[]
with self.registry.lock(identifier=self.worker_id) as session:
session.update(NICE_LEVELS, {work_spec_name: nice})
session.update(... | Load a work spec and some work units into the task list.
update the work_spec and work_units. Overwrites any existing
work spec with the same ``work_spec['name']`` and similarly
overwrites any WorkUnit with the same ``work_unit.key``
:param dict work_spec: Work spec dictionary... |
341,280 | def calc_frip(self, input_bam, input_bed, threads=4):
cmd = self.simple_frip(input_bam, input_bed, threads)
return subprocess.check_output(cmd.split(" "), shell=True) | Calculate fraction of reads in peaks.
A file of with a pool of sequencing reads and a file with peak call
regions define the operation that will be performed. Thread count
for samtools can be specified as well.
:param str input_bam: sequencing reads file
:param str input_bed: f... |
341,281 | def child_removed(self, child):
super(AndroidViewGroup, self).child_removed(child)
if child.widget is not None:
self.widget.removeView(child.widget) | Handle the child removed event from the declaration.
This handler will unparent the child toolkit widget. Subclasses
which need more control should reimplement this method. |
341,282 | def _encode_files(files, data):
if (not files):
raise ValueError("Files must be provided.")
elif isinstance(data, basestring):
raise ValueError("Data must not be a string.")
new_fields = []
fields = to_key_val_list(data or {})
files = to_key_val_... | Build the body for a multipart/form-data request.
Will successfully encode files when passed as a dict or a list of
tuples. Order is retained if data is a list of tuples but arbitrary
if parameters are supplied as a dict.
The tuples may be 2-tuples (filename, fileobj), 3-tuples (filenam... |
341,283 | def add(self, num):
try:
val = self.value() + num
except:
val = num
self.set(min(self.imax, max(self.imin, val))) | Adds num to the current value |
341,284 | def cas2mach(cas, h):
tas = cas2tas(cas, h)
M = tas2mach(tas, h)
return M | CAS Mach conversion |
341,285 | def create_comment(self, body):
assert isinstance(body, (str, unicode)), body
post_parameters = {
"body": body,
}
headers, data = self._requester.requestJsonAndCheck(
"POST",
self.url + "/comments",
input=post_parameters
)
... | :calls: `POST /repos/:owner/:repo/issues/:number/comments <http://developer.github.com/v3/issues/comments>`_
:param body: string
:rtype: :class:`github.IssueComment.IssueComment` |
341,286 | def get_access_information(self, code):
if self.config.grant_type == :
data = {: ,
: self.config.user,
: self.config.pswd}
else:
data = {: code, : ,
: self.redirect_uri}
retval = self._handle_oauth_reque... | Return the access information for an OAuth2 authorization grant.
:param code: the code received in the request from the OAuth2 server
:returns: A dictionary with the key/value pairs for ``access_token``,
``refresh_token`` and ``scope``. The ``refresh_token`` value will
be None w... |
341,287 | def project(self, projector = None):
msg = ": ADW 2018-05-05"%self.__class__.__name__
DeprecationWarning(msg)
if projector is None:
try:
self.projector = ugali.utils.projector.Projector(self.config[][][0],
... | Project coordinates on sphere to image plane using Projector class. |
341,288 | def intersperse(iterable, element):
iterable = iter(iterable)
yield next(iterable)
while True:
next_from_iterable = next(iterable)
yield element
yield next_from_iterable | Generator yielding all elements of `iterable`, but with `element`
inserted between each two consecutive elements |
341,289 | def report_object(self, key, filename, anchor_text=None, anchor_image=None,
annotation=None):
annotation = str(annotation or self.name)
filename = str(filename).strip()
if anchor_text:
anchor_text = str(anchor_text).strip()
else:
... | Writes a string to self.pipeline_objects_file. Used to report figures and others.
:param str key: name (key) of the object
:param str filename: relative path to the file (relative to parent output dir)
:param str anchor_text: text used as the link anchor test or caption to
refer to ... |
341,290 | def rotate_vec(self, vec):
xyz = Vec3(self.x, self.y, self.z)
return add_v3(vec, scale_v3(
xyz.cross(xyz.cross(vec) + scale_v3(vec, self.w)), 2.0)) | https://code.google.com/p/kri/wiki/Quaternions
v + 2.0*cross(q.xyz, cross(q.xyz,v) + q.w*v); |
341,291 | def get(self, profile_id):
ll be returned. If not, itt hit the filesystem or the web.
This method raises DataPackageRegistryException if there were any
errors.
'
if profile_id not in self._profiles:
try:
self._profiles[profile_id] = self._get_profile(... | Return the profile with the received ID as a dict
If a local copy of the profile exists, it'll be returned. If not, it'll
be downloaded from the web. The results are cached, so any subsequent
calls won't hit the filesystem or the web.
This method raises DataPackageRegistryException if ... |
341,292 | def json(
self,
filepath=None
):
self.log.debug()
dataCopy = copy.deepcopy(self.listOfDictionaries)
for d in dataCopy:
for k, v in d.iteritems():
if isinstance(v, datetime):
d[k] = v.strftime("%Y%m%dt%H%M%S")
... | *Render the data in json format*
**Key Arguments:**
- ``filepath`` -- path to the file to write the json content to. Default *None*
**Return:**
- ``renderedData`` -- the data rendered as json
**Usage:**
To render the data set as json:
.. code-... |
341,293 | def create_table_from_tabledata(
self, table_data, primary_key=None, add_primary_key_column=False, index_attrs=None
):
self.__create_table_from_tabledata(
table_data, primary_key, add_primary_key_column, index_attrs
) | Create a table from :py:class:`tabledata.TableData`.
:param tabledata.TableData table_data: Table data to create.
:param str primary_key: |primary_key|
:param tuple index_attrs: |index_attrs|
.. seealso::
:py:meth:`.create_table_from_data_matrix` |
341,294 | def email_address(self, address, owner=None, **kwargs):
return EmailAddress(self.tcex, address, owner=owner, **kwargs) | Create the Email Address TI object.
Args:
owner:
address:
**kwargs:
Return: |
341,295 | def sum_(expr):
output_type = None
if isinstance(expr, (SequenceExpr, SequenceGroupBy)):
if expr._data_type == types.boolean:
output_type = types.int64
else:
output_type = expr._data_type
return _reduction(expr, Sum, output_type) | Sum value
:param expr:
:return: |
341,296 | def validate_empty_bytes(offset: int, length: int, bytecode: bytes) -> None:
slot_length = offset + length
slot = bytecode[offset:slot_length]
if slot != bytearray(length):
raise ValidationError(
f"Bytecode segment: [{offset}:{slot_length}] is not comprised of empty bytes, "
... | Validates that segment [`offset`:`offset`+`length`] of
`bytecode` is comprised of empty bytes (b'\00'). |
341,297 | def top_x_meteor(query_dic, mark, x=1):
all_total = 0.0
with open(top_meteor_path + mark, ) as writer:
for k in query_dic:
candidate_lst = query_dic[k]
top_x = sorted(candidate_lst, key=lambda a: a[0], reverse=True)[:x]
total = 0
for t in top_... | Calculate METEOR score of the top result
:param query_dic: dict, key is qid, value is (item, meteor) tuple list, which will be ranked by 'item' as key
:param mark: string, which indicates which method is evaluated, also used as output file name here.
:param x: int, define top x
:return: average mete... |
341,298 | def _run_forever(self):
while True:
try:
tick = time.time()
asyncore.loop(timeout=self.POLL_TIMEOUT, use_poll=True)
tick += self.POLL_TIMEOUT - time.time()
if tick > 0:
... | Run configured jobs until termination request. |
341,299 | def match(self, path):
match = self._regex.search(path)
if match is not None:
remaining = path[match.end():]
groups = match.groupdict()
result = {}
for name, value in groups.items():
try:
value = self._converter... | Match a path and return ``None`` if no matching, otherwise
a dictionary of matched variables with values. If there is more
to be match in the path, the remaining string is placed in the
``__remaining__`` key of the dictionary. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.