Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
358,600 | def insert(self, database, key, value, callback=None):
token = self._get_token()
self._enqueue(self._PendingItem(token, BlobCommand(token=token, database=database,
content=InsertCommand(key=key.bytes, value=value)),
... | Insert an item into the given database.
:param database: The database into which to insert the value.
:type database: .BlobDatabaseID
:param key: The key to insert.
:type key: uuid.UUID
:param value: The value to insert.
:type value: bytes
:param callback: A call... |
358,601 | def _check_build_input(self, image, args_path):
try:
with open(os.path.join(args_path, BUILD_JSON)) as json_args:
logger.debug("build input: image = , args = ", image, json_args.read())
except (IOError, OSError) as ex:
logger.error("unable to open json ar... | Internal method, validate provided args.
:param image: str
:param args_path: str, path dir which is mounter inside container
:return: None
:raises RuntimeError |
358,602 | def set_fill_color(self,r,g=-1,b=-1):
"Set color for all filling operations"
if((r==0 and g==0 and b==0) or g==-1):
self.fill_color=sprintf(,r/255.0)
else:
self.fill_color=sprintf(,r/255.0,g/255.0,b/255.0)
self.color_flag=(self.fill_color!=self.text_color)
... | Set color for all filling operations |
358,603 | def commit(self, sourcedir, targetdir, abs_config, abs_sourcedir,
abs_targetdir):
config_path, config_filename = os.path.split(abs_config)
if not os.path.exists(config_path):
os.makedirs(config_path)
if not os.path.exists(abs_sourcedir):
os.makedi... | Commit project structure and configuration file
Args:
sourcedir (string): Source directory path.
targetdir (string): Compiled files target directory path.
abs_config (string): Configuration file absolute path.
abs_sourcedir (string): ``sourcedir`` expanded as abs... |
358,604 | def cred_def_id(issuer_did: str, schema_seq_no: int) -> str:
return .format(issuer_did, schema_seq_no, CD_ID_TAG) | Return credential definition identifier for input issuer DID and schema sequence number.
:param issuer_did: DID of credential definition issuer
:param schema_seq_no: schema sequence number
:return: credential definition identifier |
358,605 | def clean_cache(cached, **kwargs):
" Generate cache key and clean cached value. "
if isinstance(cached, basestring):
cached = _str_to_model(cached)
cache_key = generate_cache_key(cached, **kwargs)
cache.delete(cache_key) | Generate cache key and clean cached value. |
358,606 | def nEx(mt, x, n):
return mt.Dx[x + n] / mt.Dx[x] | nEx : Returns the EPV of a pure endowment (deferred capital).
Pure endowment benefits are conditional on the survival of the policyholder. (v^n * npx) |
358,607 | def list_image(root, recursive, exts):
i = 0
if recursive:
cat = {}
for path, dirs, files in os.walk(root, followlinks=True):
dirs.sort()
files.sort()
for fname in files:
fpath = os.path.join(path, fname)
suffix = os.path.... | Traverses the root of directory that contains images and
generates image list iterator.
Parameters
----------
root: string
recursive: bool
exts: string
Returns
-------
image iterator that contains all the image under the specified path |
358,608 | def _validate(instance):
try:
_ = instance.schema.validate(instance.to_dict())
except ValidationError as ex:
raise ModelValidationError(
ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs) | Validate the internal representation of the instance. |
358,609 | def preview(ident):
source = get_source(ident)
cls = backends.get(current_app, source.backend)
max_items = current_app.config[]
backend = cls(source, dryrun=True, max_items=max_items)
return backend.harvest() | Preview an harvesting for a given source |
358,610 | def current_custom_claims():
jwt_data = get_jwt_data_from_app_context()
return {k: v for (k, v) in jwt_data.items() if k not in RESERVED_CLAIMS} | This method returns any custom claims in the current jwt |
358,611 | def clear_attendance(self):
command = const.CMD_CLEAR_ATTLOG
cmd_response = self.__send_command(command)
if cmd_response.get():
return True
else:
raise ZKErrorResponse("Can't clear response") | clear all attendance record
:return: bool |
358,612 | def S(self):
"English ordinal suffix for the day of the month, 2 characters; i.e. , , or "
if self.data.day in (11, 12, 13):
return u
last = self.data.day % 10
if last == 1:
return u
if last == 2:
return u
if last == 3:
return u
return u | English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th |
358,613 | def s3_connection(self):
if not hasattr(self, ):
self.check_prerequisites()
with PatchedBotoConfig():
import boto
from boto.exception import BotoClientError, BotoServerError, NoAuthHandlerFound
from boto.s3.connection import S3Conn... | Connect to the Amazon S3 API.
If the connection attempt fails because Boto can't find credentials the
attempt is retried once with an anonymous connection.
Called on demand by :attr:`s3_bucket`.
:returns: A :class:`boto.s3.connection.S3Connection` object.
:raises: :exc:`.Cache... |
358,614 | def _sigma_pi_hiE(self, Tp, a):
m_p = self._m_p
csip = (Tp - 3.0) / m_p
m1 = a[0] * csip ** a[3] * (1 + np.exp(-a[1] * csip ** a[4]))
m2 = 1 - np.exp(-a[2] * csip ** 0.25)
multip = m1 * m2
return self._sigma_inel(Tp) * multip | General expression for Tp > 5 GeV (Eq 7) |
358,615 | def _get_local_dirs(sub):
path = os.environ.get("SPARK_LOCAL_DIRS", "/tmp")
dirs = path.split(",")
if len(dirs) > 1:
rnd = random.Random(os.getpid() + id(dirs))
random.shuffle(dirs, rnd.random)
return [os.path.join(d, "python", str(os.getpid()), sub) for d in dirs] | Get all the directories |
358,616 | def process_file(path, processor, encoding=, mode=, *args, **kwargs):
s content. If the file name ends with .gz, read it as gzip file rUrtrbr'):
raise Exception("Invalid file reading mode")
with open(path, encoding=encoding, mode=mode, *args, **kwargs) as infile:
return processor(infile) | Process a text file's content. If the file name ends with .gz, read it as gzip file |
358,617 | def put(self, accountId):
self.reqparse.add_argument(, type=str, required=True)
self.reqparse.add_argument(, type=str, required=True)
self.reqparse.add_argument(, type=dict, required=True, action=)
self.reqparse.add_argument(, type=int, required=True, choices=(0, 1))
sel... | Update an account |
358,618 | def handle_user(self, data):
data[] = {
: ,
: False,
: False,
: False,
: tuple(),
}
if in settings.MIDDLEWARE_CLASSES:
user = self.request.user
data[][] = user.is_authenticated()
if... | Insert user informations in data
Override it to add extra user attributes. |
358,619 | def disable_cpu(self, rg):
if type(rg) == int:
rg= [rg]
to_disable= set(rg) & set(self.__get_ranges("online"))
for cpu in to_disable:
fpath = path.join("cpu%i"%cpu,"online")
self.__write_cpu_file(fpath, b"0") | Disable cpus
rg: range or list of threads to disable |
358,620 | def write_script(self, script_name, contents, mode="t", *ignored):
from setuptools.command.easy_install import chmod, current_umask
log.info("Installing %s script to %s", script_name, self.install_dir)
target = os.path.join(self.install_dir, script_name)
self.outfiles.append(tar... | Write an executable file to the scripts directory |
358,621 | def binary_annotation_list_builder(binary_annotations, host):
ann_type = zipkin_core.AnnotationType.STRING
return [
create_binary_annotation(key, str(value), ann_type, host)
for key, value in binary_annotations.items()
] | Reformat binary annotations dict to return list of zipkin_core objects. The
value of the binary annotations MUST be in string format.
:param binary_annotations: dict with key, value being the name and value
of the binary annotation being logged.
:type host: :class:`zipkin_cor... |
358,622 | def avi(self, path, filtered=True, override=False):
path = pathlib.Path(path)
ds = self.rtdc_ds
if path.suffix != ".avi":
path = path.with_name(path.name + ".avi")
if not override and path.exists():
raise OSError("File already exists: {}... | Exports filtered event images to an avi file
Parameters
----------
path: str
Path to a .tsv file. The ending .tsv is added automatically.
filtered: bool
If set to `True`, only the filtered data (index in ds._filter)
are used.
override: bool
... |
358,623 | def jsonise(dic):
d = {}
for k, v in dic.items():
if type(v) in abstractRequetesSQL.TYPES_PERMIS:
d[k] = v
else:
try:
d[k] = json.dumps(v, ensure_ascii=False, cls=formats.JsonEncoder)
except ValueError a... | Renvoie un dictionnaire dont les champs dont compatibles avec SQL
Utilise Json. Attention à None : il faut laisser None et non pas null |
358,624 | def install(path, restart=False):
*
cmd = [, path, ]
if restart:
cmd.append()
else:
cmd.append()
ret_code = __salt__[](cmd, ignore_retcode=True)
file_name = os.path.basename(path)
errors = {2359302: .format(file_name),
87: }
if ret_code in e... | Install a KB from a .msu file.
Args:
path (str):
The full path to the msu file to install
restart (bool):
``True`` to force a restart if required by the installation. Adds
the ``/forcerestart`` switch to the ``wusa.exe`` command. ``False``
will add ... |
358,625 | def consume_file(self, filename):
with screed.open(filename) as sequences:
for seq in sequences:
self.consume(seq[]) | Counts all kmers in all sequences in a FASTA/FASTQ file. |
358,626 | def and_(*fs):
ensure_argcount(fs, min_=1)
fs = list(imap(ensure_callable, fs))
if len(fs) == 1:
return fs[0]
if len(fs) == 2:
f1, f2 = fs
return lambda *args, **kwargs: (
f1(*args, **kwargs) and f2(*args, **kwargs))
if len(fs) == 3:
f1, f2, f3 = fs
... | Creates a function that returns true for given arguments
iff every given function evalutes to true for those arguments.
:param fs: Functions to combine
:return: Short-circuiting function performing logical conjunction
on results of ``fs`` applied to its arguments |
358,627 | def get_suggested_filename(metadata):
if metadata.get() and metadata.get():
suggested_filename = .format(**metadata)
elif metadata.get() and metadata.get():
suggested_filename = .format(**metadata)
elif metadata.get() and metadata.get():
suggested_filename = .format(**metadata)
else:
suggested_filename =... | Generate a filename for a song based on metadata.
Parameters:
metadata (dict): A metadata dict.
Returns:
A filename. |
358,628 | def to_dict(self, split_structs_bit=False):
pref_dict = {}
struct_dict = {}
for (key, val) in six.iteritems(self):
if split_structs_bit and isinstance(val, Pref):
struct_dict[key] = val
continue
pref_dict[key] = val
if spli... | Converts prefeters to a dictionary.
Children Pref can be optionally separated |
358,629 | def py_doc_trim(docstring):
if not docstring:
return
lines = docstring.expandtabs().splitlines()
return newline_substitution_regex.sub(" ", joined) | Trim a python doc string.
This example is nipped from https://www.python.org/dev/peps/pep-0257/,
which describes how to conventionally format and trim docstrings.
It has been modified to replace single newlines with a space, but leave
multiple consecutive newlines in tact. |
358,630 | def remove_role(self, groups=None, role_type=RoleTypes.admin):
if not groups:
raise ArgumentError("You must specify groups from which to remove the role for this user")
if role_type in RoleTypes.__members__:
role_type = RoleTypes[role_type]
if role_type not in Ro... | Remove user from a role (typically admin) of some groups.
:param groups: list of group names the user should NOT have this role for
:param role_type: the type of role (defaults to "admin")
:return: the User, so you can do User(...).remove_role(...).remove_from_groups(...) |
358,631 | def exists(self):
try:
self._client.instance_admin_client.get_instance(name=self.name)
return True
except NotFound:
return False | Check whether the instance already exists.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_check_instance_exists]
:end-before: [END bigtable_check_instance_exists]
:rtype: bool
:returns: True if the table exists, else False. |
358,632 | def _destroy(self, target_position_groups):
target_position_groups = list(target_position_groups)
destroyed_tile_groups = list()
blank = Tile.singleton()
a = self._array
while target_position_groups:
clear_after_storing = list()
... | Destroy indicated position groups, handle any chain destructions,
and return all destroyed groups. |
358,633 | def frames_to_ms(frames, fps):
if fps <= 0:
raise ValueError("Framerate must be positive number (%f)." % fps)
return int(round(frames * (1000 / fps))) | Convert frame-based duration to milliseconds.
Arguments:
frames: Number of frames (should be int).
fps: Framerate (must be a positive number, eg. 23.976).
Returns:
Number of milliseconds (rounded to int).
Raises:
ValueError: fps was negative or zero. |
358,634 | def id2rel(self, xs):
if isinstance(xs, list):
return [self._id2rel[x] for x in xs]
return self._id2rel[xs] | Map id(s) to relation(s)
Parameters
----------
xs : int
id or a list of ids
Returns
-------
str or list
relation or a list of relations |
358,635 | def _start_retransmission(self, transaction, message):
with transaction:
if message.type == defines.Types[]:
future_time = random.uniform(defines.ACK_TIMEOUT, (defines.ACK_TIMEOUT * defines.ACK_RANDOM_FACTOR))
transaction.retransmit_stop = threading.Event()
... | Start the retransmission task.
:type transaction: Transaction
:param transaction: the transaction that owns the message that needs retransmission
:type message: Message
:param message: the message that needs the retransmission task |
358,636 | def _next_of_kin(self, pos):
candidate = None
parent = self.parent_position(pos)
if parent is not None:
candidate = self.next_sibling_position(parent)
if candidate is None:
candidate = self._next_of_kin(parent)
return candidate | looks up the next sibling of the closest ancestor with not-None next
siblings. |
358,637 | def from_mask_and_sub_grid_size(cls, mask, sub_grid_size=1):
sub_grid_masked = grid_util.sub_grid_1d_masked_from_mask_pixel_scales_and_sub_grid_size(
mask=mask,
pixel_scales=mask.pixel_scales,
sub_grid_size=sub_grid_size)
return SubGrid(sub_grid_masked, mask,... | Setup a sub-grid of the unmasked pixels, using a mask and a specified sub-grid size. The center of \
every unmasked pixel's sub-pixels give the grid's (y,x) arc-second coordinates.
Parameters
-----------
mask : Mask
The mask whose masked pixels are used to setup the sub-pixe... |
358,638 | def download(self, url):
try:
yt = YouTube(url)
except RegexMatchError:
log.error(f"Cannot download file at {url}")
else:
stream = yt.streams.first()
log.info(f"Download for {stream.default_filename} has started")
start_time =... | Downloads a MP4 or WebM file that is associated with the video at the URL passed.
:param str url: URL of the video to be downloaded
:return str: Filename of the file in local storage |
358,639 | def fix_e225(self, result):
target = self.source[result[] - 1]
offset = result[] - 1
fixed = target[:offset] + + target[offset:]
else:
return [] | Fix missing whitespace around operator. |
358,640 | def extend(ol,nl,**kwargs):
if( in kwargs):
mode = kwargs["mode"]
else:
mode = "new"
if(mode == "new"):
new = copy.deepcopy(ol)
cpnl = copy.deepcopy(nl)
new.extend(cpnl)
return(new)
else:
ol.extend(nl)
return(ol) | from elist.elist import *
ol = [1,2,3,4]
nl = [5,6,7,8]
id(ol)
extend(ol,nl,mode="original")
ol
id(ol)
####
ol = [1,2,3,4]
nl = [5,6,7,8]
id(ol)
new = extend(ol,nl)
new
id(new) |
358,641 | def get(self, session, discount_id=None, ext_fields=None):
request = TOPRequest()
if discount_id!=None: request[] = discount_id
if ext_fields!=None: request[] = ext_fields
self.create(self.execute(request, session))
return self.discounts | taobao.fenxiao.discounts.get 获取折扣信息
查询折扣信息 |
358,642 | def get_maximum_range(self, hmm):
length=int([x for x in open(hmm) if x.startswith("LENG")][0].split()[1])
max_length=round(length*1.5, 0)
return max_length | If no maximum range has been specified, and if using a hmm search, a
maximum range can be determined by using the length of the HMM
Parameters
----------
hmm : str
path to hmm profile
Returns
-------
Length to search to when linking hits on a single ... |
358,643 | def _write_line(self, indent_string, entry, this_entry, comment):
if not self.unrepr:
val = self._decode_element(self._quote(this_entry))
else:
val = repr(this_entry)
return % (indent_string,
self._decode_element(self._quo... | Write an individual line, for the write method |
358,644 | def main(doc, tool, dispatch_only=None):
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
try:
arguments = docopt(doc, sys.argv[1:])
command = get_command(arguments)
verbose = arguments.pop(, False)
... | gcdt tools parametrized main function to initiate gcdt lifecycle.
:param doc: docopt string
:param tool: gcdt tool (gcdt, kumo, tenkai, ramuda, yugen)
:param dispatch_only: list of commands which do not use gcdt lifecycle
:return: exit_code |
358,645 | def differentiate(self, n=1):
ak = self.coefficients()
a_, b_ = self.domain()
for _ in range(n):
ak = self.differentiator(ak)
return self.from_coeff((2./(b_-a_))**n*ak, domain=self.domain()) | n-th derivative, default 1. |
358,646 | def user_registries(fs0, fs1):
for user in fs0.ls(.format(fs0.fsroot)):
for path in user_registries_path(fs0.fsroot, user):
if fs1.exists(path):
yield path | Returns the list of user registries present on both FileSystems. |
358,647 | def _transform_chrom(chrom):
try:
c = int(chrom)
except:
if chrom in [, ]:
return chrom
elif chrom == :
return
else:
return + chrom
else:
return % c | Helper function to obtain specific sort order. |
358,648 | def _notify_change(self):
def inner_action(*args):
Cache().set_cursor_position(
self.editor.file.path,
self.editor.textCursor().position())
if os.path.exists(self.editor.file.path):
... | Notify user from external change if autoReloadChangedFiles is False
then reload the changed file in the editor |
358,649 | def runQuery(self, *args, **kwargs):
try:
return self._connectionPool.runQuery(*args, **kwargs)
except:
d = defer.Deferred()
d.errback()
return d | Execute an SQL query and return the result.
:param args: additional positional arguments to be passed to cursor execute method
:param kwargs: keyword arguments to be passed to cursor execute method
:return: <defer> |
358,650 | def summary(self):
ci = 1 - self.alpha
with np.errstate(invalid="ignore", divide="ignore"):
df = pd.DataFrame(index=self.hazards_.index)
df["coef"] = self.hazards_
df["exp(coef)"] = np.exp(self.hazards_)
df["se(coef)"] = self.standard_errors_
... | Summary statistics describing the fit.
Set alpha property in the object before calling.
Returns
-------
df : DataFrame
Contains columns coef, np.exp(coef), se(coef), z, p, lower, upper |
358,651 | def inverse(self):
r
A, _ = self.estimate_frame_bounds()
if A == 0:
_logger.warning(
)
def kernel(g, i, x):
y = g.evaluate(x).T
z = np.linalg.pinv(np.expand_dims(y, axis=-1)).squeeze(axis=-2)
return z[:, i]
... | r"""Return the pseudo-inverse filter bank.
The pseudo-inverse of the *analysis filter bank* :math:`g` is the
*synthesis filter bank* :math:`g^+` such that
.. math:: g(L)^+ g(L) = I,
where :math:`I` is the identity matrix, and the *synthesis operator*
.. math:: g(L)^+ = (g(L)\... |
358,652 | def register(self, src, trg, trg_mask=None, src_mask=None):
warp_mode = cv2.MOTION_EUCLIDEAN
termination_eps = 1e-10
criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT,
self.params[], termination_eps)
warp... | Implementation of pair-wise registration and warping using Enhanced Correlation Coefficient
This function estimates an Euclidean transformation (x,y translation + rotation) using the intensities of the
pair of images to be registered. The similarity metric is a modification of the cross-correlation met... |
358,653 | def transitions(self, current=True):
if current and isinstance(self.obj, RoleMixin):
proxy = self.obj.current_access()
else:
proxy = {}
current = False
return OrderedDict((name, transition) for name, transition in
((name, ge... | Returns available transitions for the current state, as a dictionary of
name: :class:`StateTransitionWrapper`.
:param bool current: Limit to transitions available in ``obj.``
:meth:`~coaster.sqlalchemy.mixins.RoleMixin.current_access` |
358,654 | def addRNAQuantification(self, datafields):
self._rnaValueList.append(datafields)
if len(self._rnaValueList) >= self._batchSize:
self.batchaddRNAQuantification() | Adds an RNAQuantification to the db. Datafields is a tuple in the
order:
id, feature_set_ids, description, name,
read_group_ids, programs, biosample_id |
358,655 | def request(self, endpoint, method=, params=None, version=, json_encoded=False):
if endpoint.startswith():
raise TwythonError()
if endpoint.startswith():
url = endpoint
else:
url = % (self.api_url % version, endpoint)
con... | Return dict of response received from Twitter's API
:param endpoint: (required) Full url or Twitter API endpoint
(e.g. search/tweets)
:type endpoint: string
:param method: (optional) Method of accessing data, either
GET, POST or DELETE. (default G... |
358,656 | def clean(self, *args, **kwargs):
self._validate_backend()
self._validate_config()
self._validate_netengine()
self._validate_duplicates() | validation |
358,657 | def check_required_fields(method, uri, body, field_names):
if body is None:
raise BadRequestError(method, uri, reason=3,
message="Missing request body")
for field_name in field_names:
if field_name not in body:
raise BadRequestError(meth... | Check required fields in the request body.
Raises:
BadRequestError with reason 3: Missing request body
BadRequestError with reason 5: Missing required field in request body |
358,658 | def get_pepproteins(line):
psm_id = get_psm_id(line)
proteins = get_proteins_from_psm(line)
return psm_id, proteins | Returns from a PSM line peptide sequence,
and other information about the PSM.
Return values:
psm_id - str
proteins - list of str |
358,659 | def _interp_total_size(interp):
load_segs = [x for x in interp.iter_segments() if x.header.p_type == ]
last = load_segs[-1]
return last.header.p_vaddr + last.header.p_memsz | Compute total load size of interpreter.
:param ELFFile interp: interpreter ELF .so
:return: total load size of interpreter, not aligned
:rtype: int |
358,660 | def _PPIGuessPayloadClass(p, **kargs):
if len(p) >= 4:
t,pfh_len = struct.unpack("<HH", p[:4])
cls = getPPIType(t, "default")
pfh_len += 4
out = cls(p[:pfh_len], **kargs)
if (out.payload):
out.payload = conf.raw_layer(out.payload.loa... | This function tells the PacketListField how it should extract the
TLVs from the payload. We pass cls only the length string
pfh_len says it needs. If a payload is returned, that means
part of the sting was unused. This converts to a Raw layer, and
the remainder of p is added as Ra... |
358,661 | def browse(self, wait=True, tempname="/tmp/seltable"):
import os
if os.system() == 0:
waitstr1 = ""
waitstr2 = "foreground ..."
if not wait:
waitstr1 = " &"
waitstr2 = "background ..."
if ... | Browse a table using casabrowser or a simple wxwidget
based browser.
By default the casabrowser is used if it can be found (in your PATH).
Otherwise the wxwidget one is used if wx can be loaded.
The casabrowser can only browse tables that are persistent on disk.
This gives prob... |
358,662 | def clear_caches(self):
for element_name in dir(self.components):
element = getattr(self.components, element_name)
if hasattr(element, ):
delattr(element, ) | Clears the Caches for all model elements |
358,663 | def validate_signature_fragments(
fragments,
hash_,
public_key,
sponge_type=Kerl,
):
checksum = [0] * (HASH_LENGTH * len(fragments))
normalized_hash = normalize(hash_)
for i, fragment in enumerate(fragments):
outer_sponge = sponge_type()
... | Returns whether a sequence of signature fragments is valid.
:param fragments:
Sequence of signature fragments (usually
:py:class:`iota.transaction.Fragment` instances).
:param hash_:
Hash used to generate the signature fragments (usually a
:py:class:`iota.transaction.BundleHash` instan... |
358,664 | def setCurrentAction(self, action):
self._actionGroup.blockSignals(True)
for act in self._actionGroup.actions():
act.setChecked(act == action or act.text() == action)
self._actionGroup.blockSignals(False) | Sets the current action for this button to the inputed action.
:param action | <QAction> || <str> |
358,665 | def match_handle(loc, tokens):
if len(tokens) == 4:
matches, match_type, item, stmts = tokens
cond = None
elif len(tokens) == 5:
matches, match_type, item, cond, stmts = tokens
else:
raise CoconutInternalException("invalid match statement tokens", tokens)
if match_t... | Process match blocks. |
358,666 | def show(config_file=False):
*
ret = {}
if config_file:
ret[comps[0]] = comps[1]
return ret | Return a list of sysctl parameters for this minion
config: Pull the data from the system configuration file
instead of the live data.
CLI Example:
.. code-block:: bash
salt '*' sysctl.show |
358,667 | def insert_unique(self, table_name, data, unique_fields=None, *, raise_if_found=False):
return insert_unique(table=self.table(table_name),
data=_to_string(data),
unique_fields=unique_fields,
raise_if_found=raise_if_f... | Insert `data` into `table` ensuring that data has unique values
in `table` for the fields listed in `unique_fields`.
If `raise_if_found` is True, will raise an NotUniqueItemError if
another item with the same `unique_fields` values are found
previously in `table`.
If False, will... |
358,668 | def filterResults(results, filter):
return [exp for exp in results if any(map(lambda v: v in exp, filter))] | Filter results containing the given condition
:param results: list of experiments returned by `suite.get_exps`
:param filter: list of conditions on the experiment parameters. For example:
["dropout0.0", "dropout0.50"]
:return: filtered results |
358,669 | def get_build_params(metadata):
keyrepo_urlvaluekeyrepo_idvaluekeycredentialvaluekeyresponse_urlvaluekeytokenvaluekeycommitvalue
params = dict()
for item in metadata:
if item[] == None:
response = get_build_metadata(key=item[])
item[] = response
params[item[]] = item[... | get_build_params uses get_build_metadata to retrieve corresponding meta data values for a build
:param metadata: a list, each item a dictionary of metadata, in format:
metadata = [{'key': 'repo_url', 'value': repo_url },
{'key': 'repo_id', 'value': repo_id },
{'key': 'credential'... |
358,670 | def from_scene_coords(self, x=0, y=0):
matrix = self.get_matrix()
matrix.invert()
return matrix.transform_point(x, y) | Converts x, y given in the scene coordinates to sprite's local ones
coordinates |
358,671 | def get_same_container_repos(app_or_library_name):
specs = get_expanded_libs_specs()
spec = specs.get_app_or_lib(app_or_library_name)
return get_same_container_repos_from_spec(spec) | Given the name of an app or library, returns all repos that are guaranteed
to live in the same container |
358,672 | def make_postcard(self, npix=300, shape=(1070, 1132), buffer_size=15):
source = self.kic
client = kplr.API()
targ = client.target(source)
channel = [targ.params[], targ.params[],
targ.params[], targ.params[]]
col = [targ.params[], ... | Develop a "postcard" region around the target star.
Other stars in this postcard will be used as possible reference stars.
Args:
npix: The size of the postcard region. The region will be a square with sides npix pixels
(default: ``300``)
shape: The size ... |
358,673 | def universal_transformer_basic(layer_inputs,
step, hparams,
ffn_unit,
attention_unit):
state, inputs, memory = tf.unstack(layer_inputs, num=None, axis=0,
name="unstack")
new_state... | Basic Universal Transformer.
This model is pretty similar to the vanilla transformer in which weights are
shared between layers. For some tasks, this simple idea brings a
generalization that is not achievable by playing with the size of the model
or drop_out parameters in the vanilla transformer.
Args:
... |
358,674 | def mask_by_ind(self, inds):
new_data = np.zeros(self.shape)
for ind in inds:
new_data[ind[0], ind[1]] = self.data[ind[0], ind[1]]
return type(self)(new_data.astype(self.data.dtype), self.frame) | Create a new image by zeroing out data at locations not in the
given indices.
Parameters
----------
inds : :obj:`numpy.ndarray` of int
A 2D ndarray whose first entry is the list of row indices
and whose second entry is the list of column indices.
The ... |
358,675 | def parse_columns(lines):
data = []
index = []
for line in lines:
line = line.rstrip()
if line.startswith("
tmp = __parse_entry(line)
data.append(tmp[1])
index.append(tmp[0])
return DataFrame(data, index=index, columns=[]) | Parse list of lines with columns description from SOFT file.
Args:
lines (:obj:`Iterable`): Iterator over the lines.
Returns:
:obj:`pandas.DataFrame`: Columns description. |
358,676 | def _get_customjs(self, change, p_name):
data_template = "data = {{p_name: , value: cb_obj[]}};"
fetch_data = data_template.format(change=change, p_name=p_name)
self_callback = JS_CALLBACK.format(comm_id=self.comm.id,
timeout=self.timeout,
... | Returns a CustomJS callback that can be attached to send the
widget state across the notebook comms. |
358,677 | def convert_videos_to_summaries(input_videos, output_videos, target_videos,
tag, decode_hparams,
display_ground_truth=False):
fps = decode_hparams.frames_per_second
border_percent = decode_hparams.border_percent
max_outputs = decode_hparams.max_di... | Converts input, output and target videos into video summaries.
Args:
input_videos: 5-D NumPy array, (NTHWC) conditioning frames.
output_videos: 5-D NumPy array, (NTHWC) model predictions.
target_videos: 5-D NumPy array, (NTHWC) target frames.
tag: tf summary tag.
decode_hparams: HParams.
disp... |
358,678 | def take_until(condition):
f = partial(takewhile, pipe | condition | operator.not_)
f.attrs = {: take_until_including(condition)}
return f | >>> [1, 4, 6, 4, 1] > take_until(X > 5) | list
[1, 4]
>>> [1, 4, 6, 4, 1] > take_until(X > 5).including | list
[1, 4, 6] |
358,679 | def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
subparsers = parser.add_subparsers(dest=)
subparsers.add_parser(,
help=)
subparsers.add_parser(,
help=)
subparsers.add_... | GATK germline pipeline with variant filtering and annotation. |
358,680 | def _get_mid_and_update_msg(self, msg, use_mid):
if use_mid is None:
use_mid = self._server_supports_ids
if msg.mid is None:
mid = self._next_id()
if use_mid:
msg.mid = mid
return mid
else:
... | Get message ID for current request and assign to msg.mid if needed.
Parameters
----------
msg : katcp.Message ?request message
use_mid : bool or None
If msg.mid is None, a new message ID will be created. msg.mid will be
filled with this ID if use_mid is True or if use_m... |
358,681 | def std(data, channels=None):
if channels is None:
data_stats = data
else:
data_stats = data[:, channels]
return np.std(data_stats, axis=0) | Calculate the standard deviation of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, optiona... |
358,682 | def parameter_struct_dict(self):
if self._parameter_struct_dict is None:
self._parameter_struct_dict = self._make_ff_params_dict()
elif self.auto_update_f_params:
new_hash = hash(
tuple([tuple(item)
for sublist in self.values()
... | Dictionary containing PyAtomData structs for the force field. |
358,683 | def resultsFor( self, ps ):
k = self._parametersAsIndex(ps)
if k in self._results.keys():
return [ res for res in self._results[k] if isinstance(res, dict) ]
else:
return [] | Retrieve a list of all results associated with the given parameters.
:param ps: the parameters
:returns: a list of results, which may be empty |
358,684 | def query(self, variables, evidence=None, elimination_order=None, joint=True):
return self._variable_elimination(variables, ,
evidence=evidence, elimination_order=elimination_order,
joint=joint) | Parameters
----------
variables: list
list of variables for which you want to compute the probability
evidence: dict
a dict key, value pair as {var: state_of_var_observed}
None if no evidence
elimination_order: list
order of variable elim... |
358,685 | def run(self,
job_name,
handler_spec,
input_reader_spec,
output_writer_spec=None,
params=None,
shards=None,
base_path=None):
if shards is None:
shards = parameters.config.SHARD_COUNT
if base_path is None:
base_path = paramete... | Start a mapreduce job.
Args:
job_name: mapreduce name. Only for display purpose.
handler_spec: fully qualified name to your map function/class.
input_reader_spec: fully qualified name to input reader class.
output_writer_spec: fully qualified name to output writer class.
params: a dic... |
358,686 | def getProfileInfo(exp):
totalTime = 0.000001
for region in exp.network.regions.values():
timer = region.getComputeTimer()
totalTime += timer.getElapsed()
regionNames = list(exp.network.regions.keys())
regionNames.sort()
count = 1
profileInfo = []
L2Time = 0.0
L4Time = 0.0
for regionN... | Prints profiling information.
Parameters:
----------------------------
@param reset (bool)
If set to True, the profiling will be reset. |
358,687 | def main(args=[], prog_name=sys.argv[0]):
helpStr = "Build indexes and use them to extract elements from \n" +\
"indexed files on-demand. \n" +\
" \n" +\
"----------------------... | Figure out which of the two options was used (build, get) and dispatch.
:param args: the arguments for this script, as a list of string. Should
already have had the script name stripped, so we expect the
first item in this list to specify the mode ('build' an
... |
358,688 | def cbpdnmd_ystep(k):
if mp_W.shape[0] > 1:
W = mp_W[k]
else:
W = mp_W
AXU0 = mp_DX[k] - mp_S[k] + mp_Z_U0[k]
AXU1 = mp_Z_X[k] + mp_Z_U1[k]
mp_Z_Y0[k] = mp_xrho*AXU0 / (W**2 + mp_xrho)
mp_Z_Y1[k] = sp.prox_l1(AXU1, (mp_lmbda/mp_xrho)) | Do the Y step of the cbpdn stage. The only parameter is the slice
index `k` and there are no return values; all inputs and outputs are
from and to global variables. |
358,689 | def euclidean(a, b):
a = np.asanyarray(a, dtype=np.float64)
b = np.asanyarray(b, dtype=np.float64)
return np.sqrt(((a - b) ** 2).sum()) | Euclidean distance between vectors a and b.
Parameters
------------
a : (n,) float
First vector
b : (n,) float
Second vector
Returns
------------
distance : float
Euclidean distance between A and B |
358,690 | def make_links(self):
for dep in self.deps:
filepaths, exts = dep.get_filepaths_and_exts()
for path, ext in zip(filepaths, exts):
logger.info("Need path %s with ext %s" % (path, ext))
dest = self.ipath_from_ext(ext)
if not os.pat... | Create symbolic links to the output files produced by the other tasks.
.. warning::
This method should be called only when the calculation is READY because
it uses a heuristic approach to find the file to link. |
358,691 | def _merge_before_set(self, key, existing, value, is_secret):
def _log_before_merging(_value):
self.logger.debug(
"Merging existing %s: %s with new: %s", key, existing, _value
)
def _log_after_merge(_value):
self.logger.debug("%s merged to %... | Merge the new value being set with the existing value before set |
358,692 | def from_dict(d):
warnings_ = d.get(, [])
query = d.get() or None
if query:
query = Person.from_dict(query)
person = d.get() or None
if person:
person = Person.from_dict(person)
records = d.get()
if records:
... | Transform the dict to a response object and return the response. |
358,693 | def show_buff(self, pos):
buff = self.get_name() + " "
buff += "%x:" % self.first_key
for i in self.targets:
buff += " %x" % i
return buff | Return the display of the instruction
:rtype: string |
358,694 | def dynamic_instantiate_middleware(name, args, expand=None):
def _expand(v):
if expand and compat.is_basestring(v) and v.lower() in expand:
return expand[v]
return v
try:
the_class = dynamic_import_class(name)
inst = None
if type(args) in (tupl... | Import a class and instantiate with custom args.
Example:
name = "my.module.Foo"
args_dict = {
"bar": 42,
"baz": "qux"
}
=>
from my.module import Foo
return Foo(bar=42, baz="qux") |
358,695 | def _checkIfDatabaseIsEmpty(self, successHandler=None, failHandler=None):
def failCallback(error):
errorMessage = str(error)
if isinstance(error, Failure):
errorMessage = error.getErrorMessage()
if failHandler is not None:
reactor.cal... | Check if database contains any tables.
:param successHandler: <function(<bool>)> method called if interrogation was successful where the first argument
is a boolean flag specifying if the database is empty or not
:param failHandler: <function(<str>)> method called if int... |
358,696 | def needed(name, required):
return [
relative_field(r, name) if r and startswith_field(r, name) else None
for r in required
] | RETURN SUBSET IF name IN REQUIRED |
358,697 | def status(self, core=None):
params = {
: ,
}
if core is not None:
params.update(core=core)
return self._get_url(self.url, params=params) | http://wiki.apache.org/solr/CoreAdmin#head-9be76f5a459882c5c093a7a1456e98bea7723953 |
358,698 | def copytree(self, dest_dir, src=None, newname=None,
exclude=None, overwrite=False):
def copy_object(obj, dest, name=None):
if name is None:
name = obj.GetName()
if not overwrite and name in dest:
raise ValueError(
... | Copy this directory or just one contained object into another
directory.
Parameters
----------
dest_dir : string or Directory
The destination directory.
src : string, optional (default=None)
If ``src`` is None then this entire directory is copied recurs... |
358,699 | def __get_values(self):
values = []
if self.__remote:
description = self.__client.describe(self.__point)
if description is not None:
if description[] != :
raise IOTUnknown( % self.__point)
values = description[][]
... | Retrieve value information either via describe or point value listing. MUST be called within lock. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.