Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
367,200 | def build_defines(defines):
return [ % (x, str(y)) for x, y in defines.items() if y is not None] | Build a list of `-D` directives to pass to the compiler.
This will drop any definitions whose value is None so that
you can get rid of a define from another architecture by
setting its value to null in the `module_settings.json`. |
367,201 | def set_mask(self, mask_img):
mask = load_mask(mask_img, allow_empty=True)
check_img_compatibility(self.img, mask, only_check_3d=True)
self.mask = mask | Sets a mask img to this. So every operation to self, this mask will be taken into account.
Parameters
----------
mask_img: nifti-like image, NeuroImage or str
3D mask array: True where a voxel should be used.
Can either be:
- a file path to a Nifti image
... |
367,202 | def available_ports(low=1024, high=65535, exclude_ranges=None):
if exclude_ranges is None:
exclude_ranges = []
available = utils.ranges_to_set(UNASSIGNED_RANGES)
exclude = utils.ranges_to_set(
ephemeral.port_ranges() + exclude_ranges +
[
SYSTEM_PORT_RANGE,
... | Returns a set of possible ports (excluding system,
ephemeral and well-known ports).
Pass ``high`` and/or ``low`` to limit the port range. |
367,203 | def send_email(sender,
subject,
content,
email_recipient_list,
email_address_list,
email_user=None,
email_pass=None,
email_server=None):
Example Person 1Example Person 1example1@example.comexample2@example.orgt ... | This sends an email to addresses, informing them about events.
The email account settings are retrieved from the settings file as described
above.
Parameters
----------
sender : str
The name of the sender to use in the email header.
subject : str
Subject of the email.
co... |
367,204 | def summarize_address_range(first, last):
if not (isinstance(first, _BaseIP) and isinstance(last, _BaseIP)):
raise TypeError()
if first.version != last.version:
raise TypeError("%s and %s are not of the same version" % (
str(first), str(last)))
if first > last:
r... | Summarize a network range given the first and last IP addresses.
Example:
>>> summarize_address_range(IPv4Address('1.1.1.0'),
IPv4Address('1.1.1.130'))
[IPv4Network('1.1.1.0/25'), IPv4Network('1.1.1.128/31'),
IPv4Network('1.1.1.130/32')]
Args:
first: the first IPv4A... |
367,205 | def track_metric(self, unique_identifier, metric, date=None, inc_amt=1, **kwargs):
metric = [metric] if isinstance(metric, basestring) else metric
unique_identifier = [unique_identifier] if not isinstance(unique_identifier, (types.ListType, types.TupleType, types.GeneratorType,)) else unique_id... | Tracks a metric for a specific ``unique_identifier`` for a certain date. The redis backend supports
lists for both ``unique_identifier`` and ``metric`` allowing for tracking of multiple metrics for multiple
unique_identifiers efficiently. Not all backends may support this.
:param unique_identif... |
367,206 | def sle(actual, predicted):
return (np.power(np.log(np.array(actual)+1) -
np.log(np.array(predicted)+1), 2)) | Computes the squared log error.
This function computes the squared log error between two numbers,
or for element between a pair of lists or numpy arrays.
Parameters
----------
actual : int, float, list of numbers, numpy array
The ground truth value
predicted : same type as actual
... |
367,207 | def lookups(self, request, model_admin):
User = get_user_model()
output = []
for i in models.Model.objects.values().distinct():
pk = i[]
if pk is not None:
output.append([pk, User.objects.get(pk=pk).__str__])
return output | Returns a list of tuples. The first element in each
tuple is the coded value for the option that will
appear in the URL query. The second element is the
human-readable name for the option that will appear
in the right sidebar. |
367,208 | def autoprops_decorate(cls,
include=None,
exclude=None
):
_check_known_decorators(cls, )
_execute_autoprops_on_class(cls, include=include, exclude=exclude)
return cls | To automatically generate all properties getters and setters from the class constructor manually, without using
@autoprops decorator.
* if a @contract annotation exist on the __init__ method, mentioning a contract for a given parameter, the
parameter contract will be added on the generated setter method
... |
367,209 | def _get_class(template_file):
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=RuntimeWarning)
template_module = imp.load_source(, template_file)
for name, data in inspect.getmembers(template_module, inspect.isclass):
... | Import the file and inspect for subclass of TaskTemplate.
:param template_file: filename to import. |
367,210 | def norm_to_uniform(im, scale=None):
r
if scale is None:
scale = [im.min(), im.max()]
im = (im - sp.mean(im)) / sp.std(im)
im = 1 / 2 * sp.special.erfc(-im / sp.sqrt(2))
im = (im - im.min()) / (im.max() - im.min())
im = im * (scale[1] - scale[0]) + scale[0]
return im | r"""
Take an image with normally distributed greyscale values and converts it to
a uniform (i.e. flat) distribution. It's also possible to specify the
lower and upper limits of the uniform distribution.
Parameters
----------
im : ND-image
The image containing the normally distributed s... |
367,211 | def auto_rewrite_input(self, cmd):
if not self.show_rewritten_input:
return
rw = self.prompt_manager.render() + cmd
try:
rw = str(rw)
print >> io.stdout, rw
except UnicodeEncodeError:
print "----... | Print to the screen the rewritten form of the user's command.
This shows visual feedback by rewriting input lines that cause
automatic calling to kick in, like::
/f x
into::
------> f(x)
after the user's input prompt. This helps the user understand that the
... |
367,212 | def blockreplace(
name,
marker_start=,
marker_end=,
source=None,
source_hash=None,
template=,
sources=None,
source_hashes=None,
defaults=None,
context=None,
content=,
append_if_not_found=False,
prepend_if_not_found=F... | Maintain an edit in a file in a zone delimited by two line markers
.. versionadded:: 2014.1.0
.. versionchanged:: 2017.7.5,2018.3.1
``append_newline`` argument added. Additionally, to improve
idempotence, if the string represented by ``marker_end`` is found in
the middle of the line, th... |
367,213 | def tdSensor(self):
protocol = create_string_buffer(20)
model = create_string_buffer(20)
sid = c_int()
datatypes = c_int()
self._lib.tdSensor(protocol, sizeof(protocol), model, sizeof(model),
byref(sid), byref(datatypes))
return {: sel... | Get the next sensor while iterating.
:return: a dict with the keys: protocol, model, id, datatypes. |
367,214 | def reverse_iter(self, start=None, stop=None, count=2000):
cursor =
count = 1000
start = start if start is not None else (-1 * count)
stop = stop if stop is not None else -1
_loads = self._loads
while cursor:
cursor = self._client.lrange(self.key_pre... | -> yields items of the list in reverse |
367,215 | def parse_meta(self, selected_meta_data):
files = self._get_files("meta", self.path)
df = pd.DataFrame()
print("Parsing the metadata files...")
for f in tqdm(files):
data = self.parse_single_meta(f, selected_meta_data)
if data is not None:
... | Parses all of the metadata files
:param selected_meta_data: if specified then only the columns that are contained here are going to be parsed
:return: |
367,216 | def plot_fit_individuals_lens_plane_only(
fit, should_plot_mask=True, extract_array_from_mask=False, zoom_around_mask=False, positions=None,
should_plot_image_plane_pix=False,
should_plot_image=False,
should_plot_noise_map=False,
should_plot_signal_to_noise_map=False,
sho... | Plot the model datas_ of an analysis, using the *Fitter* class object.
The visualization and output type can be fully customized.
Parameters
-----------
fit : autolens.lens.fitting.Fitter
Class containing fit between the model datas_ and observed lens datas_ (including residual_map, chi_square... |
367,217 | def find_link(self, device):
for i in range(len(self.mpstate.mav_master)):
conn = self.mpstate.mav_master[i]
if (str(i) == device or
conn.address == device or
getattr(conn, , None) == device):
return i
return None | find a device based on number, name or label |
367,218 | def _set_security(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=security.security, is_container=, presence=False, yang_name="security", rest_name="security", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=Tru... | Setter method for security, mapped from YANG variable /rbridge_id/threshold_monitor/security (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_security is considered as a private
method. Backends looking to populate this variable should
do so via calling thisOb... |
367,219 | def fetch_batch_status(self, guid):
url = % (self.base_url, guid)
headers = {
: ,
: ,
: self.api_email,
: self.api_token
}
resp = requests.get(url, headers=headers)
resp.raise_for_status()
return BatchRe... | Fetch the status of a batch, given the guid |
367,220 | def _starts_with_vowel(self, letter_group: str) -> bool:
if len(letter_group) == 0:
return False
return self._contains_vowels(letter_group[0]) | Check if a string starts with a vowel. |
367,221 | def get_validated_token(self, raw_token):
messages = []
for AuthToken in api_settings.AUTH_TOKEN_CLASSES:
try:
return AuthToken(raw_token)
except TokenError as e:
messages.append({: AuthToken.__name__,
: Au... | Validates an encoded JSON web token and returns a validated token
wrapper object. |
367,222 | def calculate_sampling_decision(trace_header, recorder, sampling_req):
if trace_header.sampled is not None and trace_header.sampled != :
return trace_header.sampled
elif not recorder.sampling:
return 1
else:
decision = recorder.sampler.should_trace(sampling_req)
return decis... | Return 1 or the matched rule name if should sample and 0 if should not.
The sampling decision coming from ``trace_header`` always has
the highest precedence. If the ``trace_header`` doesn't contain
sampling decision then it checks if sampling is enabled or not
in the recorder. If not enbaled it returns ... |
367,223 | def get_variable(name, temp_s):
return tf.Variable(tf.zeros(temp_s), name=name) | Get variable by name. |
367,224 | def print_groups():
print("Printing information about all groups defined in the Gateway")
groups = api(gateway.get_groups())
if len(groups) == 0:
exit(bold("No groups defined"))
container = []
for group in groups:
container.append(api(group).raw)
print(jsonify(container)) | Print all groups as JSON |
367,225 | def _is_admin(user_id):
user = get_session().query(User).filter(User.id==user_id).one()
if user.is_admin():
return True
else:
return False | Is the specified user an admin |
367,226 | def now_micros(absolute=False) -> int:
micros = int(time.time() * 1e6)
if absolute:
return micros
return micros - EPOCH_MICROS | Return current micros since epoch as integer. |
367,227 | def destination_uri_file_counts(self):
counts = self._job_statistics().get("destinationUriFileCounts")
if counts is not None:
return [int(count) for count in counts]
return None | Return file counts from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.extract.destinationUriFileCounts
Returns:
a list of integer counts, each representing the number of files
per destination URI or URI pattern... |
367,228 | def split(args):
from jcvi.apps.grid import Jobs
p = OptionParser(split.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
pairsfastq, = args
gz = pairsfastq.endswith(".gz")
pf = pairsfastq.replace(".gz", "").rsplit(".", 1)[0]
p1 = pf... | %prog split pairs.fastq
Split shuffled pairs into `.1.fastq` and `.2.fastq`, using `sed`. Can work
on gzipped file.
<http://seqanswers.com/forums/showthread.php?t=13776> |
367,229 | def dispatch(argdict):
cmd = argdict[]
ftc = getattr(THIS_MODULE, +cmd)
ftc(argdict) | Call the command-specific function, depending on the command. |
367,230 | def get_cloud_init_mime(cloud_init):
if isinstance(cloud_init, six.string_types):
cloud_init = salt.utils.json.loads(cloud_init)
_cloud_init = email.mime.multipart.MIMEMultipart()
if in cloud_init:
for script_name, script in six.iteritems(cloud_init[]):
_script = email.mime... | Get a mime multipart encoded string from a cloud-init dict. Currently
supports boothooks, scripts and cloud-config.
CLI Example:
.. code-block:: bash
salt myminion boto.get_cloud_init_mime <cloud init> |
367,231 | def convert_to_string(self, block):
out = ""
for seq_record in block:
taxon_id = ">{0}_{1}_{2} [org={0} {1}] [Specimen-voucher={2}] " \
"[note={3} gene, partial cds.] [Lineage={4}]".format(
seq_record.taxonomy[],
seq_record.taxo... | Takes a list of SeqRecordExpanded objects corresponding to a gene_code
and produces the gene_block as string.
:param block:
:return: str. |
367,232 | def make_mujoco_env(env_id, seed, reward_scale=1.0):
rank = MPI.COMM_WORLD.Get_rank()
myseed = seed + 1000 * rank if seed is not None else None
set_global_seeds(myseed)
env = gym.make(env_id)
logger_path = None if logger.get_dir() is None else os.path.join(logger.get_dir(), str(rank))
env ... | Create a wrapped, monitored gym.Env for MuJoCo. |
367,233 | def element_creator(namespace=None):
ELEMENT_MAKER = _objectify.ElementMaker(namespace=namespace,
annotate=False)
def create_elem(tag, attr=None, text=None):
if not attr:
attr = {}
if text:
element = getattr(ELEME... | Create a simple namespace-aware objectify element creator.
Args:
namespace (str): Namespace to work in
Returns:
function: Namespace-aware element creator |
367,234 | def iterate(self, start_line=None, parse_attr=True, headers=False,
comments=False):
handle = self.handle
split = str.split
strip = str.strip
if start_line is None:
line = next(handle)
else:
line = start_line
... | Iterate over GFF3 file, returning GFF3 entries
Args:
start_line (str): Next GFF3 entry. If 'handle' has been partially
read and you want to start iterating at the next entry, read
the next GFF3 entry and pass it to this variable when calling
gff3_it... |
367,235 | def deserialize(cls, config, credentials):
if isinstance(credentials, Credentials):
return credentials
decoded = parse.unquote(credentials)
split = decoded.split()
if split[0] is None:
raise CredentialsError(
... | A *class method* which reconstructs credentials created by
:meth:`serialize`. You can also pass it a :class:`.Credentials`
instance.
:param dict config:
The same :doc:`config` used in the :func:`.login` to get the
credentials.
:param str credentials:
... |
367,236 | def index(self, row, column, parent):
if not parent.isValid():
s = self._conf
else:
p = parent.internalPointer()
k = self.get_key(p, parent.row())
s = p[k]
return self.createIndex(row, column, s) | Reimplemented from QtCore.QAbstractItemModel
The internal pointer is the section.
The row determines the key in the scalars then sections of the configobj.
So for a given index, use row to retrieve the key::
key = self.get_key(index.internalPointer(), index.row())
To use the... |
367,237 | def evaluate_block(self, comments):
if self.jsdocs:
m1 = RE_JSDOC.match(comments)
if m1:
lines = []
for line in m1.group(1).splitlines(True):
l = line.lstrip()
lines.append(l[1:] if l.startswith() else l)
... | Evaluate block comments. |
367,238 | def update(self, data, length=None):
if self.digest_finalized:
raise DigestError("No updates allowed")
if not isinstance(data, bintype):
raise TypeError("A byte string is expected")
if length is None:
length = len(data)
elif length > len(data)... | Hashes given byte string
@param data - string to hash
@param length - if not specifed, entire string is hashed,
otherwise only first length bytes |
367,239 | def get_file(self, name):
files = self.get_output_files()
for f in files:
if f.get_name() == name:
return f
return None | Returns the output file with the specified name, if no output files
match, returns None. |
367,240 | def close(self):
if not self.driver:
return
try:
self.driver.implicitly_wait(1)
self.driver.find_element_by_id().click()
except NoSuchElementException:
pass
self.driver.quit()
self.driver = None | Logs out and quits the current web driver/selenium session. |
367,241 | def groupByContent(paths):
handles, results = [], []
except IOError:
pass
handles.append(hList)
while handles:
more, done = compareChunks(handles.pop(0))
handles.extend(more)
results.extend(done)
return dict((x[0], x) for... | Byte-for-byte comparison on an arbitrary number of files in parallel.
This operates by opening all files in parallel and comparing
chunk-by-chunk. This has the following implications:
- Reads the same total amount of data as hash comparison.
- Performs a *lot* of disk seeks. (Best suited for S... |
367,242 | def get_linode(kwargs=None, call=None):
if call == :
raise SaltCloudSystemExit(
)
if kwargs is None:
kwargs = {}
name = kwargs.get(, None)
linode_id = kwargs.get(, None)
if name is None and linode_id is None:
raise SaltCloudSystemExit(
... | Returns data for a single named Linode.
name
The name of the Linode for which to get data. Can be used instead
``linode_id``. Note this will induce an additional API call
compared to using ``linode_id``.
linode_id
The ID of the Linode for which to get data. Can be used instead ... |
367,243 | def _merge_flags(new_flags, old_flags=None, conf=):
if not old_flags:
old_flags = []
args = [old_flags, new_flags]
if conf == :
tmp = new_flags + \
[i for i in old_flags if _check_accept_keywords(new_flags, i)]
else:
tmp = portage.flatten(args)
flags = {}
... | Merges multiple lists of flags removing duplicates and resolving conflicts
giving priority to lasts lists. |
367,244 | def process_shell(self, creator, entry, config):
self.logger.info("Processing Bash code: start")
output = []
shell = creator(entry, config)
for line in shell.process():
output.append(line)
self.logger.info(" | %s", line)
if shell.success:
... | Processing a shell entry. |
367,245 | def launch(self, args, unknown):
pm = plugins.PluginManager.get()
addon = pm.get_plugin(args.addon)
isgui = isinstance(addon, plugins.JB_StandaloneGuiPlugin)
if isgui:
gui.main.init_gui()
print "Launching %s..." % args.addon
addon.run()
if isg... | Launch something according to the provided arguments
:param args: arguments from the launch parser
:type args: Namespace
:param unknown: list of unknown arguments
:type unknown: list
:returns: None
:rtype: None
:raises: SystemExit |
367,246 | def get_states(self):
variable_states = {variable.find().text: [outcome.text for outcome in variable.findall()]
for variable in self.network.findall()}
return variable_states | Returns the states of variables present in the network
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_states()
{'bowel-problem': ['true', 'false'],
'dog-out': ['true', 'false'],
'family-out': ['true', 'false'],
'he... |
367,247 | def two_digit_freqs(digits, normalize=False):
freqs = np.zeros(100, dtype=)
last = digits.next()
this = digits.next()
for d in digits:
index = int(last + this)
freqs[index] += 1
last = this
this = d
if normalize:
freqs = freqs/freqs.sum()
return freqs | Consume digits of pi and compute 2 digits freq. counts. |
367,248 | def binaryRecords(self, path, recordLength):
return RDD(self._jsc.binaryRecords(path, recordLength), self, NoOpSerializer()) | .. note:: Experimental
Load data from a flat binary file, assuming each record is a set of numbers
with the specified numerical format (see ByteBuffer), and the number of
bytes per record is constant.
:param path: Directory to the input data files
:param recordLength: The lengt... |
367,249 | def network_lopf_solve(network, snapshots=None, formulation="angles", solver_options={},solver_logfile=None, keep_files=False,
free_memory={},extra_postprocessing=None):
snapshots = _as_snapshots(network, snapshots)
logger.info("Solving model using %s", network.opt.name)
if i... | Solve linear optimal power flow for a group of snapshots and extract results.
Parameters
----------
snapshots : list or index slice
A list of snapshots to optimise, must be a subset of
network.snapshots, defaults to network.snapshots
formulation : string
Formulation of the linea... |
367,250 | def action_rename(self):
old = self.args[]
new = self.args[]
self.db_query(, (old,))
r = self.db_fetch_one()
UPDATE shortcuts SET name=? WHERE id=?
Shortcut "%s" renamed to "%s".' % (old, new)) | Rename a shortcut |
367,251 | def get_ips(host, port):
ips = set()
for af_type in (socket.AF_INET, socket.AF_INET6):
try:
records = socket.getaddrinfo(host, port, af_type, socket.SOCK_STREAM)
ips.update(rec[4][0] for rec in records)
except socket.gaierror as ex:
pass
return ips | lookup all IPs (v4 and v6) |
367,252 | def get_fallback_languages(self, language_code=None, site_id=None):
choices = self.get_active_choices(language_code, site_id=site_id)
return choices[1:] | Find out what the fallback language is for a given language choice.
.. versionadded 1.5 |
367,253 | def in4_chksum(proto, u, p):
if not isinstance(u, IP):
warning("No IP underlayer to compute checksum. Leaving null.")
return 0
if u.len is not None:
if u.ihl is None:
olen = sum(len(x) for x in u.options)
ihl = 5 + olen // 4 + (1 if olen % 4 else 0)
e... | As Specified in RFC 2460 - 8.1 Upper-Layer Checksums
Performs IPv4 Upper Layer checksum computation. Provided parameters are:
- 'proto' : value of upper layer protocol
- 'u' : IP upper layer instance
- 'p' : the payload of the upper layer provided as a string |
367,254 | def update(self, values):
for k, v in values.items():
root, sub = self.split(k)
if sub is None:
self.declarations[root] = v
else:
self.contexts[root][sub] = v
extra_context_keys = set(self.contexts) - set(self.declarations)
... | Add new declarations to this set/
Args:
values (dict(name, declaration)): the declarations to ingest. |
367,255 | def status(context):
context.obj.find_repo_type()
context.obj.call([context.obj.vc_name, ]) | See which files have changed, checked in, and uploaded |
367,256 | def mask_blurring_from_mask_and_psf_shape(mask, psf_shape):
blurring_mask = np.full(mask.shape, True)
for y in range(mask.shape[0]):
for x in range(mask.shape[1]):
if not mask[y, x]:
for y1 in range((-psf_shape[0] + 1) // 2, (psf_shape[0] + 1) // 2):
... | Compute a blurring masks from an input masks and psf shape.
The blurring masks corresponds to all pixels which are outside of the masks but will have a fraction of their \
light blur into the masked region due to PSF convolution. |
367,257 | def _join_partner(self, partner: Address):
try:
self.api.channel_open(
self.registry_address,
self.token_address,
partner,
)
except DuplicatedChannelError:
pass
total_deposit =... | Ensure a channel exists with partner and is funded in our side |
367,258 | def _move_node_file(path, old_id, new_id):
root = os.path.join(path, "project-files")
if os.path.exists(root):
for dirname in os.listdir(root):
module_dir = os.path.join(root, dirname)
if os.path.isdir(module_dir):
node_dir = os.path.join(module_dir, old_id)
... | Move the files from a node when changing his id
:param path: Path of the project
:param old_id: ID before change
:param new_id: New node UUID |
367,259 | def set_SaveName(self,SaveName=None,
include=None,
ForceUpdate=False):
if not in self.dall.keys():
self._dall[] = (SaveName is not None)
if SaveName is not None:
self._dall[] = SaveName
self._dall[] = True
... | Set the name for saving the instance (SaveName)
SaveName can be either:
- provided by the user (no constraint) - not recommended
- automatically generated from Name and key attributes (cf. include)
Parameters
----------
SaveName : None / str
If ... |
367,260 | def append_new_text(destination, text, join_str=None):
if join_str is None:
join_str =
if len(destination) > 0:
last = destination[-1]
if last.tail is None:
last.tail = text
else:
last.tail = join_str.join([last.tail, text])
else:
... | This method provides the functionality of adding text appropriately
underneath the destination node. This will be either to the destination's
text attribute or to the tail attribute of the last child. |
367,261 | def normalize_slice(e, n):
if n == 0:
return (0, 0, 1)
step = e.step
if step is None:
step = 1
if step == 0:
start = e.start
count = e.stop
if isinstance(start, int) and isinstance(count, int) and count >= 0:
if start < 0:
start +... | Return the slice tuple normalized for an ``n``-element object.
:param e: a slice object representing a selector
:param n: number of elements in a sequence to which ``e`` is applied
:returns: tuple ``(start, count, step)`` derived from ``e``. |
367,262 | def getDelta(original, update):
k = genKw(*original)
kPrime = genKw(*update)
delta = (kPrime * inverse(k, orderGt())) % orderGt()
pPrime = generatorGt()**kPrime
return delta,pPrime | Generates an update token delta_{k->k'}.
@original: values for k: (w,msk,s)
@update: values for kPrime: (w',msk',s')
@return (delta, p'): @delta = k'/k, @p' is a new pubkey based on k'. |
367,263 | def ast_from_module_name(self, modname, context_file=None):
if modname in self.astroid_cache:
return self.astroid_cache[modname]
if modname == "__main__":
return self._build_stub_module(modname)
old_cwd = os.getcwd()
if context_file:
os.chdir(... | given a module name, return the astroid object |
367,264 | async def _connect(self):
logger.debug("connecting to the stream")
await self.client.setup
if self.session is None:
self.session = self.client._session
kwargs = await self.client.headers.prepare_request(**self.kwargs)
request = self.client.error_handler(self.... | Connect to the stream
Returns
-------
asyncio.coroutine
The streaming response |
367,265 | def packageInfo(self):
url = "%s/item.pkinfo" % self.root
params = { : }
result = self._get(url=url,
param_dict=params,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
... | gets the item's package information file |
367,266 | def get_download_link(self):
url = None
if not self.get("downloadable"):
try:
url = self.client.get_location(
self.client.STREAM_URL % self.get("id"))
except serror as e:
print(e)
if not url:
try:
... | Get direct download link with soudcloud's redirect system. |
367,267 | def create_node(manager, name, meta_type_label, type_label, handle_id, legacy=True):
if meta_type_label not in META_TYPES:
raise exceptions.MetaLabelNamingError(meta_type_label)
q = % (meta_type_label, type_label)
with manager.session as s:
if legacy:
return s.run(q, {: nam... | Creates a node with the mandatory attributes name and handle_id also sets type label.
:param manager: Manager to handle sessions and transactions
:param name: Node name
:param meta_type_label: Node meta type
:param type_label: Node label
:param handle_id: Unique id
:param legacy: Backwards comp... |
367,268 | def formatters(*chained_formatters):
def formatters_chain(input_string):
for chained_formatter in chained_formatters:
input_string = chained_formatter(input_string)
return input_string
return formatters_chain | Chain formatter functions.
:param chained_formatters:
:type chained_formatters:
:return:
:rtype: |
367,269 | def get_dataarg(args):
for i, arg in enumerate(args):
if is_nested_config_arg(arg):
return i, arg
elif is_std_config_arg(arg):
return i, {"config": arg}
elif isinstance(arg, (list, tuple)) and is_nested_config_arg(arg[0]):
return i, arg[0]
raise V... | Retrieve the world 'data' argument from a set of input parameters. |
367,270 | def plot(self, coordinates, directed=False, weighted=False, fig=,
ax=None, edge_style=None, vertex_style=None, title=None, cmap=None):
newcurrentcurrentk-ko
X = np.atleast_2d(coordinates)
assert 0 < X.shape[1] <= 3,
if X.shape[1] == 1:
X = np.column_stack((np.arange(X.shape[0]), X))
... | Plot the graph using matplotlib in 2 or 3 dimensions.
coordinates : (n,2) or (n,3) array of vertex coordinates
directed : if True, edges have arrows indicating direction.
weighted : if True, edges are colored by their weight.
fig : a matplotlib Figure to use, or one of {'new','current'}. Defaults to
... |
367,271 | def connect(self, component):
if not isinstance(component, ThreadPool):
raise TypeError()
component.in_queue = self.out_queue
return component | Connect two ThreadPools.
The ``in_queue`` of the second pool will be set as the ``out_queue`` of
the current pool, thus all the output will be input to the second pool.
Args:
component (ThreadPool): the ThreadPool to be connected.
Returns:
ThreadPool: the modifi... |
367,272 | def mixedSuites(self, tests):
if not tests:
return []
head = tests.pop(0)
if not tests:
return [head]
suite = head
tail = tests[:]
context = getattr(head, , None)
if context is not None:
ancestors = [context] + [a for... | The complex case where there are tests that don't all share
the same context. Groups tests into suites with common ancestors,
according to the following (essentially tail-recursive) procedure:
Starting with the context of the first test, if it is not
None, look for tests in the remainin... |
367,273 | def create(genome, config):
connections = [cg.key for cg in itervalues(genome.connections) if cg.enabled]
layers = feed_forward_layers(config.genome_config.input_keys, config.genome_config.output_keys, connections)
node_evals = []
for layer in layers:
for ... | Receives a genome and returns its phenotype (a FeedForwardNetwork). |
367,274 | def row(self):
z = self.Z
total = 0
if 57 <= z <= 71:
return 8
elif 89 <= z <= 103:
return 9
for i in range(len(_pt_row_sizes)):
total += _pt_row_sizes[i]
if total >= z:
return i + 1
return 8 | Returns the periodic table row of the element. |
367,275 | def to_function(var_instance, lineno=None):
assert isinstance(var_instance, SymbolVAR)
from symbols import FUNCTION
var_instance.__class__ = FUNCTION
var_instance.class_ = CLASS.function
var_instance.reset(lineno=lineno)
return var_instance | Converts a var_instance to a function one |
367,276 | def execute(self, conn, child_block_name=, child_lfn_list=[], transaction=False):
sql =
binds = {}
child_ds_name =
child_where =
if child_block_name:
child_ds_name = child_block_name.split()[0]
parent_where = " where d.dataset = :child_ds_name ))"
... | cursors = self.dbi.processData(sql, binds, conn, transaction=transaction, returnCursor=True)
for i in cursors:
d = self.formatCursor(i, size=100)
if isinstance(d, list) or isinstance(d, GeneratorType):
for elem in d:
yield elem
elif d:
... |
367,277 | def value(self):
r = {}
attributes = [attr for attr in dir(self)
if not attr.startswith() and \
not attr.startswith()]
for a in attributes:
if a != "value":
val = getattr(self, a)
if val is not None:... | returns the class as a dictionary |
367,278 | def contains_ignoring_case(self, *items):
if len(items) == 0:
raise ValueError()
if isinstance(self.val, str_types):
if len(items) == 1:
if not isinstance(items[0], str_types):
raise TypeError()
if items[0].lower() not ... | Asserts that val is string and contains the given item or items. |
367,279 | def tagre(tag, attribute, value, quote=, before="", after=""):
if before:
prefix = r"[^>]*%s[^>]*\s+" % before
else:
prefix = r"(?:[^>]*\s+)?"
attrs = dict(
tag=case_insensitive_re(tag),
attribute=case_insensitive_re(attribute),
value=value,
quote=quote,
... | Return a regular expression matching the given HTML tag, attribute
and value. It matches the tag and attribute names case insensitive,
and skips arbitrary whitespace and leading HTML attributes. The "<>" at
the start and end of the HTML tag is also matched.
@param tag: the tag name
@ptype tag: strin... |
367,280 | def serialize_checks(check_set):
check_set_list = []
for check in check_set.all()[:25]:
check_set_list.append(
{
: check.checked_datetime.isoformat(),
: check.response_time,
: 1 if check.success else 0
}
)
return ch... | Serialize a check_set for raphael |
367,281 | def firwin_bpf(N_taps, f1, f2, fs = 1.0, pass_zero=False):
return signal.firwin(N_taps,2*(f1,f2)/fs,pass_zero=pass_zero) | Design a windowed FIR bandpass filter in terms of passband
critical frequencies f1 < f2 in Hz relative to sampling rate
fs in Hz. The number of taps must be provided.
Mark Wickert October 2016 |
367,282 | def parse(directive):
if not directive:
return None
if isinstance(directive, (list, tuple)):
results = []
for d in directive:
results.extend(parse(d))
return results
if isinstance(directive, (dict, client.Placement)):
directive = direc... | Given a string in the format `scope:directive`, or simply `scope`
or `directive`, return a Placement object suitable for passing
back over the websocket API. |
367,283 | def _bls_runner(times,
mags,
nfreq,
freqmin,
stepsize,
nbins,
minduration,
maxduration):
powerbestperiodbestpowertransdepthtransdurationtransingressbintransegressbin
workarr_u = npones(times.size)
... | This runs the pyeebls.eebls function using the given inputs.
Parameters
----------
times,mags : np.array
The input magnitude time-series to search for transits.
nfreq : int
The number of frequencies to use when searching for transits.
freqmin : float
The minimum frequency... |
367,284 | def l2_regularizer(weight=1.0, scope=None):
def regularizer(tensor):
with tf.name_scope(scope, , [tensor]):
l2_weight = tf.convert_to_tensor(weight,
dtype=tensor.dtype.base_dtype,
name=)
return tf.multiply(l2_weight, tf.n... | Define a L2 regularizer.
Args:
weight: scale the loss by this factor.
scope: Optional scope for name_scope.
Returns:
a regularizer function. |
367,285 | def _year_info_pq(self, year, keyword):
doc = self.get_year_doc(year)
p_tags = doc()
texts = [p_tag.text_content().strip() for p_tag in p_tags]
try:
return next(
pq(p_tag) for p_tag, text in zip(p_tags, texts)
if keyword.lower() in tex... | Returns a PyQuery object containing the info from the meta div at
the top of the team year page with the given keyword.
:year: Int representing the season.
:keyword: A keyword to filter to a single p tag in the meta div.
:returns: A PyQuery object for the selected p element. |
367,286 | def write_implied_format(self, path, jpeg_quality=0, jpeg_progressive=0):
filename = fspath(path)
with _LeptonicaErrorTrap():
lept.pixWriteImpliedFormat(
os.fsencode(filename), self._cdata, jpeg_quality, jpeg_progressive
) | Write pix to the filename, with the extension indicating format.
jpeg_quality -- quality (iff JPEG; 1 - 100, 0 for default)
jpeg_progressive -- (iff JPEG; 0 for baseline seq., 1 for progressive) |
367,287 | def message_to_dict(msg):
def parse_headers(msg):
headers = {}
for header, value in msg.items():
hv = []
for text, charset in email.header.decode_header(value):
if type(text) == bytes:
charset = charset if charset else
... | Convert an email message into a dictionary.
This function transforms an `email.message.Message` object
into a dictionary. Headers are stored as key:value pairs
while the body of the message is stored inside `body` key.
Body may have two other keys inside, 'plain', for plain body
messages and 'html'... |
367,288 | def update(self, name=None, metadata=None):
return self.policy.update_webhook(self, name=name, metadata=metadata) | Updates this webhook. One or more of the parameters may be specified. |
367,289 | def sparse(x0, rho, gamma):
lmbda = float(gamma) / rho
return (x0 - lmbda) * (x0 >= lmbda) + (x0 + lmbda) * (x0 <= -lmbda) | Proximal operator for the l1 norm (induces sparsity)
Parameters
----------
x0 : array_like
The starting or initial point used in the proximal update step
rho : float
Momentum parameter for the proximal step (larger value -> stays closer to x0)
gamma : float
A constant that... |
367,290 | def _sample_condition(exp_condition, frame_times, oversampling=50,
min_onset=-24):
n = frame_times.size
min_onset = float(min_onset)
n_hr = ((n - 1) * 1. / (frame_times.max() - frame_times.min()) *
(frame_times.max() * (1 + 1. / (n - 1)) - frame_times.min() -
... | Make a possibly oversampled event regressor from condition information.
Parameters
----------
exp_condition : arraylike of shape (3, n_events)
yields description of events for this condition as a
(onsets, durations, amplitudes) triplet
frame_times : array of shape(n_scans)
samp... |
367,291 | def remoteLocation_resolve(self, d_remote):
b_status = False
str_remotePath = ""
if in d_remote.keys():
str_remotePath = d_remote[]
b_status = True
if in d_remote.keys():
d_ret = self.storage_resolveBasedOnKey(key = d_remote... | Resolve the remote path location
:param d_remote: the "remote" specification
:return: a string representation of the remote path |
367,292 | def add_words(self):
data_blocks = len(self.buffer.getvalue()) // 8
total_blocks = tables.data_capacity[self.version][self.error][0] // 8
needed_blocks = total_blocks - data_blocks
if needed_blocks == 0:
return None
block = itertools.cycle([, ])
... | The data block must fill the entire data capacity of the QR code.
If we fall short, then we must add bytes to the end of the encoded
data field. The value of these bytes are specified in the standard. |
367,293 | def get_b(self):
try:
return self.b.value
except AttributeError:
return self.sky_coord.transform_to().b.value | Get Galactic latitude (b) corresponding to the current position
:return: Latitude |
367,294 | def format_result(line, line_num, txt):
return + str(line_num) + + line.replace(txt, + txt + ) | highlight the search result |
367,295 | def get_users(self, search=None, page=1, per_page=20, **kwargs):
if search:
return self.get(, page=page, per_page=per_page, search=search, **kwargs)
return self.get(, page=page, per_page=per_page, **kwargs) | Returns a list of users from the Gitlab server
:param search: Optional search query
:param page: Page number (default: 1)
:param per_page: Number of items to list per page (default: 20, max: 100)
:return: List of Dictionaries containing users
:raise: HttpError if invalid respons... |
367,296 | def _parse_value_pb(value_pb, field_type):
if value_pb.HasField("null_value"):
return None
if field_type.code == type_pb2.STRING:
result = value_pb.string_value
elif field_type.code == type_pb2.BYTES:
result = value_pb.string_value.encode("utf8")
elif field_type.code == type... | Convert a Value protobuf to cell data.
:type value_pb: :class:`~google.protobuf.struct_pb2.Value`
:param value_pb: protobuf to convert
:type field_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.Type`
:param field_type: type code for the value
:rtype: varies on field_type
:returns: valu... |
367,297 | def read_clusters(self, min_cluster_size):
num_found = 0
clusters = []
with open(self.get_path(OslomRunner.OUTPUT_FILE), "r") as reader:
for line1, line2 in itertools.izip_longest(*[reader] * 2):
info = OslomRunner.RE_INFOLINE.match(line1.strip()... | Read and parse OSLOM clusters output file. |
367,298 | def _maybe_notify_connected(self, arg):
if self._connected_listeners is None:
return
for d in self._connected_listeners:
d.callback(arg)
self._connected_listeners = None | Internal helper.
.callback or .errback on all Deferreds we've returned from
`when_connected` |
367,299 | def draw_variable_local(self, size):
return ss.norm.rvs(loc=self.mu0, scale=self.sigma0, size=size) | Simulate from the Normal distribution using instance values
Parameters
----------
size : int
How many simulations to perform
Returns
----------
np.ndarray of Normal random variable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.