Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
380,900 | def ret(f, *args, **kwargs):
kwargs.update({: True})
return _stump(f, *args, **kwargs) | Automatically log progress on function entry and exit. Default logging
value: info. The function's return value will be included in the logs.
*Logging with values contained in the parameters of the decorated function*
Message (args[0]) may be a string to be formatted with parameters passed to
the decor... |
380,901 | def get_yaml_parser_roundtrip_for_context():
yaml_writer = get_yaml_parser_roundtrip()
yaml_writer.Representer.add_representer(
Context,
yamler.representer.RoundTripRepresenter.represent_dict)
return yaml_writer | Create a yaml parser that can serialize the pypyr Context.
Create yaml parser with get_yaml_parser_roundtrip, adding Context.
This allows the yaml parser to serialize the pypyr Context. |
380,902 | def read_from_bpch(filename, file_position, shape, dtype, endian,
use_mmap=False):
offset = file_position + 4
if use_mmap:
d = np.memmap(filename, dtype=dtype, mode=, shape=shape,
offset=offset, order=)
else:
with FortranFile(filename, , endian) ... | Read a chunk of data from a bpch output file.
Parameters
----------
filename : str
Path to file on disk containing the data
file_position : int
Position (bytes) where desired data chunk begins
shape : tuple of ints
Resultant (n-dimensional) shape of requested data; the chun... |
380,903 | def consolidate_output(job, config, mutect, pindel, muse):
work_dir = job.fileStore.getLocalTempDir()
mutect_tar, pindel_tar, muse_tar = None, None, None
if mutect:
mutect_tar = job.fileStore.readGlobalFile(mutect, os.path.join(work_dir, ))
if pindel:
pindel_tar = job.fileStore.read... | Combine the contents of separate tarball outputs into one via streaming
:param JobFunctionWrappingJob job: passed automatically by Toil
:param Namespace config: Argparse Namespace object containing argument inputs
:param str mutect: MuTect tarball FileStoreID
:param str pindel: Pindel tarball FileStore... |
380,904 | def display(self, image):
assert(image.size == self.size)
self._last_image = image
self._count += 1
filename = self._file_template.format(self._count)
image = self.preprocess(image)
surface = self.to_surface(image, alpha=self._contrast)
logger.debug("Wri... | Takes a :py:mod:`PIL.Image` and dumps it to a numbered PNG file. |
380,905 | def crypto_sign_open(signed, pk):
message = ffi.new("unsigned char[]", len(signed))
message_len = ffi.new("unsigned long long *")
if lib.crypto_sign_open(
message, message_len, signed, len(signed), pk) != 0:
raise exc.BadSignatureError("Signature was forged or corrupt")
return... | Verifies the signature of the signed message ``signed`` using the public
key ``pk`` and returns the unsigned message.
:param signed: bytes
:param pk: bytes
:rtype: bytes |
380,906 | def _prepare_load_balancers(self):
stack = {
A.NAME: self[A.NAME],
A.VERSION: self[A.VERSION],
}
for load_balancer in self.get(R.LOAD_BALANCERS, []):
svars = {A.STACK: stack}
load_balancer[A.loadbalancer.VARS] = svars | Prepare load balancer variables |
380,907 | def get_best_ip_by_real_data_fetch(_type=):
from QUANTAXIS.QAUtil.QADate import QA_util_today_str
import time
pre_trade_date=QA_util_get_real_date(QA_util_today_str())
pre_trade_date=QA_util_get_real_date(pre_trade_date)
def get_stock_data_by_ip(ips):
start=time.time... | 用特定的数据获取函数测试数据获得的时间,从而选择下载数据最快的服务器ip
默认使用特定品种1min的方式的获取 |
380,908 | def cublasStbmv(handle, uplo, trans, diag, n, k, A, lda, x, incx):
status = _libcublas.cublasStbmv_v2(handle,
_CUBLAS_FILL_MODE[uplo],
_CUBLAS_OP[trans],
_CUBLAS_DIAG[diag],
... | Matrix-vector product for real triangular-banded matrix. |
380,909 | def matches_all_rules(self, target_filename):
for rule in self.match_rules:
if rule.test(target_filename) is False:
return False
self.logger.debug(.format(self.name,
os.path.basename(target_filename),
... | Returns true if the given file matches all the rules in this ruleset.
:param target_filename:
:return: boolean |
380,910 | def get_command(self, ctx, cmd_name):
path = "%s.%s" % (__name__, cmd_name)
path = path.replace("-", "_")
module = importlib.import_module(path)
return getattr(module, ) | Get command for click. |
380,911 | def get(obj: JsonObj, item: str, default: JsonObjTypes=None) -> JsonObjTypes:
return obj._get(item, default) | Dictionary get routine |
380,912 | def SURFstar_compute_scores(inst, attr, nan_entries, num_attributes, mcmap, NN_near, NN_far, headers, class_type, X, y, labels_std, data_type):
scores = np.zeros(num_attributes)
for feature_num in range(num_attributes):
if len(NN_near) > 0:
scores[feature_num] += compute_score(attr... | Unique scoring procedure for SURFstar algorithm. Scoring based on nearest neighbors within defined radius, as well as
'anti-scoring' of far instances outside of radius of current target instance |
380,913 | def init_group(self, group, chunk_size,
compression=None, compression_opts=None):
create_index(group, chunk_size)
self._entries[].create_dataset(
group, chunk_size, compression=compression,
compression_opts=compression_opts)
self._entries[].c... | Initializes a HDF5 group compliant with the stored data.
This method creates the datasets 'items', 'labels', 'features'
and 'index' and leaves them empty.
:param h5py.Group group: The group to initializes.
:param float chunk_size: The size of a chunk in the file (in MB).
:param... |
380,914 | def pilatus_description_metadata(description):
result = {}
if not description.startswith():
return result
for c in :
description = description.replace(c, )
for line in description.split():
if line[:2] != :
continue
line = line.split()
name = line[... | Return metatata from Pilatus image description as dict.
Return metadata from Pilatus pixel array detectors by Dectris, created
by camserver or TVX software.
>>> pilatus_description_metadata('# Pixel_size 172e-6 m x 172e-6 m')
{'Pixel_size': (0.000172, 0.000172)} |
380,915 | def _get_public_room(self, room_name, invitees: List[User]):
room_name_full = f
invitees_uids = [user.user_id for user in invitees]
for _ in range(JOIN_RETRIES):
try:
room = self._client.join_room(room_name_full)
except MatrixRequest... | Obtain a public, canonically named (if possible) room and invite peers |
380,916 | def import_module(module_fqname, superclasses=None):
module_name = module_fqname.rpartition(".")[-1]
module = __import__(module_fqname, globals(), locals(), [module_name])
modules = [class_ for cname, class_ in
inspect.getmembers(module, inspect.isclass)
if class_.__module... | Imports the module module_fqname and returns a list of defined classes
from that module. If superclasses is defined then the classes returned will
be subclasses of the specified superclass or superclasses. If superclasses
is plural it must be a tuple of classes. |
380,917 | def queryset(self, request, queryset):
form = self.get_form(request)
self.form = form
start_date = form.start_date()
end_date = form.end_date()
if form.is_valid() and (start_date or end_date):
args = self.__get_filterargs(
start=start_date,... | That's the trick - we create self.form when django tries to get our queryset.
This allows to create unbount and bound form in the single place. |
380,918 | def crop_to_extents(img1, img2, padding):
beg_coords1, end_coords1 = crop_coords(img1, padding)
beg_coords2, end_coords2 = crop_coords(img2, padding)
beg_coords = np.fmin(beg_coords1, beg_coords2)
end_coords = np.fmax(end_coords1, end_coords2)
img1 = crop_3dimage(img1, beg_coords, end_coords... | Crop the images to ensure both fit within the bounding box |
380,919 | def sign_url_path(url, secret_key, expire_in=None, digest=None):
result = urlparse(url)
query_args = MultiValueDict(parse_qs(result.query))
query_args[] = token()
if expire_in is not None:
query_args[] = int(time() + expire_in)
query_args[] = _generate_signature(result.path, secret... | Sign a URL (excluding the domain and scheme).
:param url: URL to sign
:param secret_key: Secret key
:param expire_in: Expiry time.
:param digest: Specify the digest function to use; default is sha256 from hashlib
:return: Signed URL |
380,920 | def prepare_actions(self, obs):
now = time.time()
while self._past_actions and self._past_actions[0].deadline < now:
self._past_actions.pop(0)
def add_act(ability_id, color, pos, timeout=1):
if ability_id:
ability = self._static_data.abilities[ability_id]
if ability.remaps_... | Keep a list of the past actions so they can be drawn. |
380,921 | def _read_n_samples(channel_file):
n_blocks = int((channel_file.stat().st_size - HDR_LENGTH) / BLK_SIZE)
n_samples = n_blocks * BLK_LENGTH
return n_blocks, n_samples | Calculate the number of samples based on the file size
Parameters
----------
channel_file : Path
path to single filename with the header
Returns
-------
int
number of blocks (i.e. records, in which the data is cut)
int
number of samples |
380,922 | def pattern_to_str(pattern):
if isinstance(pattern, str):
return repr(pattern)
else:
return repr(pattern.pattern) if pattern else None | Convert regex pattern to string.
If pattern is string it returns itself,
if pattern is SRE_Pattern then return pattern attribute
:param pattern: pattern object or string
:return: str: pattern sttring |
380,923 | def dense_to_deeper_block(dense_layer, weighted=True):
units = dense_layer.units
weight = np.eye(units)
bias = np.zeros(units)
new_dense_layer = StubDense(units, units)
if weighted:
new_dense_layer.set_weights(
(add_noise(weight, np.array([0, 1])), add_noise(bias, np.array([... | deeper dense layer. |
380,924 | def phone_numbers(self):
if self._phone_numbers is None:
self._phone_numbers = PhoneNumberList(self)
return self._phone_numbers | :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberList |
380,925 | def format(self):
values = {}
title = "Description"
description = self.command.description + "\n\n" + self.get_ending_note() if not self.is_cog() else inspect.getdoc(self.command)
sections = []
if isinstance(self.command, Command):
description = self.co... | Handles the actual behaviour involved with formatting.
To change the behaviour, this method should be overridden.
Returns
--------
list
A paginated output of the help command. |
380,926 | def crypto_aead_chacha20poly1305_ietf_encrypt(message, aad, nonce, key):
ensure(isinstance(message, bytes), ,
raising=exc.TypeError)
mlen = len(message)
ensure(mlen <= crypto_aead_chacha20poly1305_ietf_MESSAGEBYTES_MAX,
.format(
crypto_aead_chacha20poly1305_ietf_M... | Encrypt the given ``message`` using the IETF ratified chacha20poly1305
construction described in RFC7539.
:param message:
:type message: bytes
:param aad:
:type aad: bytes
:param nonce:
:type nonce: bytes
:param key:
:type key: bytes
:return: authenticated ciphertext
:rtype:... |
380,927 | def _build_tree(self):
groups = self._groups or self.get_children_paths(self.root_path)
for group in groups:
node = Node(name=group, parent=self.root)
self.root.children.append(node)
self._init_sub_groups(node) | Build a full or a partial tree, depending on the groups/sub-groups specified. |
380,928 | def execute_notebook(npth, dpth, timeout=1200, kernel=):
ep = ExecutePreprocessor(timeout=timeout, kernel_name=kernel)
nb = nbformat.read(npth, as_version=4)
t0 = timer()
ep.preprocess(nb, {: {: dpth}})
t1 = timer()
with open(npth, ) as f:
nbformat.write(nb, f)
return t1 - t0 | Execute the notebook at `npth` using `dpth` as the execution
directory. The execution timeout and kernel are `timeout` and
`kernel` respectively. |
380,929 | def clear(self):
for track in self._tracks:
self._tracks[track].setall(False) | Clear tracks in memory - all zero |
380,930 | def _finish_futures(self, responses):
exception_args = None
if len(self._target_objects) != len(responses):
raise ValueError("Expected a response for every request.")
for target_object, subresponse in zip(self._target_objects, responses):
if n... | Apply all the batch responses to the futures created.
:type responses: list of (headers, payload) tuples.
:param responses: List of headers and payloads from each response in
the batch.
:raises: :class:`ValueError` if no requests have been deferred. |
380,931 | def record(self, pipeline_name, from_study):
try:
return self._records[(pipeline_name, from_study)]
except KeyError:
found = []
for sname, pnames in groupby(sorted(self._records,
key=itemgetter(1)),
... | Returns the provenance record for a given pipeline
Parameters
----------
pipeline_name : str
The name of the pipeline that generated the record
from_study : str
The name of the study that the pipeline was generated from
Returns
-------
re... |
380,932 | def rpm(self, vol_per_rev):
return Stock.rpm(self, vol_per_rev, self.Q_stock()).to(u.rev/u.min) | Return the pump speed required for the reactor's stock of material
given the volume of fluid output per revolution by the stock's pump.
:param vol_per_rev: Volume of fluid pumped per revolution (dependent on pump and tubing)
:type vol_per_rev: float
:return: Pump speed for the material... |
380,933 | def parse(yaml, validate=True):
data = read_yaml(yaml)
if validate:
from .validation import validate
validate(data, raise_exc=True)
return Config.parse(data) | Parse the given YAML data into a `Config` object, optionally validating it first.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:type yaml: list|dict|str|file
:param validate: Whether to validate the data before attempting to parse it.
:type validate: bool
:retu... |
380,934 | def build_ellipse_model(shape, isolist, fill=0., high_harmonics=False):
from scipy.interpolate import LSQUnivariateSpline
finely_spaced_sma = np.arange(isolist[0].sma, isolist[-1].sma, 0.1)
nodes = isolist.sma[2:-2]
intens_array = LSQUnivariateSpline(
isolist.s... | Build an elliptical model galaxy image from a list of isophotes.
For each ellipse in the input isophote list the algorithm fills the
output image array with the corresponding isophotal intensity.
Pixels in the output array are in general only partially covered by
the isophote "pixel". The algorithm ta... |
380,935 | def run_strelka(job, tumor_bam, normal_bam, univ_options, strelka_options, split=True):
if strelka_options[]:
chromosomes = strelka_options[]
else:
chromosomes = sample_chromosomes(job, strelka_options[])
num_cores = min(len(chromosomes), univ_options[])
strelka = job.wrapJobFn(run_... | Run the strelka subgraph on the DNA bams. Optionally split the results into per-chromosome
vcfs.
:param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq
:param dict normal_bam: Dict of bam and bai for normal DNA-Seq
:param dict univ_options: Dict of universal options used by almost all tools
... |
380,936 | def type_stmt(self, stmt, p_elem, pset):
typedef = stmt.i_typedef
if typedef and not stmt.i_is_derived:
uname, dic = self.unique_def_name(typedef)
if uname not in dic:
self.install_def(uname, typedef, dic)
SchemaNode("ref", p_elem).set_attr("... | Handle ``type`` statement.
Built-in types are handled by one of the specific type
callback methods defined below. |
380,937 | def daily_from_hourly(df):
df_daily = pd.DataFrame()
if in df:
df_daily[] = df.temp.resample().mean()
df_daily[] = df.temp.groupby(df.temp.index.date).min()
df_daily[] = df.temp.groupby(df.temp.index.date).max()
if in df:
df_daily[] = df.precip.resample().sum()
... | Aggregates data (hourly to daily values) according to the characteristics
of each variable (e.g., average for temperature, sum for precipitation)
Args:
df: dataframe including time series with one hour time steps
Returns:
dataframe (daily) |
380,938 | def _create_create_tracking_event(instance):
event = _create_event(instance, CREATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
_create_tracked_field(event, instance, field) | Create a TrackingEvent and TrackedFieldModification for a CREATE event. |
380,939 | def token_generator(self, texts, **kwargs):
for text_idx, text in enumerate(texts):
if self.lower:
text = text.lower()
for char in text:
yield text_idx, char | Yields tokens from texts as `(text_idx, character)` |
380,940 | def stringize(
self,
rnf_profile,
):
coor_width = max(rnf_profile.coor_width, len(str(self.left)), len(str(self.right)))
return "({},{},{},{},{})".format(
str(self.genome_id).zfill(rnf_profile.genome_id_width),
str(self.chr_id).zfill(rnf_profile.chr_... | Create RNF representation of this segment.
Args:
rnf_profile (rnftools.rnfformat.RnfProfile): RNF profile (with widths). |
380,941 | def _initial_guess(self, countsmat):
if self.theta_ is not None:
return self.theta_
if self.guess == :
transmat, pi = _transmat_mle_prinz(countsmat)
K = np.real(scipy.linalg.logm(transmat)) / self.lag_time
elif self.guess == :
transmat,... | Generate an initial guess for \theta. |
380,942 | def get_stp_mst_detail_output_msti_port_transmitted_stp_type(self, **kwargs):
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output,... | Auto Generated Code |
380,943 | def number_peaks(self, x, n=None):
if n is None:
n = 5
peaks = feature_calculators.number_peaks(x, n)
logging.debug("agg linear trend by tsfresh calculated")
return peaks | As in tsfresh `number_peaks <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/feature_extraction/\
feature_calculators.py#L1003>`_
Calculates the number of peaks of at least support n in the time series x. A peak of support n is defined \
as a subsequence of x ... |
380,944 | def file(cls, path, encoding=None, parser=None):
cls.__hierarchy.append(file.File(path, encoding, parser)) | Set a file as a source.
File are parsed as literal python dicts by default, this behaviour
can be configured.
Args:
path: The path to the file to be parsed
encoding: The encoding of the file.
Defaults to 'raw'. Available built-in values: 'ini', 'json', '... |
380,945 | def make_sshable(c):
user = c.travis.sudo.user
home = "~{0}".format(user)
c.sudo("cp {0}/{{id_rsa.pub,authorized_keys}}".format(ssh_dir)) | Set up passwordless SSH keypair & authorized_hosts access to localhost. |
380,946 | def flush(self, objects=None, batch_size=None, **kwargs):
batch_size = batch_size or self.config.get()
if objects:
from_store = False
else:
from_store = True
objects = self.itervalues()
objects = sorted(objects, key=... | flush objects stored in self.container or those passed in |
380,947 | def registration_options(self):
registration_options = {}
rs = self.registration_model()
for k, v in self.__dict__.items():
if k not in DEFAULT_BASE_FIELDS + []:
try:
getattr(rs, k)
registration_options.update({k: v})
... | Gathers values for common attributes between the
registration model and this instance. |
380,948 | def point_dist(pt1, pt2):
from scipy import linalg as spla
dist = spla.norm(point_displ(pt1, pt2))
return dist | Calculate the Euclidean distance between two n-D points.
|pt1 - pt2|
.. todo:: Complete point_dist docstring |
380,949 | def teardown_logical_port_connectivity(self, context, port_db,
hosting_device_id):
if port_db is None or port_db.get() is None:
LOG.warning("Port id is None! Cannot remove port "
"from hosting_device:%s", hosting_device_id)
... | Removes connectivity for a logical port.
Unplugs the corresponding data interface from the VM. |
380,950 | def _gcs_get_key_names(bucket, pattern):
return [obj.metadata.name for obj in _gcs_get_keys(bucket, pattern)] | Get names of all Google Cloud Storage keys in a specified bucket that match a pattern. |
380,951 | def close(self):
if self._con is not None:
self._pool.cache(self._con)
self._con = None | Close the pooled connection. |
380,952 | def getratio(self, code) :
if len(code) == 0 : return 0
code_replaced = self.prog.sub(, code)
return (len(code) - len(code_replaced)) / len(code) | Get ratio of code and pattern matched |
380,953 | def convert(cls, **kwargsql):
filters = []
for k, v in kwargsql.items():
terms = k.split()
if terms[-1] in cls.KWARGQL_SUPPORTED_MONGO_OPS:
v = {
+ terms[-1]: v
}
if terms[-1] == :
v... | :param dict kwargsql:
Kwargsql expression to convert
:return:
filter to be used in :py:method:`pymongo.collection.find`
:rtype: dict |
380,954 | def load(cls, config: Optional[Config] = None):
if cls._dfk is not None:
raise RuntimeError()
if config is None:
cls._dfk = DataFlowKernel(Config())
else:
cls._dfk = DataFlowKernel(config)
return cls._dfk | Load a DataFlowKernel.
Args:
- config (Config) : Configuration to load. This config will be passed to a
new DataFlowKernel instantiation which will be set as the active DataFlowKernel.
Returns:
- DataFlowKernel : The loaded DataFlowKernel object. |
380,955 | def switch_training(self, flag):
if self._is_training == flag: return
self._is_training = flag
if flag:
self._training_flag.set_value(1)
else:
self._training_flag.set_value(0) | Switch training mode.
:param flag: switch on training mode when flag is True. |
380,956 | def export_coreml(self, filename):
import coremltools
def _create_vision_feature_print_scene():
prob_name = self.target +
top_spec = coremltools.proto.Model_pb2.Model()
top_spec.specificationVersion... | Save the model in Core ML format.
See Also
--------
save
Examples
--------
>>> model.export_coreml('myModel.mlmodel') |
380,957 | def _check_unpack_options(extensions, function, extra_args):
existing_extensions = {}
for name, info in _UNPACK_FORMATS.items():
for ext in info[0]:
existing_extensions[ext] = name
for extension in extensions:
if extension in existing_extensions:
msg =
... | Checks what gets registered as an unpacker. |
380,958 | def get_sites(self, filter_func=lambda x: True):
response = self._session.get(BASE_URL_TSQUARE + )
response.raise_for_status()
site_list = response.json()[]
if not site_list:
if filter_func(t_site):
result_list.append(t_site)
ret... | Returns a list of TSquareSite objects that represent the sites available
to a user.
@param filter_func - A function taking in a Site object as a parameter
that returns a True or False, depending on whether
or not that site should be returned by t... |
380,959 | def _handle_struct_ref(self, node, scope, ctxt, stream):
self._dlog("handling struct ref")
struct = self._handle_node(node.name, scope, ctxt, stream)
try:
sub_field = getattr(struct, node.field.name)
except AttributeError as e:
... | TODO: Docstring for _handle_struct_ref.
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO |
380,960 | def delete_api_model(restApiId, modelName, region=None, key=None, keyid=None, profile=None):
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_model(restApiId=restApiId, modelName=modelName)
return {: True}
except ClientError as e:
retur... | Delete a model identified by name in a given API
CLI Example:
.. code-block:: bash
salt myminion boto_apigateway.delete_api_model restApiId modelName |
380,961 | def quote_value(value):
try:
if value == None:
return SQL_NULL
elif isinstance(value, SQL):
return quote_sql(value.template, value.param)
elif is_text(value):
return SQL("")
elif is_data(value):
return quote_value(json_encode(value... | convert values to mysql code for the same
mostly delegate directly to the mysql lib, but some exceptions exist |
380,962 | def _watch(inotify, watchers, watch_flags, s3_uploader):
executor = futures.ThreadPoolExecutor(max_workers=1)
last_pass_done = False
stop_file_exists = False
while not last_pass_done:
for event in inotify.read(timeout=1000):
for flag in inotify_simple.f... | As soon as a user is done with a file under `/opt/ml/output/intermediate`
we would get notified by using inotify. We would copy this file under
`/opt/ml/output/intermediate/.tmp.sagemaker_s3_sync` folder preserving
the same folder structure to prevent it from being further modified.
As we copy the file ... |
380,963 | def ssh_invite(ctx, code_length, user, **kwargs):
for name, value in kwargs.items():
setattr(ctx.obj, name, value)
from . import cmd_ssh
ctx.obj.code_length = code_length
ctx.obj.ssh_user = user
return go(cmd_ssh.invite, ctx.obj) | Add a public-key to a ~/.ssh/authorized_keys file |
380,964 | def identity_to_string(identity_dict):
result = []
if identity_dict.get():
result.append(identity_dict[] + )
if identity_dict.get():
result.append(identity_dict[] + )
result.append(identity_dict[])
if identity_dict.get():
result.append( + identity_dict[])
if identity... | Dump Identity dictionary into its string representation. |
380,965 | def add_item(self, key, value, cache_name=None):
cache_name = cache_name or
value = % (cache_name, key, value)
self._set(, value.strip(), multi=True)
return self._section | Add an item into the given cache.
This is a commodity option (mainly useful for testing) allowing you
to store an item in a uWSGI cache during startup.
:param str|unicode key:
:param value:
:param str|unicode cache_name: If not set, default will be used. |
380,966 | def contract_multiplier(self):
try:
return self.__dict__["contract_multiplier"]
except (KeyError, ValueError):
raise AttributeError(
"Instrument(order_book_id={}) has no attribute ".format(self.order_book_id)
) | [float] 合约乘数,例如沪深300股指期货的乘数为300.0(期货专用) |
380,967 | def get_params(self, deep=False):
params = super(XGBModel, self).get_params(deep=deep)
if isinstance(self.kwargs, dict):
params.update(self.kwargs)
if params[] is np.nan:
params[] = None
return params | Get parameters. |
380,968 | def create(self, name, script, params=None):
params = update_params(params, {
: name,
: script
})
return self.request(, params, ) | /v1/startupscript/create
POST - account
Create a startup script
Link: https://www.vultr.com/api/#startupscript_create |
380,969 | def thaw_from_args(parser):
parser.add_argument(,
dest=,
help=)
parser.add_argument(,
dest=,
help=) | Adds command line options for things related to inline thawing
of icefiles |
380,970 | def get_language():
global sensor_graph, statement
if sensor_graph is not None:
return sensor_graph
_create_primitives()
_create_simple_statements()
_create_block_bnf()
sensor_graph = ZeroOrMore(statement) + StringEnd()
sensor_graph.ignore(comment)
return sensor_graph | Create or retrieve the parse tree for defining a sensor graph. |
380,971 | def invertible_1x1_conv(name, x, reverse=False):
_, height, width, channels = common_layers.shape_list(x)
w_shape = [channels, channels]
random_matrix = np.random.rand(channels, channels)
np_w = scipy.linalg.qr(random_matrix)[0].astype("float32")
np_p, np_l, np_u = scipy.linalg.lu(np_w)
np_s = np... | 1X1 convolution on x.
The 1X1 convolution is parametrized as P*L*(U + sign(s)*exp(log(s))) where
1. P is a permutation matrix.
2. L is a lower triangular matrix with diagonal entries unity.
3. U is a upper triangular matrix where the diagonal entries zero.
4. s is a vector.
sign(s) and P are fixed and the... |
380,972 | def _handle_start_center(self, attrs):
center_lat = attrs.get("lat")
center_lon = attrs.get("lon")
if center_lat is None or center_lon is None:
raise ValueError("Unable to get lat or lon of way center.")
self._curr["center_lat"] = Decimal(center_lat)
self._cu... | Handle opening center element
:param attrs: Attributes of the element
:type attrs: Dict |
380,973 | def consolidate_tarballs_job(job, fname_to_id):
work_dir = job.fileStore.getLocalTempDir()
tar_paths = []
for fname, file_store_id in fname_to_id.iteritems():
p = job.fileStore.readGlobalFile(file_store_id, os.path.join(work_dir, fname + ))
tar_paths.append((p, fname))
... | Combine the contents of separate tarballs into one.
Subdirs within the tarball will be named the keys in **fname_to_id
:param JobFunctionWrappingJob job: passed automatically by Toil
:param dict[str,str] fname_to_id: Dictionary of the form: file-name-prefix=FileStoreID
:return: The file store ID of the... |
380,974 | def colless(self, normalize=):
t_res = copy(self); t_res.resolve_polytomies(); leaves_below = dict(); n = 0; I = 0
for node in t_res.traverse_postorder():
if node.is_leaf():
leaves_below[node] = 1; n += 1
else:
cl,cr = node.children; nl = ... | Compute the Colless balance index of this ``Tree``. If the tree has polytomies, they will be randomly resolved
Args:
``normalize`` (``str``): How to normalize the Colless index (if at all)
* ``None`` to not normalize
* ``"leaves"`` to normalize by the number of leaves
... |
380,975 | def __check_success(resp):
if "success" not in resp.keys():
try:
raise APIError(, , resp["error"])
except KeyError:
raise APIError(, , str(resp))
return resp["success"] | Check a JSON server response to see if it was successful
:type resp: Dictionary (parsed JSON from response)
:param resp: the response string
:rtype: String
:returns: the success message, if it exists
:raises: APIError if the success message is not present |
380,976 | def vm_netstats(vm_=None, **kwargs):
your-vmrx_bytesrx_packetsrx_errsrx_droptx_bytestx_packetstx_errstx_drop*
def _info(dom):
nics = _get_nics(dom)
ret = {
: 0,
: 0,
: 0,
: 0,
: 0,
: 0,
... | Return combined network counters used by the vms on this hyper in a
list of dicts:
:param vm_: domain name
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.... |
380,977 | def reMutualReceptions(self, idA, idB):
mr = self.mutualReceptions(idA, idB)
filter_ = [, ]
return [(a,b) for (a,b) in mr if (a in filter_ and b in filter_)] | Returns ruler and exaltation mutual receptions. |
380,978 | def getTargetNamespace(self):
parent = self
targetNamespace =
tns = self.attributes.get(targetNamespace)
while not tns and parent and parent._parent is not None:
parent = parent._parent()
tns = parent.attributes.get(targetNamespace)
return tns or... | return targetNamespace |
380,979 | def obspy_3d_plot(inventory, catalog, size=(10.5, 7.5), **kwargs):
nodes = []
for ev in catalog:
nodes.append((ev.preferred_origin().latitude,
ev.preferred_origin().longitude,
ev.preferred_origin().depth / 1000))
all_stas = []
for net in inve... | Plot obspy Inventory and obspy Catalog classes in three dimensions.
:type inventory: obspy.core.inventory.inventory.Inventory
:param inventory: Obspy inventory class containing station metadata
:type catalog: obspy.core.event.catalog.Catalog
:param catalog: Obspy catalog class containing event metadata... |
380,980 | def save_svg(string, parent=None):
if isinstance(string, unicode):
string = string.encode()
dialog = QtGui.QFileDialog(parent, )
dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
dialog.setDefaultSuffix()
dialog.setNameFilter()
if dialog.exec_():
filename = dialog.selected... | Prompts the user to save an SVG document to disk.
Parameters:
-----------
string : basestring
A Python string containing a SVG document.
parent : QWidget, optional
The parent to use for the file dialog.
Returns:
--------
The name of the file to which the document was saved... |
380,981 | def dict_to_numpy_dict(obj_dict):
return {key: np.asarray(value) if value is not None else None for key, value in obj_dict.items()} | Convert a dictionary of lists into a dictionary of numpy arrays |
380,982 | def all_files_exist(file_list):
all_exist = True
for filename in file_list:
all_exist = all_exist and os.path.isfile(filename)
return all_exist | Check if all files exist.
:param file_list: the names of files to check.
:type file_list: list
:returns: ``True`` if all files exist, ``False`` otherwise. |
380,983 | def format_usage_masks(self, V_usage_mask_in, J_usage_mask_in, print_warnings = True):
if V_usage_mask_in is None:
V_usage_mask = self.d_V_usage_mask
elif isinstance(V_usage_mask_in, list):
e_V_usage_mask = set()
for v in V_usage_mask_i... | Format raw usage masks into lists of indices.
Usage masks allows the Pgen computation to be conditioned on the V and J
gene/allele identities. The inputted masks are lists of strings, or a
single string, of the names of the genes or alleles to be conditioned on.
The default mask ... |
380,984 | def simplex_find_cycle(self):
nl = self.get_node_list()
q = [nl[0]]
visited = []
depth = {nl[0]:0}
pred = {nl[0]:None}
for n in nl:
self.get_node(n).set_attr(, None)
component_nr = int(nl[0])
self.get_node(nl[0]).set_... | API:
simplex_find_cycle(self)
Description:
Returns a cycle (list of nodes) if the graph has one, returns None
otherwise. Uses DFS. During DFS checks existence of arcs to lower
depth regions. Note that direction of the arcs are not important.
Return:
... |
380,985 | def p_ports(self, p):
wid = None
port = Port(name=p[3], width=wid, type=None, lineno=p.lineno(1))
p[0] = p[1] + (port,)
p.set_lineno(0, p.lineno(1)) | ports : ports COMMA portname |
380,986 | def get_geostationary_angle_extent(geos_area):
req = geos_area.proj_dict[] / 1000
rp = geos_area.proj_dict[] / 1000
h = geos_area.proj_dict[] / 1000 + req
aeq = 1 - req**2 / (h ** 2)
ap_ = 1 - rp**2 / (h ** 2)
xmax = np.arccos(np.sqrt(aeq))
ymax = np.arccos(n... | Get the max earth (vs space) viewing angles in x and y. |
380,987 | def main(argv):
import argparse
description = \
\
\
parser = argparse.ArgumentParser(prog=, description=description)
parser.add_argument(, nargs=, help=)
parser.add_argument(, default=None, type=str, required=False)
parser.add_argume... | This function sets up a command-line option parser and then calls match_and_print
to do all of the real work. |
380,988 | def pdf_row_limiter(rows, limits=None, **kwargs):
limits = limits or [None, None]
upper_limit = limits[0] if limits else None
lower_limit = limits[1] if len(limits) > 1 else None
return rows[upper_limit: lower_limit] | Limit row passing a value. In this case we dont implementate a best effort
algorithm because the posibilities are infite with a data text structure
from a pdf. |
380,989 | def run(self):
self._logger.info("running for <{url}>".format(url=self._url))
args = format_args(self._options)
self._logger.debug("command: `{cmd}` / args: {args}".
format(cmd=self._cmd, args=args))
try:
process = Popen(
... | Perform phantomas run |
380,990 | def verify_invoice_params(self, price, currency):
if re.match("^[A-Z]{3,3}$", currency) is None:
raise BitPayArgumentError("Currency is invalid.")
try:
float(price)
except:
raise BitPayArgumentError("Price must be formatted as a float") | Deprecated, will be made private in 2.4 |
380,991 | def register_opts(conf):
conf.register_cli_opts(CLI_OPTS)
conf.register_opts(EPISODE_OPTS)
conf.register_opts(FORMAT_OPTS)
conf.register_opts(CACHE_OPTS, ) | Configure options within configuration library. |
380,992 | def run_star(job, fastqs, univ_options, star_options):
assert star_options[] in (, )
job.fileStore.logToMaster( %univ_options[])
work_dir = job.fileStore.getLocalTempDir()
input_files = {
: fastqs[],
: fastqs[],
: star_options[]}
input_files = get_files_from_filestore(jo... | This module uses STAR to align the RNA fastqs to the reference
ARGUMENTS
1. fastqs: REFER RETURN VALUE of run_cutadapt()
2. univ_options: Dict of universal arguments used by almost all tools
univ_options
+- 'dockerhub': <dockerhub to use>
3. star_options: Dict of parameters speci... |
380,993 | def log_message(self, msg, *args):
if args:
msg = msg % args
self.logger.info(msg) | Hook to log a message. |
380,994 | def relabel(self, qubits: Qubits) -> :
chan = copy(self)
chan.vec = chan.vec.relabel(qubits)
return chan | Return a copy of this channel with new qubits |
380,995 | def get(self, name):
ws_list = self.list()
return ws_list[name] if name in ws_list else None | Get workspace infos from name.
Return None if workspace doesn't exists. |
380,996 | def update(self):
for linenum in reversed(sorted(self.updates)):
self.replace_baseline_repr(linenum, self.updates[linenum])
if not self.TEST_MODE:
path = .format(*os.path.splitext(self.path))
with io.open(path, , encoding=) as fh:
fh.write(.j... | Replace baseline representations previously registered for update. |
380,997 | def set_group_anonymous(self, *, group_id, enable=True):
return super().__getattr__() \
(group_id=group_id, enable=enable) | 群组匿名
------------
:param int group_id: 群号
:param bool enable: 是否允许匿名聊天
:return: None
:rtype: None |
380,998 | def get_relationship_info(tree, media, image_sizes):
if tree is None:
return {}
result = {}
for el in tree.iter():
el_id = el.get()
if el_id is None:
continue
target = el.get()
if any(
target.lower().endswith(ext) for
... | There is a separate file holds the targets to links as well as the targets
for images. Return a dictionary based on the relationship id and the
target. |
380,999 | def _parse_name(self, name):
if name is None:
self.ifo = None
self.tag = None
self.version = None
elif re_IFO_TAG_VERSION.match(name):
match = re_IFO_TAG_VERSION.match(name).groupdict()
self.ifo = match[]
self.tag = match[]... | Internal method to parse a `string` name into constituent
`ifo, `name` and `version` components.
Parameters
----------
name : `str`, `None`
the full name of a `DataQualityFlag` to parse, e.g.
``'H1:DMT-SCIENCE:1'``, or `None` to set all components
to ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.