Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
348,900 | def dropout_pred(model, ref, ref_rc, alt, alt_rc, mutation_positions, out_annotation_all_outputs,
output_filter_mask=None, out_annotation=None, dropout_iterations=30):
prefix = "do"
seqs = {"ref": ref, "ref_rc": ref_rc, "alt": alt, "alt_rc": alt_rc}
assert np.all([np.array(get_seq_le... | Dropout-based variant effect prediction
This method is based on the ideas in [Gal et al.](https://arxiv.org/pdf/1506.02142.pdf) where dropout
layers are also actived in the model prediction phase in order to estimate model uncertainty. The
advantage of this method is that instead of a point est... |
348,901 | def write(self, address, size, value):
for i in range(0, size):
self.__write_byte(address + i, (value >> (i * 8)) & 0xff) | Write arbitrary size content to memory. |
348,902 | def compute_lsrk(self):
ra = Angle(self.header[b], unit=)
dec = Angle(self.header[b], unit=)
mjdd = self.header[b]
rarad = ra.to().value
dcrad = dec.to().value
last = self.compute_lst()
tellat = np.deg2rad(self.coords[0])
tellong = np.deg2rad(sel... | Computes the LSR in km/s
uses the MJD, RA and DEC of observation to compute
along with the telescope location. Requires pyslalib |
348,903 | def latents_to_frames(z_top_interp, level_eps_interp, hparams):
images, _, _, _ = glow_ops.encoder_decoder(
"codec", z_top_interp, hparams, eps=level_eps_interp, reverse=True)
images = glow_ops.postprocess(images)
return images | Decodes latents to frames. |
348,904 | def service_search(auth=None, **kwargs):
***
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.search_services(**kwargs) | Search services
CLI Example:
.. code-block:: bash
salt '*' keystoneng.service_search
salt '*' keystoneng.service_search name=glance
salt '*' keystoneng.service_search name=135f0403f8e544dc9008c6739ecda860 |
348,905 | def render_trace(
self, trace_list=None, file=sys.stdout, render_cls=default_renderer(),
symbol_len=5, segment_size=5, segment_delim=, extra_line=True):
if _currently_in_ipython():
from IPython.display import display, HTML, Javascript
from .inputoutput... | Render the trace to a file using unicode and ASCII escape sequences.
:param trace_list: A list of signals to be output in the specified order.
:param file: The place to write output, default to stdout.
:param render_cls: A class that translates traces into output bytes.
:param symbol_le... |
348,906 | def make_factory(klass, **kwargs):
factory_name = % klass.__name__
class Meta:
model = klass
kwargs[] = Meta
base_class = kwargs.pop(, base.Factory)
factory_class = type(base.Factory).__new__(type(base.Factory), factory_name, (base_class,), kwargs)
factory_class.__name__ = % kl... | Create a new, simple factory for the given class. |
348,907 | def read_file_chunks(
file_path: str,
chunk_size: int = DEFAULT_CHUNK_SIZE
) -> bytes:
chunk_count = get_file_chunk_count(file_path, chunk_size)
if chunk_count < 1:
return
with open(file_path, mode=) as fp:
for chunk_index in range(chunk_count):
source = f... | Reads the specified file in chunks and returns a generator where
each returned chunk is a compressed base64 encoded string for sync
transmission
:param file_path:
The path to the file to read in chunks
:param chunk_size:
The size, in bytes, of each chunk. The final chunk will be less th... |
348,908 | def parse_footnotes(document, xmlcontent):
footnotes = etree.fromstring(xmlcontent)
document.footnotes = {}
for footnote in footnotes.xpath(, namespaces=NAMESPACES):
_type = footnote.attrib.get(_name(), None)
| Parse footnotes document.
Footnotes are defined in file 'footnotes.xml' |
348,909 | def add_value(
self, secret_resource_name, secret_value_resource_name, name, value=None, custom_headers=None, raw=False, **operation_config):
secret_value_resource_description = models.SecretValueResourceDescription(name=name, value=value)
url = self.add_value.metadata[]
... | Adds the specified value as a new version of the specified secret
resource.
Creates a new value of the specified secret resource. The name of the
value is typically the version identifier. Once created the value
cannot be changed.
:param secret_resource_name: The name of the se... |
348,910 | def search(self, query, verbose=0):
if verbose > 0:
print("searching " + query)
query = query.lower()
qgram = ng(query, self.slb)
qocument = set()
for q in qgram:
if q in self.ngrams.keys():
for i in self.ngrams[q]:
... | Searches files satisfying query
It first decompose the query in ngrams, then score each document containing
at least one ngram with the number. The ten document having the most ngrams
in common with the query are selected.
Args:
query (str): what to search;
... |
348,911 | def parse_document_id(chrom, pos, ref, alt, variant_type, case_id):
return generate_md5_key([chrom, pos, ref, alt, variant_type, case_id]) | Parse the unique document id for a variant.
This will always be unique in the database.
Args:
chrom(str)
pos(str)
ref(str)
alt(str)
variant_type(str): 'clinical' or 'research'
case_id(str): unqiue family id
Returns:
document_id(str): The unique docu... |
348,912 | def filter(self, msg_type=None, maxsize=0):
if self._dead:
return iter(())
iterator = Handler._SBPQueueIterator(maxsize)
ref = weakref.ref(iterator)
self._sinks.append(ref)
def feediter(msg, **metadata):
i = ref()
if... | Get a filtered iterator of messages for synchronous, blocking use in
another thread. |
348,913 | def task_requires(*dependencies):
def entangle(task):
"Decorator wrapper."
if not isinstance(task, tasks.Task):
task = tasks.Task(task)
def tool_task(*args, **kw):
"Install requirements, then call original task."
install_tools(dependencies)
... | A task decorator that ensures a distutils dependency (or a list thereof) is met
before that task is executed. |
348,914 | def peek_all(self, model_class):
if self._cache:
return self._cache.get_records(model_class.__name__)
else:
return [] | Return a list of models from the local cache.
Args:
model_class (:class:`cinder_data.model.CinderModel`): A subclass of
:class:`cinder_data.model.CinderModel` of your chosen model.
Returns:
list: A list of instances of you model_class or and empty list. |
348,915 | def logCellActivity_varyNumColumns(noiseSigma, noiseEverywhere):
noiseLevels = [0.30, 0.40, 0.45, 0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90]
l2Overrides = {"sampleSizeDistal": 20}
columnCounts = [1, 2, 3, 4, 5]
results = defaultdict(list)
for trial in xrange(1):
print "trial", trial
ob... | Run the experiment, varying the column counts, and save each
[# correctly active cells, # incorrectly active cells]
pair to a JSON file that can be visualized. |
348,916 | def vspec_magic(data):
vdata, Dirdata, step_meth = [], [], ""
if len(data) == 0:
return vdata
treat_init = ["treatment_temp", "treatment_temp_decay_rate", "treatment_temp_dc_on", "treatment_temp_dc_off", "treatment_ac_field", "treatment_ac_field_decay_rate", "treatment_ac_field_dc_on",
... | Takes average vector of replicate measurements |
348,917 | def __vCmdSetCamExposureMode(self, args):
if len(args) == 1:
for cam in self.camera_list:
cam.boSetExposureMode(args[0])
elif len(args) == 2:
cam = self.camera_list[int(args[1])]
cam.boSetExposureMode(args[0])
else:
print (... | ToDo: Validate CAM number and Valid Mode Values |
348,918 | def sync_map_permissions(self):
if self._sync_map_permissions is None:
self._sync_map_permissions = SyncMapPermissionList(
self._version,
service_sid=self._solution[],
map_sid=self._solution[],
)
return self._sync_map_permi... | Access the sync_map_permissions
:returns: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionList
:rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionList |
348,919 | def _join_names(names):
levels = (str(name) for name in names if name != )
return .join(levels) | Join the names of a multi-level index with an underscore. |
348,920 | async def fetch_ban(self, user):
data = await self._state.http.get_ban(user.id, self.id)
return BanEntry(
user=User(state=self._state, data=data[]),
reason=data[]
) | |coro|
Retrieves the :class:`BanEntry` for a user, which is a namedtuple
with a ``user`` and ``reason`` field. See :meth:`bans` for more
information.
You must have the :attr:`~Permissions.ban_members` permission
to get this information.
Parameters
-----------
... |
348,921 | def get_last_config_update_time_for_xpaths_input_xpath_strings_xpath_string(self, **kwargs):
config = ET.Element("config")
get_last_config_update_time_for_xpaths = ET.Element("get_last_config_update_time_for_xpaths")
config = get_last_config_update_time_for_xpaths
input = ET.Sub... | Auto Generated Code |
348,922 | def emit(self, event: str, *args, **kwargs) -> None:
threads = kwargs.pop(, None)
if threads:
events = [
Thread(target=f, args=args, kwargs=kwargs) for f in
self._event_funcs(event)
]
for event in events:
eve... | Emit an event and run the subscribed functions.
:param event: Name of the event.
:type event: str
.. notes:
Passing in threads=True as a kwarg allows to run emitted events
as separate threads. This can significantly speed up code execution
depending on the c... |
348,923 | def _get_ratings_page(self):
self._build_url()
soup = get_soup(self.url)
if soup:
return soup
self._build_url(shorten=False)
soup = get_soup(self.url)
if soup:
return soup
return SearchDaily(self.catego... | Do a limited search for the correct url. |
348,924 | def make_table(self,fromlines,tolines,fromdesc=,todesc=,context=False,
numlines=5):
self._make_prefix()
fromlines,tolines = self._tab_newline_replace(fromlines,tolines)
if context:
context_lines = numlines
... | Returns HTML table of side by side comparison with change highlights
Arguments:
fromlines -- list of "from" lines
tolines -- list of "to" lines
fromdesc -- "from" file column header string
todesc -- "to" file column header string
context -- set to True for contextual dif... |
348,925 | def reciprocal_lattice(self) -> "Lattice":
v = np.linalg.inv(self._matrix).T
return Lattice(v * 2 * np.pi) | Return the reciprocal lattice. Note that this is the standard
reciprocal lattice used for solid state physics with a factor of 2 *
pi. If you are looking for the crystallographic reciprocal lattice,
use the reciprocal_lattice_crystallographic property.
The property is lazily generated fo... |
348,926 | def config_profile_list(self):
these_profiles = self._config_profile_list() or []
profile_list = [q for p in these_profiles for q in
[p.get()]]
return profile_list | Return config profile list from DCNM. |
348,927 | def _dictToAlignments(self, diamondDict, read):
alignments = []
getScore = itemgetter( if self._hspClass is HSP else )
for diamondAlignment in diamondDict[]:
alignment = Alignment(diamondAlignment[],
diamondAlignment[])
alignmen... | Take a dict (made by DiamondTabularFormatReader.records)
and convert it to a list of alignments.
@param diamondDict: A C{dict}, from records().
@param read: A C{Read} instance, containing the read that DIAMOND used
to create this record.
@return: A C{list} of L{dark.alignmen... |
348,928 | def slice_columns(x, using=None):
if using is None:
using = range(0, len(x[0]))
return [x[:,s] for s in using] | Slice a numpy array to make columns
Parameters
----------
x : ndarray
A numpy array instance
using : list of integer or slice instance or None, optional
A list of index or slice instance
Returns
-------
ndarray
A list of numpy array columns sliced |
348,929 | def set_file_chksum(self, doc, chk_sum):
if self.has_package(doc) and self.has_file(doc):
if not self.file_chksum_set:
self.file_chksum_set = True
self.file(doc).chk_sum = checksum.Algorithm(, chk_sum)
return True
else:
... | Sets the file check sum, if not already set.
chk_sum - A string
Raises CardinalityError if already defined.
Raises OrderError if no package previously defined. |
348,930 | def fit(self,vxvv,vxvv_err=None,pot=None,radec=False,lb=False,
customsky=False,lb_to_customsky=None,pmllpmbb_to_customsky=None,
tintJ=10,ntintJ=1000,integrate_method=,
disp=False,
**kwargs):
if pot is None:
try:
pot= self._pot
... | NAME:
fit
PURPOSE:
fit an Orbit to data using the current orbit as the initial
condition
INPUT:
vxvv - [:,6] array of positions and velocities along the orbit [cannot be Quantities]
vxvv_err= [:,6] array of errors on positions and velocities along ... |
348,931 | def report_message_type(self, msg):
desc = get_message_description(self.linter, msg.msg_id)
self.tc.message(, id=msg.msg_id, name=msg.symbol, description=desc, category=msg.category) | Issues an `inspectionType` service message to define generic properties of a given PyLint message type.
:param utils.Message msg: a PyLint message |
348,932 | def create(cls, name, database=SYSTEM_DATABASE, type=2):
client = Client.instance()
api = client.api
if client.database != database:
database = client.database
collection_data = {
: name,
: type,
}
data = api.collection.pos... | Creates collection
:param name Collection name
:param database Database name in which it is created
:param type Collection type (2 = document / 3 = edge)
:returns Collection |
348,933 | def indexes(self, collection=None):
indexes = []
for collection_name in self.collections():
if collection and collection != collection_name:
continue
for index_name in self.db[collection_name].index_information():
if index_name !... | Return a list with the current indexes
Skip the mandatory _id_ indexes
Args:
collection(str)
Returns:
indexes(list) |
348,934 | def get_template(template_name, data_dir=None, url=None, resume=True, verbose=1):
warn(DEPRECATION_MSG)
if template_name.startswith():
template_name = template_name[4:]
template_name = TEMPLATE_ALIASES.get(template_name, template_name)
return get_dataset(template_name, dataset_prefix=... | Download and load a template |
348,935 | def _process_organism_dbxref(self, limit):
if self.test_mode:
graph = self.testgraph
else:
graph = self.graph
model = Model(graph)
line_counter = 0
raw = .join((self.rawdir, ))
LOG.info("processing organsim dbxref mappings")
with o... | This is the mapping between the flybase organisms and
external identifier "FBsp". We will want to use the NCBITaxon as
the primary, if possible, but will default to a blank node/internal id
if that is all that is available
But we need to make the equivalences/sameAs.
:param limi... |
348,936 | def start_parent():
while True:
args = [sys.executable] + sys.argv
new_environ = environ.copy()
new_environ["_IN_CHILD"] =
ret = subprocess.call(args, env=new_environ)
if ret != settings.CODE_RELOAD_EXIT:
return ret | Start the parent that will simply run the child forever until stopped. |
348,937 | def _process_net_mhcii(mhc_file, normal=False):
results = pandas.DataFrame(columns=[, , , , ])
with open(mhc_file, ) as mf:
peptides = set()
allele = re.sub(, , mf.readline().strip())
_ = mf.readline()
for line in mf:
line = line.strip().split()
... | Process the results from running NetMHCIIpan binding predictions into a pandas dataframe.
:param str mhc_file: Output file containing netmhciipan mhcii:peptide binding predictions
:param bool normal: Is this processing the results of a normal?
:return: Results in a tabular format
:rtype: pandas.DataFra... |
348,938 | def from_base64_data(cls, **kwargs):
o = cls()
meta = cls._meta
pkname = meta.pkname()
for name, value in iteritems(kwargs):
if name == pkname:
field = meta.pk
elif name in meta.dfields:
field = meta.dfields[name]
... | Load a :class:`StdModel` from possibly base64encoded data.
This method is used to load models from data obtained from the :meth:`tojson`
method. |
348,939 | def Initialize(config=None,
external_hostname = None,
admin_password = None,
redownload_templates = False,
repack_templates = True,
token = None):
print("Checking write access on config %s" % config["Config.writeback"])
if not os.access(... | Initialize or update a GRR configuration. |
348,940 | def ctrl_alt_del(vm_, **kwargs):
*
conn = __get_conn(**kwargs)
dom = _get_domain(conn, vm_)
ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0
conn.close()
return ret | Sends CTRL+ALT+DEL to a VM
: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.0
:param password: password to connect with, overriding ... |
348,941 | def daemonize(**params):
log = params.get()
redir = params.get(, True)
try:
if os.fork() != 0:
os._exit(0)
except Exception as e:
if log: log("First fork failed -- %s", e)
return False
try:
os.setsid()
except Exception as e:
if log: log("... | This is a simple daemonization method. It just does a double fork() and the
parent exits after closing a good clump of possibly open file descriptors. The
child redirects stdin from /dev/null and sets a new process group and session.
If you need fancier, suggest you look at http://pypi.python.org/pypi/python-daemon/
... |
348,942 | def on_command(name: Union[str, CommandName_T], *,
aliases: Iterable[str] = (),
permission: int = perm.EVERYBODY,
only_to_me: bool = True,
privileged: bool = False,
shell_like: bool = False) -> Callable:
def deco(func: CommandHandler_T... | Decorator to register a function as a command.
:param name: command name (e.g. 'echo' or ('random', 'number'))
:param aliases: aliases of command name, for convenient access
:param permission: permission required by the command
:param only_to_me: only handle messages to me
:param privileged: can be... |
348,943 | def _rev(repo):
try:
repo_info = dict(six.iteritems(CLIENT.info(repo[])))
except (pysvn._pysvn.ClientError, TypeError,
KeyError, AttributeError) as exc:
log.error(
,
repo[], repo[], exc
)
else:
return repo_info[].number
... | Returns revision ID of repo |
348,944 | def install_completion(ctx, attr, value):
import click_completion.core
if not value or ctx.resilient_parsing:
return value
shell, path = click_completion.core.install()
click.secho(
.format(shell, path), fg=
)
ctx.exit() | Install completion for the current shell. |
348,945 | def list_deployments(self):
response = self._do_request(, )
return self._parse_response(response, MarathonDeployment, is_list=True) | List all running deployments.
:returns: list of deployments
:rtype: list[:class:`marathon.models.deployment.MarathonDeployment`] |
348,946 | def determine_collections(self):
for value in record_get_field_values(self.record, , code=):
if in value.upper():
self.collections.add()
if in value.upper():
self.collections.add()
if in value.upper():
self.collectio... | Try to determine which collections this record should belong to. |
348,947 | def aliases(context, build, symbol):
LOG.info("Running scout view aliases")
adapter = context.obj[]
if symbol:
alias_genes = {}
res = adapter.gene_by_alias(symbol, build=build)
for gene_obj in res:
hgnc_id = gene_obj[]
hgnc_symbol = gene... | Show all alias symbols and how they map to ids |
348,948 | def _outer_to_vectorized_indexer(key, shape):
key = key.tuple
n_dim = len([k for k in key if not isinstance(k, integer_types)])
i_dim = 0
new_key = []
for k, size in zip(key, shape):
if isinstance(k, integer_types):
new_key.append(np.array(k).reshape((1,) * n_dim))
... | Convert an OuterIndexer into an vectorized indexer.
Parameters
----------
key : Outer/Basic Indexer
An indexer to convert.
shape : tuple
Shape of the array subject to the indexing.
Returns
-------
VectorizedIndexer
Tuple suitable for use to index a NumPy array with ... |
348,949 | def BCC(self, params):
label = self.get_one_parameter(self.ONE_PARAMETER, params)
self.check_arguments(label_exists=(label,))
def BCC_func():
if not self.is_C_set():
self.register[] = self.labels[label]
return BCC_func | BCC label
Branch to the instruction at label if the C flag is not set |
348,950 | def pandas(self):
names,prior,posterior = [],[],[]
for iname,name in enumerate(self.posterior_parameter.row_names):
names.append(name)
posterior.append(np.sqrt(float(
self.posterior_parameter[iname, iname]. x)))
iprior = self.parcov.row_names.... | get a pandas dataframe of prior and posterior for all predictions
Returns:
pandas.DataFrame : pandas.DataFrame
a dataframe with prior and posterior uncertainty estimates
for all forecasts (predictions) |
348,951 | def rownumber(self):
if self._frame is not None and self._pos is not None:
return self._frame.offset + self._pos
return self._pos | Read-only attribute providing the current 0-based index of the
cursor in the result set or ``None`` if the index cannot be
determined.
The index can be seen as index of the cursor in a sequence
(the result set). The next fetch operation will fetch the
row indexed by :attr:`rownu... |
348,952 | def list_pool(self, auth, spec=None):
if spec is None:
spec = {}
self._logger.debug("list_pool called; spec: %s" % unicode(spec))
sql =
params = list()
where, params = self._expand_pool_spec(spec)
if len(where) > 0:
sql += " ... | Return a list of pools.
* `auth` [BaseAuth]
AAA options.
* `spec` [pool_spec]
Specifies what pool(s) to list. Of omitted, all will be listed.
Returns a list of dicts.
This is the documentation of the internal backend function. It's
... |
348,953 | def get_data(self):
data = []
ntobj = cx.namedtuple("NtGoCnt", "Depth_Level BP_D MF_D CC_D BP_L MF_L CC_L")
cnts = self.get_cnts_levels_depths_recs(set(self.obo.values()))
max_val = max(max(dep for dep in cnts[]), max(lev for lev in cnts[]))
for i in ra... | Collect counts of GO terms at all levels and depths. |
348,954 | def check_configuration_string(
self,
config_string,
is_job=True,
external_name=False
):
if is_job:
self.log(u"Checking job configuration string")
else:
self.log(u"Checking task configuration string")
self.resul... | Check whether the given job or task configuration string
is well-formed (if ``is_bstring`` is ``True``)
and it has all the required parameters.
:param string config_string: the byte string or Unicode string to be checked
:param bool is_job: if ``True``, ``config_string`` is a job config... |
348,955 | def list_ebs(region, filter_by_kwargs):
conn = boto.ec2.connect_to_region(region)
instances = conn.get_all_volumes()
return lookup(instances, filter_by=filter_by_kwargs) | List running ebs volumes. |
348,956 | def _convert_schema(bundle):
schema_csv = None
for f in bundle.dataset.files:
if f.path.endswith():
contents = f.unpacked_contents
if isinstance(contents, six.binary_type):
contents = contents.decode()
schema_csv = six.StringIO(contents)
... | Converts schema of the dataset to resource dict ready to save to CKAN. |
348,957 | def moveToNextRow(vs, func, reverse=False):
rng = range(vs.cursorRowIndex-1, -1, -1) if reverse else range(vs.cursorRowIndex+1, vs.nRows)
for i in rng:
try:
if func(vs.rows[i]):
vs.cursorRowIndex = i
return True
except Exception:
pass... | Move cursor to next (prev if reverse) row for which func returns True. Returns False if no row meets the criteria. |
348,958 | async def xgroup_set_id(self, name: str, group: str, stream_id: str) -> bool:
return await self.execute_command(, name, group, stream_id) | [NOTICE] Not officially released yet
:param name: name of the stream
:param group: name of the consumer group
:param stream_id:
If we provide $ as we did, then only new messages arriving
in the stream from now on will be provided to the consumers in the group.
... |
348,959 | def voucher_code(request):
VOUCHERS_FORM_PREFIX = "vouchers"
v = _handle_voucher(request, VOUCHERS_FORM_PREFIX)
voucher_form, voucher_handled = v
if voucher_handled:
messages.success(request, "Your voucher code was accepted.")
return redirect("dashboard")
data = {
... | A view *just* for entering a voucher form. |
348,960 | def buses_of_vlvl(network, voltage_level):
mask = network.buses.v_nom.isin(voltage_level)
df = network.buses[mask]
return df.index | Get bus-ids of given voltage level(s).
Parameters
----------
network : :class:`pypsa.Network
Overall container of PyPSA
voltage_level: list
Returns
-------
list
List containing bus-ids. |
348,961 | def create_packages_archive(packages, filename):
import tarfile
tar = tarfile.open(filename, "w")
def add(src, dst):
logger.debug(, src, dst)
tar.add(src, dst)
def add_files_for_package(sub_package_path, root_package_path, root_package_name):
for root, dirs, files in os.wa... | Create a tar archive which will contain the files for the packages listed in packages. |
348,962 | def dfs(self, node, bucket=None, order="append"):
if self[node].discovered:
return bucket
self[node].discovered = True
nodes_ = sorted(self[node].iternodes(), cmp=self.cmp_branch)
for node_ in nodes_:
self.dfs(node_, bucket, order)
getattr(bucket,... | Recursive depth first search. By default ("order" = ``"append"``) this
returns the **node objects** in the reverse postorder. To change this
into the preorder use a ``collections.deque`` as "bucket" and
``"appendleft"`` as "order".
Arguments:
- bucket(``list`` ... |
348,963 | def morphAveragePitch(fromDataList, toDataList):
timeList, fromPitchList = zip(*fromDataList)
toPitchList = [pitchVal for _, pitchVal in toDataList]
fromListNoZeroes = [val for val in fromPitchList if val > 0]
fromAverage = sum(fromListNoZeroes) / float(len(fromListNoZeroes))
... | Adjusts the values in fromPitchList to have the same average as toPitchList
Because other manipulations can alter the average pitch, morphing the pitch
is the last pitch manipulation that should be done
After the morphing, the code removes any values below zero, thus the
final average might no... |
348,964 | def filter_wait_on_queues(max_waiting):
def filter_func(log_line):
waiting = int(max_waiting)
return waiting >= log_line.time_wait_queues
return filter_func | Filter :class:`.Line` objects by their queueing time in
HAProxy.
:param max_waiting: maximum time, in milliseconds, a request is waiting on
HAProxy prior to be delivered to a backend server. If HAProxy takes less
than that time the log line is counted.
:type max_waiting: string
:returns: a ... |
348,965 | def get_transition(self,
line,
line_index,
column,
is_escaped,
comment_system_transitions,
eof=False):
del comment_system_transitions
if (_token_at_col_in... | Get transition from InCommentParser. |
348,966 | def acorr_lpc(x, axis=-1):
if not np.isrealobj(x):
raise ValueError("Complex input not supported yet")
maxlag = x.shape[axis]
nfft = int(2 ** nextpow2(2 * maxlag - 1))
if axis != -1:
x = np.swapaxes(x, -1, axis)
a = _acorr_last_axis(x, nfft, maxlag)
if axis != -1:
... | Compute autocorrelation of x along the given axis.
This compute the biased autocorrelation estimator (divided by the size of
input signal)
Notes
-----
The reason why we do not use acorr directly is for speed issue. |
348,967 | def plot_rebit_posterior(updater, prior=None, true_state=None, n_std=3, rebit_axes=REBIT_AXES, true_size=250,
legend=True,
level=0.95,
region_est_method=
):
pallette = plt.rcParams[]
plot_rebit_modelparams(updater.particle_locations,
c=pallette[0],
l... | Plots posterior distributions over rebits, including covariance ellipsoids
:param qinfer.smc.SMCUpdater updater: Posterior distribution over rebits.
:param qinfer.tomography.DensityOperatorDistribution: Prior distribution
over rebit states.
:param np.ndarray true_state: Model parameters for "true" ... |
348,968 | def getUser(self):
username = self.getUsername()
if not username:
return None
user = api.user.get(userid=username)
return user | Returns the linked Plone User or None |
348,969 | def postprocess_WC(self, entry):
if type(entry.WC) not in [str, unicode]:
WC= u.join([unicode(k) for k in entry.WC])
else:
WC= entry.WC
entry.WC= [k.strip().upper() for k in WC.split()] | Parse WC keywords.
Subject keywords are usually semicolon-delimited. |
348,970 | def symbol_size(self, scale=1, border=None):
return utils.get_symbol_size(self._version, scale=scale, border=border) | \
Returns the symbol size (width x height) with the provided border and
scaling factor.
:param scale: Indicates the size of a single module (default: 1).
The size of a module depends on the used output format; i.e.
in a PNG context, a scaling factor of 2 indicate... |
348,971 | async def sdiff(self, keys, *args):
"Return the difference of sets specified by ``keys``"
args = list_or_args(keys, args)
return await self.execute_command(, *args) | Return the difference of sets specified by ``keys`` |
348,972 | def items(self):
return [(value_descriptor.name, value_descriptor.number)
for value_descriptor in self._enum_type.values] | Return a list of the (name, value) pairs of the enum.
These are returned in the order they were defined in the .proto file. |
348,973 | def _tls_hmac_add(self, hdr, msg):
write_seq_num = struct.pack("!Q", self.tls_session.wcs.seq_num)
self.tls_session.wcs.seq_num += 1
alg = self.tls_session.wcs.hmac
version = struct.unpack("!H", hdr[1:3])[0]
if version > 0x300:
h = alg.digest(write_seq_num +... | Provided with the record header (concatenation of the TLSCompressed
type, version and length fields) and the TLSCompressed.fragment,
return the concatenation of the TLSCompressed.fragment and the HMAC.
Meant to be used with a block cipher or a stream cipher.
It would fail with an AEAD c... |
348,974 | def calc_derivation(passphrase, salt):
argonhash = argon2.low_level.hash_secret_raw((str.encode(passphrase)), salt=salt, hash_len=32,
time_cost=__argon2_timing_cost__, memory_cost=__argon2_memory_cost__,
paralleli... | Calculate a 32 bytes key derivation with Argon2.
:param passphrase: A string of any length specified by user.
:param salt: 512 bits generated by Botan Random Number Generator.
:return: a 32 bytes keys. |
348,975 | def is_directory_index(resource):
remote_regexp = re.compile(r"^https?://(.+)/?$", re.I)
result = remote_regexp.match(resource)
if result is not None:
juicer.utils.Log.log_debug("%s matches directory index regexp" % resource)
return True
else:
juicer.utils.Log.log_debug("%s... | Classify the input resource as a directory index or not. |
348,976 | def receive(self, length):
slipDriver = sliplib.Driver()
ret = self._serialPort.read(length)
temp = slipDriver.receive(ret)
return iter(temp) | Reads in data from a serial port (length bytes), decodes SLIP packets
A function which reads from the serial port and then uses the SlipLib
module to decode the SLIP protocol packets. Each message received
is added to a receive buffer in SlipLib which is then returned.
Args:
... |
348,977 | def get_valid_fns(self) -> Tuple[List[str], List[str]]:
return self.prefixes_to_fns(self.valid_prefixes) | Fetches the validation set of the corpus. |
348,978 | def _span_dimensions(self, other_tc):
def raise_on_inverted_L(a, b):
if a.top == b.top and a.bottom != b.bottom:
raise InvalidSpanError()
if a.left == b.left and a.right != b.right:
raise InvalidSpanError()
def raise_on_tee_shaped(a, b):
... | Return a (top, left, height, width) 4-tuple specifying the extents of
the merged cell formed by using this tc and *other_tc* as opposite
corner extents. |
348,979 | def make_attribute_list(self, node):
atr_nodes = []
for n in self.get_specific_subnodes(node, , recursive=2):
if n.attributes[].value == and n.attributes[].value == :
atr_nodes.append(n)
if not atr_nodes:
return
self.add_text([, ,
... | Produces the "Attributes" section in class docstrings for public
member variables (attributes). |
348,980 | def strace_data_access_event(self,
operation,
address,
data,
data_mask=None,
access_width=4,
address_range=0):
... | Sets an event to trigger trace logic when data access is made.
Data access corresponds to either a read or write.
Args:
self (JLink): the ``JLink`` instance.
operation (int): one of the operations in ``JLinkStraceOperation``.
address (int): the address of the load/store d... |
348,981 | def _expand_pattern_lists(pattern, **mappings):
expanded_patterns = []
f = string.Formatter()
for (_, field_name, _, _) in f.parse(pattern):
if field_name is None:
continue
(value, _) = f.get_field(field_name, None, mappings)
if isinstance(value, list):
... | Expands the pattern for any list-valued mappings, such that for any list of
length N in the mappings present in the pattern, N copies of the pattern are
returned, each with an element of the list substituted.
pattern:
A pattern to expand, for example ``by-role/{grains[roles]}``
mappings:
... |
348,982 | def is_prettytable(string):
return type(string).__name__ in {,} and (
len(string.splitlines()) > 1
) and (
all(string[i] == string[-i-1] for i in range(3))
) | returns true if the input looks like a prettytable |
348,983 | def register_lists(self, category_lists, lists_init_kwargs=None, editor_init_kwargs=None):
lists_init_kwargs = lists_init_kwargs or {}
editor_init_kwargs = editor_init_kwargs or {}
for lst in category_lists:
if isinstance(lst, string_types):
lst = self.lis... | Registers CategoryList objects to handle their requests.
:param list category_lists: CategoryList objects
:param dict lists_init_kwargs: Attributes to apply to each of CategoryList objects |
348,984 | def viewlog(calc_id, host=, port=8000):
base_url = % (host, port)
start = 0
psize = 10
try:
while True:
url = base_url + % (calc_id, start, start + psize)
rows = json.load(urlopen(url))
for row in rows:
print(.join(row))
st... | Extract the log of the given calculation ID from the WebUI |
348,985 | def swo_disable(self, port_mask):
res = self._dll.JLINKARM_SWO_DisableTarget(port_mask)
if res != 0:
raise errors.JLinkException(res)
return None | Disables ITM & Stimulus ports.
Args:
self (JLink): the ``JLink`` instance
port_mask (int): mask specifying which ports to disable
Returns:
``None``
Raises:
JLinkException: on error |
348,986 | def check_id_idx_exclusivity(id, idx):
if (id is not None and idx is not None):
msg = (" and fields can't both not be None," +
" please specify subset in only one of these fields")
logger.error(msg)
raise Exception("parse_gctx.check_id_idx_exclusivity: " + msg)
elif ... | Makes sure user didn't provide both ids and idx values to subset by.
Input:
- id (list or None): if not None, a list of string id names
- idx (list or None): if not None, a list of integer id indexes
Output:
- a tuple: first element is subset type, second is subset content |
348,987 | def _cut(dna, index, restriction_enzyme):
cut_site = restriction_enzyme.cut_site
top_cut = index + cut_site[0]
bottom_cut = index + cut_site[1]
to_cut = dna.pop()
max_cut = max(top_cut, bottom_cut)
min_cut = min(top_cut, bottom_cut)
left = to_cut[:max_cut]
right... | Cuts template once at the specified index.
:param dna: DNA to cut
:type dna: coral.DNA
:param index: index at which to cut
:type index: int
:param restriction_enzyme: Enzyme with which to cut
:type restriction_enzyme: coral.RestrictionSite
:returns: 2-element list of digested sequence, incl... |
348,988 | def print_preprocessing_list(preprocessing_queue):
print("
print("```")
for algorithm in preprocessing_queue:
print("* " + str(algorithm))
print("```") | Print the ``preproc_list`` in a human-readable form.
Parameters
----------
preprocessing_queue : list of preprocessing objects
Algorithms that get applied for preprocessing. |
348,989 | def format_node(import_graph, node, indent):
if isinstance(node, graph.NodeSet):
ind = * indent
out = [ind + ] + [
format_file_node(import_graph, n, indent + 1)
for n in node.nodes
] + [ind + ]
return .join(out)
else:
return format_fi... | Helper function for print_tree |
348,990 | def parseDate(dateString, strict=True):
if (not strict) and (not dateString):
return None
if not isinstance(dateString, basestring):
raise TypeError( % dateString)
return parser.parse(dateString) | Return a datetime object, by parsing a string date/time
With strict=False, dateString may be None or '', otherwise it must be a
parseable string |
348,991 | def xml_tag (self, name, content, attrs=None):
self.write(self.indent*self.level)
self.write(u"<%s" % xmlquote(name))
if attrs:
for aname, avalue in attrs.items():
args = (xmlquote(aname), xmlquoteattr(avalue))
self.write(u % args)
sel... | Write XML tag with content. |
348,992 | def get_all_server_credentials(self, authorization, **kwargs):
kwargs[] = True
if kwargs.get():
return self.get_all_server_credentials_with_http_info(authorization, **kwargs)
else:
(data) = self.get_all_server_credentials_with_http_info(authorization, **kwarg... | Fetch all (Bootstrap and LwM2M) server credentials. # noqa: E501
This REST API is intended to be used by customers to fetch all (Bootstrap and LwM2M) server credentials that they will need to use with their clients to connect to bootstrap or LwM2M server. **Example usage:** curl -X GET \"http://api.us-east-1... |
348,993 | def delimit_slug(slug, sep=):
hyphenated_slug = re.sub(CRE_SLUG_DELIMITTER, sep, slug)
return hyphenated_slug | Return a str of separated tokens found within a slugLike_This => 'slug Like This'
>>> delimit_slug("slugLike_ThisW/aTLA's")
'slug Like This W a TLA s'
>>> delimit_slug('slugLike_ThisW/aTLA', '|')
'slug|Like|This|W|a|TLA' |
348,994 | def detect_arbitrary_send(self, contract):
ret = []
for f in [f for f in contract.functions if f.contract == contract]:
nodes = self.arbitrary_send(f)
if nodes:
ret.append((f, nodes))
return ret | Detect arbitrary send
Args:
contract (Contract)
Returns:
list((Function), (list (Node))) |
348,995 | def actions(self):
r = self.session.query(models.Action).all()
return [x.type_name for x in r] | Gets the list of allowed actions
:rtype: list[str] |
348,996 | def get(self, exclude_recurse=None):
reqs = Queue()
pending = 1
path = self.path
zk = self.zk
def child_of(path):
return zk.get_children_async(path)
def dispatch(path):
return Request(path, child_of(path))
stat = zk.exists(path)... | Paths matching exclude_recurse will not be recursed. |
348,997 | def do_shell(self, arglist):
proc = subprocess.Popen(
shlex.split(arglist), stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
print(proc.communicate()[0]) | Run a shell command |
348,998 | def apply_patch(self, patch_path):
return self._execute(, stdout=open(os.devnull, ), stdin=open(patch_path, ))[0] | Applies the patch located at *patch_path*. Returns the return code of
the patch command. |
348,999 | def list_files(i):
o=i.get(,)
ruoa=i.get(,)
muoa=i.get(,)
duoa=i.get(,)
r=load({:ruoa, :muoa, :duoa})
if r[]>0: return r
p=r[]
ii={:p}
if i.get(,)!=: ii[]=i[]
if i.get(,)!=: ii[]=i[]
if i.get(,)!=: ii[]=i[]
r=list_all_files(ii)
if r[]>0: return r
... | Input: {
(repo_uoa)
(module_uoa)
(data_uoa)
parameters for function 'list_all_files'
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.