Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
386,900 | def iteritems(self):
r
if self.columns.is_unique and hasattr(self, ):
for k in self.columns:
yield k, self._get_item_cache(k)
else:
for i, k in enumerate(self.columns):
yield k, self._ixs(i, axis=1) | r"""
Iterator over (column name, Series) pairs.
Iterates over the DataFrame columns, returning a tuple with
the column name and the content as a Series.
Yields
------
label : object
The column names for the DataFrame being iterated over.
content : Se... |
386,901 | def saturation_equivalent_potential_temperature(pressure, temperature):
r
t = temperature.to().magnitude
p = pressure.to().magnitude
e = saturation_vapor_pressure(temperature).to().magnitude
r = saturation_mixing_ratio(pressure, temperature).magnitude
th_l = t * (1000 / (p - e)) ** mpconsts.kap... | r"""Calculate saturation equivalent potential temperature.
This calculation must be given an air parcel's pressure and temperature.
The implementation uses the formula outlined in [Bolton1980]_ for the
equivalent potential temperature, and assumes a saturated process.
First, because we assume a satura... |
386,902 | def get_config_parameter_loglevel(config: ConfigParser,
section: str,
param: str,
default: int) -> int:
try:
value = config.get(section, param).lower()
if value == "debug":
return l... | Get ``loglevel`` parameter from ``configparser`` ``.INI`` file, e.g.
mapping ``'debug'`` to ``logging.DEBUG``.
Args:
config: :class:`ConfigParser` object
section: section name within config file
param: name of parameter within section
default: default value
Returns:
... |
386,903 | def decr(self, field, by=1):
return self._client.hincrby(self.key_prefix, field, by * -1) | :see::meth:RedisMap.decr |
386,904 | def get_file_checksum(path):
if not (sys.platform.startswith() or \
sys.platform in [, ]):
raise OSError()
assert isinstance(path, (str, _oldstr))
if not os.path.isfile(path):
raise IOError( %(path))
sub = subproc.Popen( %(path), bufsize=-1, shell=T... | Get the checksum of a file (using ``sum``, Unix-only).
This function is only available on certain platforms.
Parameters
----------
path: str
The path of the file.
Returns
-------
int
The checksum.
Raises
------
IOError
If the file does not exist. |
386,905 | def match(self, ra1, dec1, ra2, dec2, radius, maxmatch=1, convertToArray=True):
ra1 = numpy.array(ra1, dtype=, ndmin=1, copy=False)
dec1 = numpy.array(dec1, dtype=, ndmin=1, copy=False)
ra2 = numpy.array(ra2, dtype=, ndmin=1, copy=False)
dec2 = numpy.array(dec2, dtype=... | *Crossmatch two lists of ra/dec points*
This is very efficient for large search angles and large lists. Note, if you need to match against the same points many times, you should use a `Matcher` object
**Key Arguments:**
- ``ra1`` -- list, numpy array or single ra value (first coordinate se... |
386,906 | def add_dimension(dimension,**kwargs):
if numpy.isscalar(dimension):
dimension = {: dimension}
new_dimension = Dimension()
new_dimension.name = dimension["name"]
if "description" in dimension and dimension["description"] is not None:
new_dimension.description = dimension[... | Add the dimension defined into the object "dimension" to the DB
If dimension["project_id"] is None it means that the dimension is global, otherwise is property of a project
If the dimension exists emits an exception |
386,907 | def get_version(model_instance, version):
version_field = get_version_fieldname(model_instance)
kwargs = {: model_instance.pk, version_field: version}
return model_instance.__class__.objects.get(**kwargs) | try go load from the database one object with specific version
:param model_instance: instance in memory
:param version: version number
:return: |
386,908 | def get_learning_path_session_for_objective_bank(self, objective_bank_id=None):
if not objective_bank_id:
raise NullArgument
if not self.supports_learning_path():
raise Unimplemented()
try:
from . import sessions
except ImportError:
... | Gets the OsidSession associated with the learning path service
for the given objective bank.
arg: objectiveBankId (osid.id.Id): the Id of the
ObjectiveBank
return: (osid.learning.LearningPathSession) - a
LearningPathSession
raise: NotFound - no object... |
386,909 | def fnmatch( name, pat ):
import os
name = os.path.normcase( name )
pat = os.path.normcase( pat )
return fnmatchcase( name, pat ) | Test whether FILENAME matches PATTERN.
Patterns are Unix shell style:
* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any char not in seq
An initial period in FILENAME is not special.
Both FILENAME and PATTERN are first ... |
386,910 | def word_wrap(self):
return {
ST_TextWrappingType.SQUARE: True,
ST_TextWrappingType.NONE: False,
None: None
}[self._txBody.bodyPr.wrap] | Read-write setting determining whether lines of text in this shape
are wrapped to fit within the shape's width. Valid values are True,
False, or None. True and False turn word wrap on and off,
respectively. Assigning None to word wrap causes any word wrap
setting to be removed from the t... |
386,911 | def add_to_inventory(self):
if not self.server_attrs:
return
for addy in self.server_attrs[A.server.PUBLIC_IPS]:
self.stack.add_host(addy, self.groups, self.hostvars) | Adds host to stack inventory |
386,912 | def clear(self):
if self._cache is None:
return _NO_RESULTS
if self._cache is not None:
with self._cache as k:
res = [x.as_operation() for x in k.values()]
k.clear()
k.out_deque.clear()
return res | Clears the cache. |
386,913 | def bind_rows(df, other, join=, ignore_index=False):
df = pd.concat([df, other], join=join, ignore_index=ignore_index, axis=0)
return df | Binds DataFrames "vertically", stacking them together. This is equivalent
to `pd.concat` with `axis=0`.
Args:
df (pandas.DataFrame): Top DataFrame (passed in via pipe).
other (pandas.DataFrame): Bottom DataFrame.
Kwargs:
join (str): One of `"outer"` or `"inner"`. Outer join will pr... |
386,914 | def _get_installed(self):
from utility import get_json
fulldata = get_json(self.instpath, {})
if "installed" in fulldata:
return fulldata["installed"]
else:
return [] | Gets a list of the file paths to repo settings files that are
being monitored by the CI server. |
386,915 | def to_file(self, f, sorted=True, relativize=True, nl=None):
if sys.hexversion >= 0x02030000:
str_type = basestring
else:
str_type = str
if nl is None:
opts =
else:
opts =
if isinstance(f, str_type):
... | Write a zone to a file.
@param f: file or string. If I{f} is a string, it is treated
as the name of a file to open.
@param sorted: if True, the file will be written with the
names sorted in DNSSEC order from least to greatest. Otherwise
the names will be written in whatever or... |
386,916 | def AddAnalogShortIdRecordNoStatus(site_service, tag, time_value, value):
szService = c_char_p(site_service.encode())
szPointId = c_char_p(tag.encode())
tTime = c_long(int(time_value))
dValue = c_double(value)
nRet = dnaserv_dll.DnaAddAnalogShortIdRecordNoStatus(szService, szPointId,... | This function will add an analog value to the specified eDNA service and
tag, without an associated point status.
:param site_service: The site.service where data will be pushed
:param tag: The eDNA tag to push data. Tag only (e.g. ADE1CA01)
:param time_value: The time of the point, which MUST be in UT... |
386,917 | def _onIdle(self, evt):
evt.Skip()
FigureCanvasBase.idle_event(self, guiEvent=evt) | a GUI idle event |
386,918 | def printUniqueTFAM(tfam, samples, prefix):
fileName = prefix + ".unique_samples.tfam"
try:
with open(fileName, "w") as outputFile:
for i in sorted(samples.values()):
print >>outputFile, "\t".join(tfam[i])
except IOError:
msg = "%(fileName)s: no such file"
... | Prints a new TFAM with only unique samples.
:param tfam: a representation of a TFAM file.
:param samples: the position of the samples
:param prefix: the prefix of the output file name
:type tfam: list
:type samples: dict
:type prefix: str |
386,919 | def wait_for(self, timeout=None, **kwargs):
if len(kwargs) == 0:
raise ArgumentError("You must specify at least one message field to wait on")
spec = MessageSpec(**kwargs)
future = self._add_waiter(spec)
future.add_done_callback(lambda x: self._remove_waiter(spec, ... | Wait for a specific matching message or timeout.
You specify the message by passing name=value keyword arguments to
this method. The first message received after this function has been
called that has all of the given keys with the given values will be
returned when this function is aw... |
386,920 | def ast_to_html(self, ast, link_resolver):
out, _ = cmark.ast_to_html(ast, link_resolver)
return out | See the documentation of `to_ast` for
more information.
Args:
ast: PyCapsule, a capsule as returned by `to_ast`
link_resolver: hotdoc.core.links.LinkResolver, a link
resolver instance. |
386,921 | def cache_status(db, aid, force=False):
with db:
cur = db.cursor()
if not force:
number = 0
for number, watched in cur:
if watched == 0:
number -= 1
break
set_status(db,... | Calculate and cache status for given anime.
Don't do anything if status already exists and force is False. |
386,922 | def set_experiment_winner(experiment):
redis = _get_redis_connection()
experiment = Experiment.find(redis, experiment)
if experiment:
alternative_name = request.form.get()
alternative = Alternative(redis, alternative_name, experiment.name)
if alternative.name in experiment.alter... | Mark an alternative as the winner of the experiment. |
386,923 | def cov_from_scales(self, scales):
ord_sc = []
for stochastic in self.stochastics:
ord_sc.append(np.ravel(scales[stochastic]))
ord_sc = np.concatenate(ord_sc)
if np.squeeze(ord_sc).shape[0] != self.dim:
raise ValueError("Improper initial scales... | Return a covariance matrix built from a dictionary of scales.
`scales` is a dictionary keyed by stochastic instances, and the
values refer are the variance of the jump distribution for each
stochastic. If a stochastic is a sequence, the variance must
have the same length. |
386,924 | def _compute_fluxes(self):
sma = self.sample.geometry.sma
x0 = self.sample.geometry.x0
y0 = self.sample.geometry.y0
xsize = self.sample.image.shape[1]
ysize = self.sample.image.shape[0]
imin = max(0, int(x0 - sma - 0.5) - 1)
jmin = max(0, int(y... | Compute integrated flux inside ellipse, as well as inside a
circle defined with the same semimajor axis.
Pixels in a square section enclosing circle are scanned; the
distance of each pixel to the isophote center is compared both
with the semimajor axis length and with the length of the
... |
386,925 | def get_inventory(self):
if self._inventory is not None:
return self._inventory
self._inventory = self.resolver.getMetadata()
return self._inventory | Request the api endpoint to retrieve information about the inventory
:return: Main Collection
:rtype: Collection |
386,926 | def _parse(cls, scope):
if not scope:
return (,)
if isinstance(scope, string_types):
scope = scope.split()
scope = {str(s).lower() for s in scope if s}
return scope or (,) | Parses the input scope into a normalized set of strings.
:param scope: A string or tuple containing zero or more scope names.
:return: A set of scope name strings, or a tuple with the default scope name.
:rtype: set |
386,927 | def api_notifications():
event_type = request.values[]
assignment_id = request.values[]
db.logger.debug(,
event_type, assignment_id)
q.enqueue(worker_function, event_type, assignment_id, None)
db.logger.debug(, len(q),
.join(q.job_ids))
return ... | Receive MTurk REST notifications. |
386,928 | def info(self, correlation_id, message, *args, **kwargs):
self._format_and_write(LogLevel.Info, correlation_id, None, message, args, kwargs) | Logs an important information message
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param message: a human-readable message to log.
:param args: arguments to parameterize the message.
:param kwargs: arguments to parameterize the message. |
386,929 | def morph(clm1, clm2, t, lmax):
clm = (1 - t) * clm1 + t * clm2
grid_reco = clm.expand(lmax=lmax)
agrid_reco = grid_reco.to_array()
pts = []
for i, longs in enumerate(agrid_reco):
ilat = grid_reco.lats()[i]
for j, value in enumerate(longs):
ilong = grid_reco.lons()... | Interpolate linearly the two sets of sph harm. coeeficients. |
386,930 | def transform_doc_comments(text):
try:
while True:
found = DOC_COMMENT_SEE_PATTERN.search(text)
if found is None:
break
ref = found.group("attr_value").replace("<", "\<").replace("`", "\`")
reftype = "any"
... | Parse XML content for references and other syntax.
This avoids an LXML dependency, we only need to parse out a small subset
of elements here. Iterate over string to reduce regex pattern complexity
and make substitutions easier
.. seealso::
`Doc comment reference <https://m... |
386,931 | def chmod(self, path, mode, follow_symlinks=True):
try:
file_object = self.resolve(path, follow_symlinks, allow_fd=True)
except IOError as io_error:
if io_error.errno == errno.ENOENT:
self.raise_os_error(errno.ENOENT, path)
raise
if se... | Change the permissions of a file as encoded in integer mode.
Args:
path: (str) Path to the file.
mode: (int) Permissions.
follow_symlinks: If `False` and `path` points to a symlink,
the link itself is affected instead of the linked object. |
386,932 | def parse_variant_id(chrom, pos, ref, alt, variant_type):
return generate_md5_key([chrom, pos, ref, alt, variant_type]) | Parse the variant id for a variant
variant_id is used to identify variants within a certain type of
analysis. It is not human readable since it is a md5 key.
Args:
chrom(str)
pos(str)
ref(str)
alt(str)
variant_type(str): 'clinical' or 'research'
Returns:
... |
386,933 | def ucc_circuit(theta):
generator = sX(0) * sY(1)
initial_prog = Program().inst(X(1), X(0))
program = initial_prog + exponentiate(float(theta) * generator)
return program | Implements
exp(-i theta X_{0}Y_{1})
:param theta: rotation parameter
:return: pyquil.Program |
386,934 | def add_func_edges(dsp, fun_id, nodes_bunch, edge_weights=None, input=True,
data_nodes=None):
add_edge = _add_edge_dmap_fun(dsp.dmap, edge_weights)
node, add_data = dsp.dmap.nodes, dsp.add_data
remove_nodes = dsp.dmap.remove_nodes_from
msg = % [, ][input]
i, j = ... | Adds function node edges.
:param dsp:
A dispatcher that identifies the model adopted.
:type dsp: schedula.Dispatcher
:param fun_id:
Function node id.
:type fun_id: str
:param nodes_bunch:
A container of nodes which will be iterated through once.
:type nodes_bunch: iter... |
386,935 | def _insert_lcl_level(pressure, temperature, lcl_pressure):
interp_temp = interpolate_1d(lcl_pressure, pressure, temperature)
loc = pressure.size - pressure[::-1].searchsorted(lcl_pressure)
return np.insert(temperature.m, loc, interp_temp.m) * temperature.units | Insert the LCL pressure into the profile. |
386,936 | def instantiate(self, **extra_args):
input_block = self.input_block.instantiate()
backbone = self.backbone.instantiate(**extra_args)
return StochasticPolicyModel(input_block, backbone, extra_args[]) | Instantiate the model |
386,937 | def iterstruct(self):
from rowgenerators.rowpipe.json import add_to_struct
json_headers = self.json_headers
for row in islice(self, 1, None):
d = {}
for pos, jh in json_headers:
add_to_struct(d, jh, row[pos])
yield d | Yield data structures built from the JSON header specifications in a table |
386,938 | def channel2int(channel):
if channel is None:
return None
if isinstance(channel, int):
return channel
if hasattr(channel, "lower"):
match = re.match(r, channel)
if match:
return int(match.group(1))
return None | Try to convert the channel to an integer.
:param channel:
Channel string (e.g. can0, CAN1) or integer
:returns: Channel integer or `None` if unsuccessful
:rtype: int |
386,939 | def z_axis_rotation(theta):
R = np.array([[np.cos(theta), -np.sin(theta), 0],
[np.sin(theta), np.cos(theta), 0],
[0, 0, 1]])
return R | Generates a 3x3 rotation matrix for a rotation of angle
theta about the z axis.
Parameters
----------
theta : float
amount to rotate, in radians
Returns
-------
:obj:`numpy.ndarray` of float
A random 3x3 rotation matrix. |
386,940 | def parsemeta(metadataloc):
if os.path.isdir(metadataloc):
metalist = glob.glob(os.path.join(metadataloc, METAPATTERN))
if not metalist:
raise MTLParseError(
"No files matching metadata file pattern in directory %s."
% metadataloc)
elif ... | Parses the metadata from a Landsat image bundle.
Arguments:
metadataloc: a filename or a directory.
Returns metadata dictionary |
386,941 | def get_file_language(self, file):
for language in self.__languages:
if re.search(language.extensions, file):
LOGGER.debug("> file detected language: .".format(file, language.name))
return language | Returns the language of given file.
:param file: File to get language of.
:type file: unicode
:return: File language.
:rtype: Language |
386,942 | def set_col_width(self, col, tab, width):
try:
old_width = self.col_widths.pop((col, tab))
except KeyError:
old_width = None
if width is not None:
self.col_widths[(col, tab)] = float(width) | Sets column width |
386,943 | def _set_and_filter(self):
fmtos = []
seen = set()
for key in self._force:
self._registered_updates.setdefault(key, getattr(self, key).value)
for key, value in chain(
six.iteritems(self._registered_updates),
six.iteritems(
... | Filters the registered updates and sort out what is not needed
This method filters out the formatoptions that have not changed, sets
the new value and returns an iterable that is sorted by the priority
(highest priority comes first) and dependencies
Returns
-------
list... |
386,944 | def get_or_create(cls, name):
obj = cls.query.filter_by(name=name).one_or_none()
if obj:
return obj
try:
with session.begin_nested():
obj = cls(name=name)
session.add(obj)
session.flush()
return obj
... | Return the instance of the class with the specified name. If it doesn't
already exist, create it. |
386,945 | def _set_motion_detection(self, enable):
url = (
) % self.root_url
enabled = self._motion_detection_xml.find(self.element_query())
if enabled is None:
_LOGGING.error("CouldnenabledXML: %struefalseUnable to set MotionDetection, error: %sAuthentication failedt ... | Set desired motion detection state on camera |
386,946 | def page_missing(request, page_name, revision_requested, protected=False):
return Response(
generate_template(
"page_missing.html",
page_name=page_name,
revision_requested=revision_requested,
protected=protected,
),
status=404,
) | Displayed if page or revision does not exist. |
386,947 | def load_ensembl_coverage(cohort, coverage_path, min_tumor_depth, min_normal_depth=0,
pageant_dir_fn=None):
if pageant_dir_fn is None:
pageant_dir_fn = lambda patient: patient.id
columns_both = [
"depth1",
"depth2",
"onBP1",
"onBP2",... | Load in Pageant CoverageDepth results with Ensembl loci.
coverage_path is a path to Pageant CoverageDepth output directory, with
one subdirectory per patient and a `cdf.csv` file inside each patient subdir.
If min_normal_depth is 0, calculate tumor coverage. Otherwise, calculate
join tumor/normal cove... |
386,948 | def Match(self, artifact=None, os_name=None, cpe=None, label=None):
return [
c for c in self.conditions if c.Match(artifact, os_name, cpe, label)
] | Test if host data should trigger a check.
Args:
artifact: An artifact name.
os_name: An OS string.
cpe: A CPE string.
label: A label string.
Returns:
A list of conditions that match. |
386,949 | def export(self, filepath, encoding="utf-8", gzipped=True):
data = json.dumps(self.word_frequency.dictionary, sort_keys=True)
write_file(filepath, encoding, gzipped, data) | Export the word frequency list for import in the future
Args:
filepath (str): The filepath to the exported dictionary
encoding (str): The encoding of the resulting output
gzipped (bool): Whether to gzip the dictionary or not |
386,950 | def app_versions(self):
if not self._app_versions:
app_versions_url = self._build_url()
response = self._request(, app_versions_url)
if response.status_code == requests.codes.not_found:
self._app_versions = []
elif response.status_code =... | List of the versions of the internal KE-chain 'app' modules. |
386,951 | def update_progress(opts, progress, progress_iter, out):
try:
progress_outputter = salt.loader.outputters(opts)[out]
except KeyError:
log.warning()
return False
progress_outputter(progress, progress_iter) | Update the progress iterator for the given outputter |
386,952 | def summed_probabilities(self, choosers, alternatives):
if len(alternatives) == 0 or len(choosers) == 0:
return pd.Series()
logger.debug(
.format(
self.name))
probs = []
for name, df in self._iter_groups(choosers):
probs.appe... | Returns the sum of probabilities for alternatives across all
chooser segments.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
Must have a column matching the .segmentation_col attribute.
alte... |
386,953 | def vsound(H):
T = temperature(H)
a = np.sqrt(gamma * R * T)
return a | Speed of sound |
386,954 | def open_tablebase(directory: PathLike, *, libgtb: Any = None, LibraryLoader: Any = ctypes.cdll) -> Union[NativeTablebase, PythonTablebase]:
try:
if LibraryLoader:
return open_tablebase_native(directory, libgtb=libgtb, LibraryLoader=LibraryLoader)
except (OSError, RuntimeError) as err:
... | Opens a collection of tables for probing.
First native access via the shared library libgtb is tried. You can
optionally provide a specific library name or a library loader.
The shared library has global state and caches, so only one instance can
be open at a time.
Second, pure Python probing code... |
386,955 | def get_phonetic_info(self, lang):
phonetic_data = self.all_phonetic_data if lang != LC_TA else self.tamil_phonetic_data
phonetic_vectors = self.all_phonetic_vectors if lang != LC_TA else self.tamil_phonetic_vectors
return phonetic_data, phonetic_vectors | For a specified language (lang), it returns the matrix and the vecto
containing specifications of the characters. |
386,956 | def keys_to_datetime(obj, *keys):
if not keys:
return obj
for k in keys:
if k not in obj:
continue
v = obj[k]
if not isinstance(v, string_types):
continue
obj[k] = parse_datetime(v)
return obj | Converts all the keys in an object to DateTime instances.
Args:
obj (dict): the JSON-like ``dict`` object to modify inplace.
keys (str): keys of the object being converted into DateTime
instances.
Returns:
dict: ``obj`` inplace.
>>> keys_to_... |
386,957 | def get_ready_user_tasks(self):
return [t for t in self.get_tasks(Task.READY)
if not self._is_engine_task(t.task_spec)] | Returns a list of User Tasks that are READY for user action |
386,958 | def create_shepherd_tour(self, name=None, theme=None):
shepherd_theme = "shepherd-theme-arrows"
if theme:
if theme.lower() == "default":
shepherd_theme = "shepherd-theme-default"
elif theme.lower() == "dark":
shepherd_theme = "shepherd-th... | Creates a Shepherd JS website tour.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
theme - Sets the default theme for the tour.
Choose from "light"/"arrows", "dark", "default", "... |
386,959 | def loc_info(text, index):
if index > len(text):
raise ValueError()
line, last_ln = text.count(, 0, index), text.rfind(, 0, index)
col = index - (last_ln + 1)
return (line, col) | Location of `index` in source code `text`. |
386,960 | def enqueue(self, message, *, delay=None):
queue_name = message.queue_name
message = message.copy(options={
"redis_message_id": str(uuid4()),
})
if delay is not None:
queue_name = dq_name(queue_name)
message_eta = ... | Enqueue a message.
Parameters:
message(Message): The message to enqueue.
delay(int): The minimum amount of time, in milliseconds, to
delay the message by. Must be less than 7 days.
Raises:
ValueError: If ``delay`` is longer than 7 days. |
386,961 | def pgrrec(body, lon, lat, alt, re, f):
body = stypes.stringToCharP(body)
lon = ctypes.c_double(lon)
lat = ctypes.c_double(lat)
alt = ctypes.c_double(alt)
re = ctypes.c_double(re)
f = ctypes.c_double(f)
rectan = stypes.emptyDoubleVector(3)
libspice.pgrrec_c(body, lon, lat, alt, re, ... | Convert planetographic coordinates to rectangular coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pgrrec_c.html
:param body: Body with which coordinate system is associated.
:type body: str
:param lon: Planetographic longitude of a point (radians).
:type lon: float
:param ... |
386,962 | def from_collection_xml(cls, xml_content):
xml_dataset = xmltodict.parse(xml_content, process_namespaces=False)
return cls(xml_records) | Build a :class:`~zenodio.harvest.Datacite3Collection` from
Datecite3-formatted XML.
Users should use :func:`zenodio.harvest.harvest_collection` to build a
:class:`~zenodio.harvest.Datacite3Collection` for a Community.
Parameters
----------
xml_content : str
... |
386,963 | def get_foldrate(seq, secstruct):
seq = ssbio.protein.sequence.utils.cast_to_str(seq)
url =
values = {: seq, : secstruct}
data = urlencode(values)
data = data.encode()
response = urlopen(url, data)
result = str(response.read())
ind = str.find(result, )
result2 = result[ind:... | Submit sequence and structural class to FOLD-RATE calculator (http://www.iitm.ac.in/bioinfo/fold-rate/)
to calculate kinetic folding rate.
Args:
seq (str, Seq, SeqRecord): Amino acid sequence
secstruct (str): Structural class: `all-alpha``, ``all-beta``, ``mixed``, or ``unknown``
Returns:
... |
386,964 | def widths_in_range_mm(
self,
minwidth=EMIR_MINIMUM_SLITLET_WIDTH_MM,
maxwidth=EMIR_MAXIMUM_SLITLET_WIDTH_MM
):
list_ok = []
for i in range(EMIR_NBARS):
slitlet_ok = minwidth <= self._csu_bar_slit_width[i] <= maxwidth
if slitlet_o... | Return list of slitlets which width is within given range
Parameters
----------
minwidth : float
Minimum slit width (mm).
maxwidth : float
Maximum slit width (mm).
Returns
-------
list_ok : list
List of booleans indicating whe... |
386,965 | def calc_freefree_kappa(ne, t, hz):
return 9.78e-3 * ne**2 * hz**-2 * t**-1.5 * (24.5 + np.log(t) - np.log(hz)) | Dulk (1985) eq 20, assuming pure hydrogen. |
386,966 | def _get_button_attrs(self, tool):
attrs = getattr(tool, , {})
if in attrs:
attrs.pop()
if in attrs:
attrs.pop()
default_attrs = {
: attrs.get(, ),
: getattr(tool, , ),
}
standa... | Get the HTML attributes associated with a tool.
There are some standard attributes (class and title) that the template
will always want. Any number of additional attributes can be specified
and passed on. This is kinda awkward and due for a refactor for
readability. |
386,967 | def check_ip(ip, log=False):
if log:
print(.format(ip))
request_timeout = 0.1
try:
tv_url = .format(ip)
request = requests.get(tv_url, timeout=request_timeout)
except requests.exceptions.ConnectTimeout:
return False
... | Attempts a connection to the TV and checks if there really is a TV. |
386,968 | def _reproject(wcs1, wcs2):
import gwcs
forward_origin = []
if isinstance(wcs1, fitswcs.WCS):
forward = wcs1.all_pix2world
forward_origin = [0]
elif isinstance(wcs2, gwcs.wcs.WCS):
forward = wcs1.forward_transform
else:
r... | Perform the forward transformation of ``wcs1`` followed by the
inverse transformation of ``wcs2``.
Parameters
----------
wcs1, wcs2 : `~astropy.wcs.WCS` or `~gwcs.wcs.WCS`
The WCS objects.
Returns
-------
result : func
Function to compute... |
386,969 | def broadcast(self, msg):
if getattr(msg, , False):
for m in msg:
self._send( % self._escape(str(m)))
else:
self._send( % self._escape(str(msg))) | Broadcasts msg to Scratch. msg can be a single message or an iterable
(list, tuple, set, generator, etc.) of messages. |
386,970 | def search_windows(
self, winname=None, winclass=None, winclassname=None,
pid=None, only_visible=False, screen=None, require=False,
searchmask=0, desktop=None, limit=0, max_depth=-1):
windowlist_ret = ctypes.pointer(window_t(0))
nwindows_ret = ctypes.c_uint(0... | Search for windows.
:param winname:
Regexp to be matched against window name
:param winclass:
Regexp to be matched against window class
:param winclassname:
Regexp to be matched against window class name
:param pid:
Only return windows fro... |
386,971 | def sparse_dot_product_attention(q, k, v, bi, use_map_fn, experts_params):
batch_size, nb_heads, _, depth = common_layers.shape_list(q)
@expert_utils.add_name_scope()
def flatten_first_dims(x):
if x.get_shape().as_list()[0] == 1:
return tf.squeeze(x, axis=0)
x = tf.transpose(x, p... | Sparse multihead self attention.
Perform an approximation of the full multihead attention by dispatching
the tokens using their keys/values. Thus the attention matrix are only
computed each times on a subset of the tokens.
Notes:
* The function don't perform scaling here (multihead_attention does
the /sq... |
386,972 | def _set_ccm_interval(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u: {: 3}, u: {: 60000}, ... | Setter method for ccm_interval, mapped from YANG variable /cfm_state/cfm_detail/domain/ma/ccm_interval (ccm-intervals)
If this variable is read-only (config: false) in the
source YANG file, then _set_ccm_interval is considered as a private
method. Backends looking to populate this variable should
do so ... |
386,973 | def _get_dataset_showcase_dict(self, showcase):
if isinstance(showcase, hdx.data.showcase.Showcase) or isinstance(showcase, dict):
if not in showcase:
showcase = hdx.data.showcase.Showcase.read_from_hdx(showcase[])
showcase = showcase[]
elif not... | Get dataset showcase dict
Args:
showcase (Union[Showcase,Dict,str]): Either a showcase id or Showcase metadata from a Showcase object or dictionary
Returns:
dict: dataset showcase dict |
386,974 | def load(self, buf = None):
if self.password is None and self.keyfile is None:
raise KPError()
elif self.filepath is None and buf is None:
raise KPError()
if buf is None:
buf = self.read_buf()
header = buf[:124]
... | This method opens an existing database.
self.password/self.keyfile and self.filepath must be set. |
386,975 | def create_form_data(self, **kwargs):
children = kwargs.get(, [])
sort_order = kwargs.get(, None)
solr_response = kwargs.get(, None)
superuser = kwargs.get(, False)
vocabularies = self.get_vocabularies()
for element in children:
... | Create groupings of form elements. |
386,976 | def create(self, healthCheckNotification, instance, ipAddressResourceId, name, notificationContacts, rules,
loadBalancerClassOfServiceID=1, *args, **kwargs):
response = self._call(method=SetEnqueueLoadBalancerCreation,
healthCheckNotification=healthCheckNoti... | :type healthCheckNotification: bool
:type instance: list[Instance]
:type ipAddressResourceId: list[int]
:type loadBalancerClassOfServiceID: int
:type name: str
:type notificationContacts: NotificationContacts or list[NotificationContact]
:type rules: Rules
:param ... |
386,977 | def fromXml(xml):
slide = XWalkthroughSlide(**xml.attrib)
for xgraphic in xml:
slide.addItem(XWalkthroughItem.fromXml(xgraphic))
return slide | Creates a new slide from XML.
:return <XWalkthroughSlide> |
386,978 | def ndwi(self):
data = self._read(self[self._ndwi_bands,...]).astype(np.float32)
return (data[1,:,:] - data[0,:,:]) / (data[0,:,:] + data[1,:,:]) | Calculates Normalized Difference Water Index using Coastal and NIR2 bands for WV02, WV03.
For Landsat8 and sentinel2 calculated by using Green and NIR bands.
Returns: numpy array of ndwi values |
386,979 | def sha1_hexdigest(self):
if self._sha1_hexdigest is None:
self._sha1_hexdigest = hashlib.sha1(self._pem_bytes).hexdigest()
return self._sha1_hexdigest | A SHA-1 digest of the whole object for easy differentiation.
.. versionadded:: 18.1.0 |
386,980 | def get_abi_size(self, target_data, context=None):
llty = self._get_ll_pointer_type(target_data, context)
return target_data.get_pointee_abi_size(llty) | Get the ABI size of this type according to data layout *target_data*. |
386,981 | def conv_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs):
return conv_block_internal(conv, inputs, filters,
dilation_rates_and_kernel_sizes, **kwargs) | A block of standard 2d convolutions. |
386,982 | def context_spec(self):
from harpoon.option_spec import image_objs
return dict_from_bool_spec(lambda meta, val: {"enabled": val}
, create_spec(image_objs.Context
, validators.deprecated_key("use_git_timestamps", "Since docker 1.8, timestamps no longer invalidate the ... | Spec for specifying context options |
386,983 | def merge_results(x, y):
z = x.copy()
for key, value in y.items():
if isinstance(value, list) and isinstance(z.get(key), list):
z[key] += value
else:
z[key] = value
return z | Given two dicts, x and y, merge them into a new dict as a shallow copy.
The result only differs from `x.update(y)` in the way that it handles list
values when both x and y have list values for the same key. In which case
the returned dictionary, z, has a value according to:
z[key] = x[key] + z[key]
... |
386,984 | def _get_variables(self) -> Dict[str, str]:
variables = {}
for group in self.groups:
setting_variables = self._read_group_variables(group)
variables.update(setting_variables)
return variables | Gets the variables that should be set for this project.
:return: the variables |
386,985 | def _get_option(config, supplement, section, option, fallback=None):
if supplement:
return_value = supplement.get(section, option, fallback=config.get(section, option, fallback=fallback))
else:
return_value = config.get(section, option, fallback=fallback)
if fal... | Reads an option for a configuration file.
:param configparser.ConfigParser config: The main config file.
:param configparser.ConfigParser supplement: The supplement config file.
:param str section: The name of the section op the option.
:param str option: The name of the option.
... |
386,986 | def runInParallel(*fns):
proc = []
for fn in fns:
p = Process(target=fn)
p.start()
proc.append(p)
for p in proc:
p.join() | Runs multiple processes in parallel.
:type: fns: def |
386,987 | def age_to_BP(age, age_unit):
ageBP = -1e9
if age_unit == "Years AD (+/-)" or age_unit == "Years Cal AD (+/-)":
if age < 0:
age = age+1
ageBP = 1950-age
elif age_unit == "Years BP" or age_unit == "Years Cal BP":
ageBP = age
elif age_unit == "ka":
ageBP ... | Convert an age value into the equivalent in time Before Present(BP) where Present is 1950
Returns
---------
ageBP : number |
386,988 | def trace_plot(precisions, path, n_edges=20, ground_truth=None, edges=[]):
_check_path(path)
assert len(path) == len(precisions)
assert len(precisions) > 0
path = np.array(path)
dim, _ = precisions[0].shape
if not edges:
base_precision = np.copy(precisions[-1])
base_p... | Plot the change in precision (or covariance) coefficients as a function
of changing lambda and l1-norm. Always ignores diagonals.
Parameters
-----------
precisions : array of len(path) 2D ndarray, shape (n_features, n_features)
This is either precision_ or covariance_ from an InverseCovariance... |
386,989 | def error(self, msg=, exit=None):
def handler(exc):
if msg:
self.perr(msg.format(err=exc))
if exit is not None:
self.quit(exit)
return handler | Error handler factory
This function takes a message with optional ``{err}`` placeholder and
returns a function that takes an exception object, prints the error
message to STDERR and optionally quits.
If no message is supplied (e.g., passing ``None`` or ``False`` or empty
string... |
386,990 | def hub_virtual_network_connections(self):
api_version = self._get_api_version()
if api_version == :
from .v2018_04_01.operations import HubVirtualNetworkConnectionsOperations as OperationClass
else:
raise NotImplementedError("APIVersion {} is not available".form... | Instance depends on the API version:
* 2018-04-01: :class:`HubVirtualNetworkConnectionsOperations<azure.mgmt.network.v2018_04_01.operations.HubVirtualNetworkConnectionsOperations>` |
386,991 | def load_yaml(yaml_file: str) -> Any:
with open(yaml_file, ) as file:
return ruamel.yaml.load(file, ruamel.yaml.RoundTripLoader) | Load YAML from file.
:param yaml_file: path to YAML file
:return: content of the YAML as dict/list |
386,992 | def post(self, command, data=None):
now = calendar.timegm(datetime.datetime.now().timetuple())
if now > self.expiration:
auth = self.__open("/oauth/token", data=self.oauth)
self.__sethead(auth[])
return self.__open("%s%s" % (self.api, command),
... | Post data to API. |
386,993 | def from_domain(cls, domain, version=None, require_https=True):
url = + domain +
try:
return cls.from_url(url, version=version, require_https=require_https)
except MissingHive:
url = + domain +
return cls.from_url(url, version=version, require_htt... | Try to find a hive for the given domain; raise an error if we have to
failover to HTTP and haven't explicitly suppressed it in the call. |
386,994 | def search_feature_sets(self, dataset_id):
request = protocol.SearchFeatureSetsRequest()
request.dataset_id = dataset_id
request.page_size = pb.int(self._page_size)
return self._run_search_request(
request, "featuresets", protocol.SearchFeatureSetsResponse) | Returns an iterator over the FeatureSets fulfilling the specified
conditions from the specified Dataset.
:param str dataset_id: The ID of the
:class:`ga4gh.protocol.Dataset` of interest.
:return: An iterator over the :class:`ga4gh.protocol.FeatureSet`
objects defined by ... |
386,995 | def check_files(cls, dap):
problems = list()
dirname = os.path.dirname(dap._meta_location)
if dirname:
dirname +=
files = [f for f in dap.files if f.startswith(dirname)]
if len(files) == 1:
msg =
problems.append(DapProblem(msg, leve... | Check that there are only those files the standard accepts.
Return list of DapProblems. |
386,996 | def _boxFromData(self, messageData):
inputBoxes = parseString(messageData)
if not len(inputBoxes) == 1:
raise MalformedMessage()
[inputBox] = inputBoxes
return inputBox | A box.
@param messageData: a serialized AMP box representing either a message
or an error.
@type messageData: L{str}
@raise MalformedMessage: if the C{messageData} parameter does not parse
to exactly one AMP box. |
386,997 | def show(i):
import os
o=i.get(,)
curdir=os.getcwd()
duoa=i.get(,)
reset=i.get(,)
stable=i.get(,)
version=i.get(,)
if stable==: version=
r=ck.list_data({:work[],
:duoa})
if r[]>0: return r
if o==:
ck.out()
ck.out()
r=ck.rel... | Input: {
(data_uoa) - repo UOA
(reset) - if 'yes', reset repos
(stable) - take stable version (highly experimental)
(version) - checkout version (default - stable)
}
Output: {
return - return code = 0, if successful
... |
386,998 | def organization_memberships(self, user):
return self._query_zendesk(self.endpoint.organization_memberships, , id=user) | Retrieve the organization memberships for this user.
:param user: User object or id |
386,999 | def image_export(self, image_name, dest_url, remote_host=None):
try:
return self._imageops.image_export(image_name, dest_url,
remote_host)
except exception.SDKBaseException:
LOG.error("Failed to export image " % image_name)
... | Export the image to the specified location
:param image_name: image name that can be uniquely identify an image
:param dest_url: the location of exported image, eg.
file:///opt/images/export.img, now only support export to remote server
or local server's file system
:param remote... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.