Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
342,300 | def _selector_as_string(self, selector):
return .join(
.join(token.as_css() for token in strip_whitespace(token_list))
for token_list in split_on_comma(selector)) | Returns a selector as a CSS string
:param selector: A list of tinycss Tokens
:type selector: list
:returns: The CSS string for the selector
:rtype: str |
342,301 | def run_rsem(job, star_bams, univ_options, rsem_options):
job.fileStore.logToMaster( % univ_options[])
work_dir = job.fileStore.getLocalTempDir()
input_files = {
: star_bams[],
: rsem_options[]}
input_files = get_files_from_filestore(job, input_files, work_dir, docker=True)
para... | This module will run rsem on the RNA Bam file.
ARGUMENTS
1. star_bams: Dict of input STAR bams
star_bams
+- 'rnaAligned.toTranscriptome.out.bam': <JSid>
2. univ_options: Dict of universal arguments used by almost all tools
univ_options
+- 'dockerhub': <docker... |
342,302 | def _try_get_string(dev, index, langid = None, default_str_i0 = "",
default_access_error = "Error Accessing String"):
if index == 0 :
string = default_str_i0
else:
try:
if langid is None:
string = util.get_string(dev, index)
else:
... | try to get a string, but return a string no matter what |
342,303 | def setup(app):
app.add_config_value(
,
default=None,
rebuild=False
)
try:
app.add_config_value(
,
default=None,
rebuild=False
)
except:
pass
app.connect(, add_html_link)
app.connect(, create_sitemap)
a... | Setup connects events to the sitemap builder |
342,304 | def set_attributes(name, attributes, region=None, key=None, keyid=None,
profile=None):
{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
al = attrib... | Set attributes on an ELB.
name (string)
Name of the ELB instance to set attributes for
attributes
A dict of attributes to set.
Valid attributes are:
access_log (dict)
enabled (bool)
Enable storage of access logs.
s3_bucket_name (string)... |
342,305 | def set_signal_replacement(self, signum, handle):
signame = lookup_signame(signum)
if signame is None:
self.dbgr.intf[-1].errmsg(("%s is not a signal number"
" I know about.") % signum)
return False
self.s... | A replacement for signal.signal which chains the signal behind
the debugger's handler |
342,306 | def status(ctx):
status = ctx.status()
click.echo(click.style(, bold=True))
if status[]:
line = .format(
status[][],
status[][])
click.echo(click.style(line, fg=))
click.echo(click.style(, bold=True))
if status[]:
line = .format(
statu... | Print a status of this Lambda function |
342,307 | def do_resolve(self, definitions):
filtered = []
for p in self.ports:
ref = qualify(p.binding, self.root, definitions.tns)
binding = definitions.bindings.get(ref)
if binding is None:
raise Exception("binding , not-found" % (p.binding,))
... | Resolve named references to other WSDL objects. Ports without SOAP
bindings are discarded.
@param definitions: A definitions object.
@type definitions: L{Definitions} |
342,308 | def sent(self):
sent_updates = []
url = PATHS[] % self.profile_id
response = self.api.get(url=url)
for update in response[]:
sent_updates.append(Update(api=self.api, raw_response=update))
self.__sent = sent_updates
return self.__sent | Returns an array of updates that have been sent from the buffer for an
individual social media profile. |
342,309 | def attempt_json_write(
path: str,
contents: dict,
mode: str =
) -> typing.Union[None, Exception]:
try:
with open(path, mode) as f:
json.dump(contents, f)
return None
except Exception as error:
return error | Attempts to write the specified JSON content to file.
:param path:
The path to the file where the JSON serialized content will be written.
:param contents:
The JSON data to write to the file
:param mode:
The mode used to open the file where the content will be written.
:r... |
342,310 | def unique_sites(self, scaled_positions, symprec=1e-3, output_mask=False):
scaled = np.array(scaled_positions, ndmin=2)
symnorm = self.symmetry_normalised_sites(scaled)
perm = np.lexsort(symnorm.T)
iperm = perm.argsort()
xmask = np.abs(np.diff(symnorm[perm], axis=0)).max... | Returns a subset of *scaled_positions* containing only the
symmetry-unique positions. If *output_mask* is True, a boolean
array masking the subset is also returned.
Example:
>>> from ase.lattice.spacegroup import Spacegroup
>>> sg = Spacegroup(225) # fcc
>>> sg.unique... |
342,311 | def data_changed(self, change):
index = self.index
if index:
self.view.model.dataChanged.emit(index, index) | Notify the model that data has changed in this cell! |
342,312 | async def _redirect(self, response_obj):
redirect, force_get, location = False, None, None
if 300 <= response_obj.status_code < 400:
if response_obj.status_code == 303:
self.data, self.json, self.files = None, None, None
if response_obj.status_code in [30... | Calls the _check_redirect method of the supplied response object
in order to determine if the http status code indicates a redirect.
Returns:
Response: May or may not be the result of recursive calls due
to redirects!
Notes:
If it does redirect, it calls the... |
342,313 | def visit_importfrom(self, node):
module_filename = node.root().file
if fnmatch.fnmatch(module_filename, ) and \
not fnmatch.fnmatch(module_filename, ):
return
basename = node.modname
self._check_blacklisted_module(node, basename) | triggered when a from statement is seen |
342,314 | def recurrence_to_lag(rec, pad=True, axis=-1):
timelagLag (zero-padded)timeLag (no padding)
axis = np.abs(axis)
if rec.ndim != 2 or rec.shape[0] != rec.shape[1]:
raise ParameterError(
.format(rec.shape))
sparse = scipy.sparse.issparse(rec)
roll_ax = None
... | Convert a recurrence matrix into a lag matrix.
`lag[i, j] == rec[i+j, j]`
Parameters
----------
rec : np.ndarray, or scipy.sparse.spmatrix [shape=(n, n)]
A (binary) recurrence matrix, as returned by `recurrence_matrix`
pad : bool
If False, `lag` matrix is square, which is equi... |
342,315 | def get_elem_type(elem):
elem_type = None
if isinstance(elem, list):
if elem[0].get("type") == "radio":
elem_type = "radio"
else:
raise ValueError(u"Unknown element type: {}".format(elem))
elif elem.name == "select":
elem_type = "select"
elif elem.n... | Get elem type of soup selection
:param elem: a soup element |
342,316 | def get_services(root, hosts_map, view=None):
services_list = []
mgmt_service = root.get_cloudera_manager().get_service()
services_list.append({"hostname": CM_DUMMY_HOST,
"name": mgmt_service.name,
"display_name": "CM Managed Service: %s" % (mgmt_service.name,),
... | Gets a list of objects representing the Nagios services.
Each object contains the Nagios hostname, service name, service display
name, and service health summary. |
342,317 | def registration_backend(backend=None, namespace=None):
backend = backend or ORGS_REGISTRATION_BACKEND
class_module, class_name = backend.rsplit(".", 1)
mod = import_module(class_module)
return getattr(mod, class_name)(namespace=namespace) | Returns a specified registration backend
Args:
backend: dotted path to the registration backend class
namespace: URL namespace to use
Returns:
an instance of an RegistrationBackend |
342,318 | def get_total_paid_for_remaining_stock(self) -> Decimal:
paid = Decimal(0)
accounts = self.get_holding_accounts()
for acc in accounts:
splits = self.get_available_splits_for_account(acc)
paid += sum(split.value for split in splits)
return paid | Returns the amount paid only for the remaining stock |
342,319 | def execute(self, sensor_graph, scope_stack):
parent = scope_stack[-1]
alloc = parent.allocator
trigger_stream, trigger_cond = parent.trigger_chain()
rpc_const = alloc.allocate_stream(DataStream.ConstantType, attach=True)
rpc_val = (self.slot_id.address << 16) | self.r... | Execute this statement on the sensor_graph given the current scope tree.
This adds a single node to the sensor graph with the call_rpc function
as is processing function.
Args:
sensor_graph (SensorGraph): The sensor graph that we are building or
modifying
... |
342,320 | def get(self, fallback=not_set):
envvar_value = self._get_envvar_value()
if envvar_value is not not_set:
return envvar_value
if self.has_value:
if self._value is not not_set:
return self._value
else:
return copy.deepc... | Returns config value.
See Also:
:meth:`.set` and :attr:`.value` |
342,321 | def draw_axes(self):
self.canvas.delete()
rect = 50, 50, self.w - 50, self.h - 50
self.canvas.create_rectangle(rect, outline="black")
for x in self.frange(0, self.x_max - self.x_min + 1, self.x_tick):
value = Decimal(self.x_min + x)
if self.x_min <= val... | Removes all existing series and re-draws the axes.
:return: None |
342,322 | def add_argument(self, *args, **kwargs):
argparse_action_name = kwargs.get(, None)
argparse_dest = kwargs.get(, None)
argparse_const = kwargs.get(, None)
argparse_default = kwargs.get(, None)
if argparse_default is argparse.SU... | this method overrides the standard in order to create a parallel
argument system in both the argparse and configman worlds. Each call
to this method returns a standard argparse Action object as well as
adding an equivalent configman Option object to the required_config
for this object. ... |
342,323 | def run(input=sys.stdin, output=sys.stdout):
r
functions = []
environments = dict()
def _writejson(obj):
obj = json.encode(obj)
if isinstance(obj, unicode):
obj = obj.encode()
output.write(obj)
output.write()
output.flush()
def _log(message):
... | r"""CouchDB view function handler implementation for Python.
:param input: the readable file-like object to read input from
:param output: the writable file-like object to write output to |
342,324 | def _resolve(self, path, migration_file):
name = "_".join(migration_file.split("_")[4:])
migration_file = os.path.join(path, "%s.py" % migration_file)
parent = os.path.join(path, "__init__.py")
if not os.path.exists(parent):
with open(parent, "w"):
... | Resolve a migration instance from a file.
:param migration_file: The migration file
:type migration_file: str
:rtype: orator.migrations.migration.Migration |
342,325 | def get_desktop_for_window(self, window):
desktop = ctypes.c_long(0)
_libxdo.xdo_get_desktop_for_window(
self._xdo, window, ctypes.byref(desktop))
return desktop.value | Get the desktop a window is on.
Uses _NET_WM_DESKTOP of the EWMH spec.
If your desktop does not support ``_NET_WM_DESKTOP``, then '*desktop'
remains unmodified.
:param wid: the window to query |
342,326 | def aer2ecef(az: float, el: float, srange: float,
lat0: float, lon0: float, alt0: float,
ell=None, deg: bool = True) -> Tuple[float, float, float]:
x0, y0, z0 = geodetic2ecef(lat0, lon0, alt0, ell, deg=deg)
e1, n1, u1 = aer2enu(az, el, srange, deg=deg)
dx, dy, d... | converts target azimuth, elevation, range from observer at lat0,lon0,alt0 to ECEF coordinates.
Parameters
----------
az : float or numpy.ndarray of float
azimuth to target
el : float or numpy.ndarray of float
elevation to target
srange : float or numpy.ndarray of float
sl... |
342,327 | def _multi_lines(self, strands, permutation):
lines = []
lines.append(str(len(strands)))
lines += [str(strand) for strand in strands]
lines.append(.join(str(p) for p in permutation))
return lines | Prepares lines to write to file for pfunc command input.
:param strand: Strand input (cr.DNA or cr.RNA).
:type strand: cr.DNA or cr.DNA
:param permutation: Permutation (e.g. [1, 2, 3, 4]) of the type used
by pfunc_multi.
:type permutation: list |
342,328 | def _RawGlobPathSpecWithAlphabeticalSchema(
file_system, parent_path_spec, segment_format, location, segment_length,
upper_case=False):
segment_number = 0
segment_files = []
while True:
segment_index = segment_number
segment_letters = []
while len(segment_letters) < segment_length:
s... | Globs for path specifications according to an alphabetical naming schema.
Args:
file_system (FileSystem): file system.
parent_path_spec (PathSpec): parent path specification.
segment_format (str): naming schema of the segment file location.
location (str): the base segment file location string.
s... |
342,329 | def _sumDiceRolls(self, rollList):
if isinstance(rollList, RollList):
self.rolls.append(rollList)
return rollList.sum()
else:
return rollList | convert from dice roll structure to a single integer result |
342,330 | def spectrum_data(filename):
import os
import pkg_resources
info = pkg_resources.get_distribution()
location = info.location
share = os.sep.join([location, "spectrum", ])
filename2 = os.sep.join([share, filename])
if os.path.exists(filename2):
return filename2
else:
... | Simple utilities to retrieve data sets from |
342,331 | def list_all_eq_to(list_, val, strict=True):
if util_type.HAVE_NUMPY and isinstance(val, np.ndarray):
return all([np.all(item == val) for item in list_])
try:
with warnings.catch_warnings():
warnings.filterwarnings(, category=FutureWarning)
flags = ... | checks to see if list is equal everywhere to a value
Args:
list_ (list):
val : value to check against
Returns:
True if all items in the list are equal to val |
342,332 | def get_image_registry_url(self, image_name):
c = self._oc_command(["get", "is", image_name,
"--output=jsonpath=\"])
try:
internal_registry_name = run_cmd(c, return_output=True)
except subprocess.CalledProcessError as ex:
raise ConuE... | Helper function for obtain registry url of image from it's name
:param image_name: str, short name of an image, example:
- conu:0.5.0
:return: str, image registry url, example:
- 172.30.1.1:5000/myproject/conu:0.5.0 |
342,333 | def handle_translocation_illegal(self, line: str, position: int, tokens: ParseResults) -> None:
raise MalformedTranslocationWarning(self.get_line_number(), line, position, tokens) | Handle a malformed translocation. |
342,334 | def _audio_segment_extractor(self, audio_abs_path, segment_abs_path,
starting_second, duration):
subprocess.Popen(["sox", str(audio_abs_path), str(segment_abs_path),
"trim", str(starting_second), str(duration)],
unive... | Parameters
-----------
audio_abs_path : str
segment_abs_path : str
starting_second : int
duration : int |
342,335 | def sendPartialResponse(self):
self.requestProtocol.requestResponse["code"] = (
self.responseCode
)
self.requestProtocol.requestResponse["content"] = (
self.responseContent
)
self.requestProtocol.requestResponse["errors"] = (
self.resp... | Send a partial response without closing the connection.
:return: <void> |
342,336 | def get_X_gradients(self, X):
return X.mean.gradient, X.variance.gradient, X.binary_prob.gradient | Get the gradients of the posterior distribution of X in its specific form. |
342,337 | def stop(self):
yield from self._stop_ubridge()
if self._nvram_watcher:
self._nvram_watcher.close()
self._nvram_watcher = None
if self._telnet_server:
self._telnet_server.close()
self._telnet_server = None
if self.is_running():
... | Stops the IOU process. |
342,338 | def get_preferred_collection(self):
bus = secretstorage.dbus_init()
try:
if hasattr(self, ):
collection = secretstorage.Collection(
bus, self.preferred_collection)
else:
collection = secretstorage.get_default_collection... | If self.preferred_collection contains a D-Bus path,
the collection at that address is returned. Otherwise,
the default collection is returned. |
342,339 | def etree(A):
assert isinstance(A,spmatrix), "A must be a sparse matrix"
assert A.size[0] == A.size[1], "A must be a square matrix"
n = A.size[0]
cp,ri,_ = A.CCS
parent = matrix(0,(n,1))
w = matrix(0,(n,1))
for k in range(n):
parent[k] = k
w[k] = -1
for p in ra... | Compute elimination tree from upper triangle of A. |
342,340 | def initialize(self, conf, ctx):
config = get_config()[]
kafka_class = import_name(config[])
self.client = kafka_class(**config[])
self.topic = self.client.topics[config[]]
self.producer = self.topic.get_producer()
self.tweet_shelf = shelf_from_config(c... | Initialization steps:
1. Connect to Kafka.
2. Prepare Kafka producer for `tweet` topic.
3. Prepare to track tweets published to topic, to avoid redundant data. |
342,341 | def define_noisy_gate(self, name, qubit_indices, kraus_ops):
kraus_ops = [np.asarray(k, dtype=np.complex128) for k in kraus_ops]
_check_kraus_ops(len(qubit_indices), kraus_ops)
return self.inst(_create_kraus_pragmas(name, tuple(qubit_indices), kraus_ops)) | Overload a static ideal gate with a noisy one defined in terms of a Kraus map.
.. note::
The matrix elements along each axis are ordered by bitstring. For two qubits the order
is ``00, 01, 10, 11``, where the the bits **are ordered in reverse** by the qubit index,
i.e., for... |
342,342 | def check_limits(self, verbose=False):
checker = AwsLimitChecker()
checker.set_threshold_overrides(AWS_THRESHOLD_OVERRIDES)
checker.set_limit_overrides(AWS_LIMIT_OVERRIDES)
print("Checking AWS resource usage; WARNING threshold {w}% of "
"limit, C... | Run the actual usage and limit check, with overrides.
see: http://awslimitchecker.readthedocs.org/en/latest/python_usage.html#ci-deployment-checks |
342,343 | def get_all_names(chebi_ids):
all_names = [get_names(chebi_id) for chebi_id in chebi_ids]
return [x for sublist in all_names for x in sublist] | Returns all names |
342,344 | def get_ncbi_id_from_symbol(gene_symbol):
monarch_url =
params = DipperUtil._get_solr_weight_settings()
params["q"] = "{0} \"{0}\"".format(gene_symbol)
params["fq"] = ["taxon:\"NCBITaxon:9606\"", "category:\"gene\""]
gene_id = None
try:
monarch_reque... | Get ncbi gene id from symbol using monarch and mygene services
:param gene_symbol:
:return: |
342,345 | def set_default(self, section, option,
default):
if not self.parser.has_option(section, option):
self.parser.set(section, option, default) | If the option did not exist, create a default value. |
342,346 | def eth_getUncleCountByBlockHash(self, bhash):
response = yield from self.rpc_call(,
[bhash])
if response:
return hex_to_dec(response)
return response | https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getunclecountbyblockhash
:param bhash: Block hash
:type bhash: str
:return: count
:rtype: int or None |
342,347 | def remove_whitespace(text):
clean_text = []
curr_line =
while text:
if not curr_line:
curr_line = text.pop(0)
while not curr_line.strip() and text:
curr_line = text.pop(0)
if curr_line.strip():
clean_te... | Remove unnecessary whitespace while keeping logical structure.
Keyword arguments:
text -- text to remove whitespace from (list)
Retain paragraph structure but remove other whitespace,
such as between words on a line and at the start and end of the text. |
342,348 | def _build_task_heads(self, head_modules):
num_layers = len(self.config["layer_out_dims"])
task_head_layers = self._set_task_head_layers(num_layers)
self.task_map = defaultdict(list)
for t, l in enumerate(task_head_layers):
self.task_map[l... | Creates and attaches task_heads to the appropriate network layers |
342,349 | def url_unquote_plus(s, charset="utf-8", errors="replace"):
if isinstance(s, text_type):
s = s.replace(u"+", u" ")
else:
s = s.replace(b"+", b" ")
return url_unquote(s, charset, errors) | URL decode a single string with the given `charset` and decode "+" to
whitespace.
Per default encoding errors are ignored. If you want a different behavior
you can set `errors` to ``'replace'`` or ``'strict'``. In strict mode a
:exc:`HTTPUnicodeError` is raised.
:param s: The string to unquote.
... |
342,350 | def get_frequency_grid(times,
samplesperpeak=5,
nyquistfactor=5,
minfreq=None,
maxfreq=None,
returnf0dfnf=False):
baseline = times.max() - times.min()
nsamples = times.size
df = 1. / bas... | This calculates a frequency grid for the period finding functions in this
module.
Based on the autofrequency function in astropy.stats.lombscargle.
http://docs.astropy.org/en/stable/_modules/astropy/stats/lombscargle/core.html#LombScargle.autofrequency |
342,351 | def close(self):
self._outfile.write(struct.pack(, 4, 0x0400))
if self._close:
self._outfile.close() | Finalize the GDSII stream library. |
342,352 | def get_current_track_info(self):
response = self.avTransport.GetPositionInfo([
(, 0),
(, )
])
track = {: , : , : , : ,
: }
track[] = response[]
track[] = response[]
track[] = response[]
track[] = response[]
... | Get information about the currently playing track.
Returns:
dict: A dictionary containing information about the currently
playing track: playlist_position, duration, title, artist, album,
position and an album_art link.
If we're unable to return data for a field, we... |
342,353 | def reconstruct(self, inputs, samples=1, sample_static=False,
sample_dynamic=False, swap_static=False, swap_dynamic=False,
fix_static=False, fix_dynamic=False):
batch_size = tf.shape(input=inputs)[-5]
length = len(tf.unstack(inputs, axis=-4))
features = self.compr... | Reconstruct the given input sequences.
Args:
inputs: A batch of image sequences `x_{1:T}` of shape
`[batch_size, timesteps, height, width, channels]`.
samples: Number of samples to draw from the latent distributions.
sample_static: Boolean for whether or not to randomly sample the
... |
342,354 | def process_minter(value):
try:
return current_pidstore.minters[value]
except KeyError:
raise click.BadParameter(
.format(
value, .join(current_pidstore.minters.keys())
)
) | Load minter from PIDStore registry based on given value.
:param value: Name of the minter.
:returns: The minter. |
342,355 | def running(self, offset=0, count=25):
return self.client(, , self.name, offset, count) | Return all the currently-running jobs |
342,356 | def reconstruct(self, X=None):
if X is None:
X = self.X
return self.D.dot(self.X) | Reconstruct representation. |
342,357 | def get_users_by_ids(self, user_ids):
urls = [urljoin(self.user_url, F"{i}.json") for i in user_ids]
result = self._run_async(urls=urls)
return [User(r) for r in result if r] | Given a list of user ids, return all the User objects |
342,358 | def build_field(self, field_name, info, model_class, nested_depth):
if field_name in info.fields_and_pk:
model_field = info.fields_and_pk[field_name]
return self.build_standard_field(field_name, model_field)
elif field_name in info.relations:
relation_info =... | Return a two tuple of (cls, kwargs) to build a serializer field with. |
342,359 | def design(self):
floc_dict = {: self.channel_n,
: self.channel_L,
: self.channel_W,
: self.baffle_S,
: self.obstacle_n,
: self.vel_grad_avg,
: self.retention_time,
... | Returns the designed values.
:returns: list of designed values (G, t, channel_W, obstacle_n)
:rtype: int |
342,360 | def count(self):
if self._group_by or self._join or self.distinct_field:
return self.do_(self.get_query().limit(None).order_by(None).offset(None).alias().count()).scalar()
else:
return self.do_(self.get_query().with_only_columns([func.count()]).limit(None).order_by(None)... | If result is True, then the count will process result set , if
result if False, then only use condition to count |
342,361 | def cache_key(*args, **kwargs):
key = ""
for arg in args:
if callable(arg):
key += ":%s" % repr(arg)
else:
key += ":%s" % str(arg)
return key | Base method for computing the cache key with respect to the given
arguments. |
342,362 | def create(cls, path, N, column_names, dtypes=None, write=True):
dtypes = dtypes or [np.float] * len(column_names)
if N == 0:
raise ValueError("Cannot export empty table")
with h5py.File(path, "w") as h5file_output:
h5data_output = h5file_output.require_group("... | Create a new (empty) hdf5 file with columns given by column names, of length N
Optionally, numpy dtypes can be passed, default is floats |
342,363 | def getConf(self, key, defaultValue=_NoValue):
return self.sparkSession.conf.get(key, defaultValue) | Returns the value of Spark SQL configuration property for the given key.
If the key is not set and defaultValue is set, return
defaultValue. If the key is not set and defaultValue is not set, return
the system default value.
>>> sqlContext.getConf("spark.sql.shuffle.partitions")
... |
342,364 | def parser(cls, buf, offset):
stats = OFPStats()
reserved, length = struct.unpack_from(, buf, offset)
stats.length = length
offset += 4
length -= 4
fields = []
while length > 0:
n, value, _, field_len = ofproto.oxs_parse(buf, offse... | Returns an object which is generated from a buffer including the
expression of the wire protocol of the flow stats. |
342,365 | def transform(self, X):
r
if isinstance(X, np.ndarray):
if X.ndim == 2:
mapped = self._transform_array(X)
return mapped
else:
raise TypeError(
% (str(X.shape), X.ndim)... | r"""Maps the input data through the transformer to correspondingly
shaped output data array/list.
Parameters
----------
X : ndarray(T, n) or list of ndarray(T_i, n)
The input data, where T is the number of time steps and n is the
number of dimensions.
... |
342,366 | def _filter_dead_code(nodes: Iterable[ast.AST]) -> List[ast.AST]:
new_nodes: List[ast.AST] = []
for node in nodes:
if isinstance(node, (ast.Break, ast.Continue, ast.Return)):
new_nodes.append(node)
break
new_nodes.append(node)
return new_nodes | Return a list of body nodes, trimming out unreachable code (any
statements appearing after `break`, `continue`, and `return` nodes). |
342,367 | def create_plots(self):
for i, axis in enumerate(self.ax):
trans_plot_class_call = globals()[self.plot_types[i]]
trans_plot_class = trans_plot_class_call(self.fig, axis,
self.value_classes[i].x_arr_list,
... | Creates plots according to each plotting class. |
342,368 | def get_subdomain_DID_info(self, fqn, cur=None):
subrec = self.get_subdomain_entry_at_sequence(fqn, 0, cur=cur)
cmd = .format(self.subdomain_table)
args = (fqn, subrec.address, subrec.parent_zonefile_index)
cursor = None
if cur is None:
cursor = self.conn.cu... | Get the DID information for a subdomain.
Raise SubdomainNotFound if there is no such subdomain
Return {'name_type': ..., 'address': ..., 'index': ...} |
342,369 | def negotiate_encoding (self):
try:
features = self.url_connection.sendcmd("FEAT")
except ftplib.error_perm as msg:
log.debug(LOG_CHECK, "Ignoring error when getting FTP features: %s" % msg)
pass
else:
log.debug(LOG_CHECK, "FTP features %s... | Check if server can handle UTF-8 encoded filenames.
See also RFC 2640. |
342,370 | def generateRaDec(self):
self.prefix = self.PAR_PREFIX
if not isinstance(self.wcs,pywcs.WCS):
print(
textutil.textbox(
),
file=sys.stderr
)
raise ValueError
... | Convert XY positions into sky coordinates using STWCS methods. |
342,371 | def read_raw_data(self, f):
if not self.toc["kTocRawData"]:
return
f.seek(self.data_position)
total_data_size = self.next_segment_offset - self.raw_data_offset
log.debug(
"Reading %d bytes of data at %d in %d chunks" %
(total_data_size, f.t... | Read signal data from file |
342,372 | def _get_agg_font(self, prop):
if __debug__: verbose.report(,
)
key = hash(prop)
font = RendererAgg._fontd.get(key)
if font is None:
fname = findfont(prop)
font = RendererAgg._fontd.get(fname)
if font is ... | Get the font for text instance t, cacheing for efficiency |
342,373 | def calc_freefree_eta(ne, t, hz):
kappa = calc_freefree_kappa(ne, t, hz)
return kappa * cgs.k * t * hz**2 / cgs.c**2 | Dulk (1985) equations 7 and 20, assuming pure hydrogen. |
342,374 | def propose_unif(self):
while True:
u, idx, q = self.mell.sample(rstate=self.rstate, return_q=True)
if unitcheck(u, self.nonperiodic):
if q == 1 or self.rstate.rand() < 1.0 / ... | Propose a new live point by sampling *uniformly* within
the union of ellipsoids. |
342,375 | def fancy_SCAT(points, low_bound, high_bound, x_max, y_max):
SCAT =
SCATs = {: , : , : }
for point_type in points:
for point in points[point_type]:
result = in_SCAT_box(point[0], point[1], low_bound, high_bound, x_max, y_max)
if not resul... | runs SCAT test and returns 'Pass' or 'Fail' |
342,376 | async def application_info(self):
data = await self.http.application_info()
if not in data:
data[] = None
return AppInfo(self._connection, data) | |coro|
Retrieve's the bot's application information.
Raises
-------
HTTPException
Retrieving the information failed somehow.
Returns
--------
:class:`.AppInfo`
A namedtuple representing the application info. |
342,377 | def update(self, prob):
chunk_activated = prob > 1.0 - self.sensitivity
if chunk_activated or self.activation < 0:
self.activation += 1
has_activated = self.activation > self.trigger_level
if has_activated or chunk_activated and self.activation < 0:... | Returns whether the new prediction caused an activation |
342,378 | def wrong_usage (docstring, *rest):
intext = False
if len (rest) == 0:
detail =
elif len (rest) == 1:
detail = rest[0]
else:
detail = rest[0] % tuple (rest[1:])
print (, detail, , file=sys.stderr)
show_usage (docstring, True, sys.stderr, 1) | Print a message indicating invalid command-line arguments and exit with an
error code.
:arg str docstring: the program help text
:arg rest: an optional specific error message
This function is intended for small programs launched from the command
line. The intention is for the program help informat... |
342,379 | def reset_rammbock(self):
for client in self._clients:
client.close()
for server in self._servers:
server.close()
self._init_caches() | Closes all connections, deletes all servers, clients, and protocols.
You should call this method before exiting your test run. This will
close all the connections and the ports will therefore be available for
reuse faster. |
342,380 | def parse_requirements(path):
try:
requirements = map(str.strip, local_file(path).splitlines())
except IOError:
raise RuntimeError("Couldn file :(")
links = []
pkgs = []
for req in requirements:
if not req:
continue
if in req or in req:
... | Rudimentary parser for the `requirements.txt` file
We just want to separate regular packages from links to pass them to the
`install_requires` and `dependency_links` params of the `setup()`
function properly. |
342,381 | def install_script(self, dist, script_name, script_text, dev_path=None):
spec = str(dist.as_requirement())
is_script = is_python_script(script_text, script_name)
if is_script:
script_text = (ScriptWriter.get_header(script_text) +
self._load_templa... | Generate a legacy script wrapper and install it |
342,382 | def siphashx24(message, key=b, encoder=nacl.encoding.HexEncoder):
digest = _sip_hashx(message, key)
return encoder.encode(digest) | Computes a keyed MAC of ``message`` using the 128 bit variant of the
siphash-2-4 construction.
:param message: The message to hash.
:type message: bytes
:param key: the message authentication key for the siphash MAC construct
:type key: bytes(:const:`SIPHASHX_KEYBYTES`)
:param encoder: A class ... |
342,383 | def buildPolyData(vertices, faces=None, indexOffset=0):
if not utils.isSequence(vertices):
faces = vertices.cells()
vertices = vertices.coordinates()
sourcePoints = vtk.vtkPoints()
sourcePolygons = vtk.vtkCellArray()
sourceVertices = vtk.vtkCellArray()
isgt2 = len(vertices[0... | Build a ``vtkPolyData`` object from a list of vertices
where faces represents the connectivity of the polygonal mesh.
E.g. :
- ``vertices=[[x1,y1,z1],[x2,y2,z2], ...]``
- ``faces=[[0,1,2], [1,2,3], ...]``
Use ``indexOffset=1`` if face numbering starts from 1 instead of 0.
.. hint:: |b... |
342,384 | def matrix(
m, n, lst,
m_text: list=None,
n_text: list=None):
fmt = ""
if n_text:
fmt += " {}\n".format(" ".join(n_text))
for i in range(1, m+1):
if m_text:
fmt += "{:<4.4} ".format(m_text[i-1])
fmt += "|"
for j in ra... | m: row
n: column
lst: items
>>> print(_matrix(2, 3, [(1, 1), (2, 3)]))
|x| | |
| | |x| |
342,385 | def merge_nested_environment_dicts(env_dicts, env_name=None, env_root=None):
if all(isinstance(val, (six.string_types, list))
for (_key, val) in env_dicts.items()):
return flatten_path_lists(env_dicts, env_root)
if env_name is None:
if env_dicts.get():
retu... | Return single-level dictionary from dictionary of dictionaries. |
342,386 | def most_specific_convertible_shape(self, other):
other = as_shape(other)
if self._dims is None or other.dims is None or self.ndims != other.ndims:
return unknown_shape()
dims = [(Dimension(None))] * self.ndims
for i, (d1, d2) in enumerate(zip(self._dims, other.dim... | Returns the most specific TensorShape convertible with `self` and `other`.
* TensorShape([None, 1]) is the most specific TensorShape convertible with
both TensorShape([2, 1]) and TensorShape([5, 1]). Note that
TensorShape(None) is also convertible with above mentioned TensorShapes.
... |
342,387 | def anonymous(self):
if hasattr(self.handler, ):
anon = self.handler.anonymous
if callable(anon):
return anon
for klass in typemapper.keys():
if anon == klass.__name__:
return klass
return None | Gets the anonymous handler. Also tries to grab a class
if the `anonymous` value is a string, so that we can define
anonymous handlers that aren't defined yet (like, when
you're subclassing your basehandler into an anonymous one.) |
342,388 | def check_local_install(ctx, version, ext, server="local"):
here = Path(ctx.releaser.here).resolve()
dist_dir = here /
all_files = list(dist_dir.glob(.format(ext)))
the_file = all_files[0]
for f in all_files[1:]:
if f.stat().st_mtime > the_file.stat().st_mtime:
the_file = ... | Upload and install works?
Uploads a distribution to PyPI, and then tests to see if I can download and
install it.
Returns:
str: string summazing operation |
342,389 | def lastOfferedMonth(self):
lastOfferedSeries = self.event_set.order_by().first()
return (lastOfferedSeries.year,lastOfferedSeries.month) | Sometimes a Series is associated with a month other than the one
in which the first class begins, so this returns a (year,month) tuple
that can be used in admin instead. |
342,390 | def _to_solr(self, data):
return self._dest.index_json(self._dest_coll, json.dumps(data,sort_keys=True)) | Sends data to a Solr instance. |
342,391 | def sub(self, index):
index = np.asarray(index)
if index.dtype == :
index = index.nonzero()[0]
if self.size < len(index):
raise ValueError(t subset "{}": index ({}) is bigger than the number of elements ({})'.format(self.name, len(index), self.size))
... | Return a sub-attribute |
342,392 | def brew_recipe(recipe_name):
prefix = "{}.".format(recipes.__name__)
for importer, modname, _ in pkgutil.iter_modules(recipes.__path__, prefix):
_module = importer.find_module(modname).load_module(modname)
_recipe_classes = [cls for cls in _module.__dict... | Returns a pipeline string from a recipe name.
Parameters
----------
recipe_name : str
Name of the recipe. Must match the name attribute in one of the classes
defined in :mod:`flowcraft.generator.recipes`
Returns
-------
str
Pipeline string ready for parsing and processi... |
342,393 | def close(self):
log.debug(, self, self.proto, self.connector)
assert self._dDown is None
self._dDown = Deferred()
if self.proto is not None:
self.proto.transport.loseConnection()
elif self.connector is not None:
def connectingFailed(reason):
... | Permanently dispose of the broker client.
This terminates any outstanding connection and cancels any pending
requests. |
342,394 | def percentage(self):
total_vote_count = self.poll.vote_count
if total_vote_count:
return self.vote_count * 100.0 / total_vote_count
return 0 | Returns the percentage of votes cast for this poll option in
relation to all of its poll's other options. |
342,395 | def deprecated(message=None):
def decorated_method_to_deprecate(func):
if inspect.isclass(func):
msg = "Class {}() is DEPRECATED! *** ".format(func.__name__)
if message:
msg += "<> %s <>" % message
warnings.simplefilter(, DeprecationWarn... | This decorator marks methods as deprecated.
A warning is displayed if the method is called. |
342,396 | def getISAStudy(studyNum, pathToISATABFile, noAssays = True):
from isatools import isatab
import copy
try:
isa = isatab.load(pathToISATABFile, skip_load_tables=True)
st = copy.deepcopy(isa.studies[studyNum - 1])
if noAssays:
st.assays = []
return st
excep... | This function returns a Study object given the study number in an ISA file
Typically, you should use the exploreISA function to check the contents
of the ISA file and retrieve the study number you are interested in!
:param studyNum: The Study number (notice it's not zero-based index).
:type studyNum: in... |
342,397 | def annoy():
"Annoy everyone with meaningless banter"
def a1():
yield
yield
yield "WHAT DO YOU DO WITH A DRUNKEN SAILOR, EARLY IN THE MORNINM HENRY THE EIGHTH I AM"
yield "HENRY THE EIGHTH I AM I AM"
yield (
"I GOT MARRIED TO THE GIRL NEXT DOOR; SHEs me! My Tallest? "
"My Tallest!")
return random.c... | Annoy everyone with meaningless banter |
342,398 | def __render(self, context, **kwargs):
kwargs["namespaces"] = [context, ] + kwargs.get("namespaces", []) \
+ kwargs.get("searchList", [])
kwargs["searchList"] = None
kwargs = self.filter_options(kwa... | Render template.
:param context: A dict or dict-like object to instantiate given
template file
:param kwargs: Keyword arguments passed to the template engine to
render templates with specific features enabled.
:return: Rendered string |
342,399 | def unpack(self, data):
size = self._get_calculated_size(self.size, data)
self.set_value(data[0:size])
return data[len(self):] | Takes in a byte string and set's the field value based on field
definition.
:param structure: The message structure class object
:param data: The byte string of the data to unpack
:return: The remaining data for subsequent fields |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.