Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
1,700 | def get_protein_data_pgrouped(proteindata, p_acc, headerfields):
report = get_protein_data_base(proteindata, p_acc, headerfields)
return get_cov_protnumbers(proteindata, p_acc, report) | Parses protein data for a certain protein into tsv output
dictionary |
1,701 | def truncate(self, length):
if length > len(self.digest):
raise ValueError("cannot enlarge the original digest by %d bytes"
% (length - len(self.digest)))
return self.__class__(self.func, self.digest[:length]) | Return a new `Multihash` with a shorter digest `length`.
If the given `length` is greater than the original, a `ValueError`
is raised.
>>> mh1 = Multihash(0x01, b'FOOBAR')
>>> mh2 = mh1.truncate(3)
>>> mh2 == (0x01, b'FOO')
True
>>> mh3 = mh1.truncate(10)
... |
1,702 | def _process_state(cls, unprocessed, processed, state):
assert type(state) is str, "wrong state name %r" % state
assert state[0] != , "invalid state name %r" % state
if state in processed:
return processed[state]
tokens = processed[state] = []
rflags = cls.fl... | Preprocess a single state definition. |
1,703 | def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
tabs = self.get_active_tabs()
context.update({
: tabs,
: tabs[0].code if tabs else ,
: self.get_app_label(),
: self.get_model_name(),
: self.get... | Add context data to view |
1,704 | def lx4num(string, first):
string = stypes.stringToCharP(string)
first = ctypes.c_int(first)
last = ctypes.c_int()
nchar = ctypes.c_int()
libspice.lx4num_c(string, first, ctypes.byref(last), ctypes.byref(nchar))
return last.value, nchar.value | Scan a string from a specified starting position for the
end of a number.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lx4num_c.html
:param string: Any character string.
:type string: str
:param first: First character to scan from in string.
:type first: int
:return: last and nc... |
1,705 | def fmap(self, f: Callable[[T], B]) -> :
return List([f(x) for x in self.unbox()]) | doufo.List.fmap: map `List`
Args:
`self`:
`f` (`Callable[[T], B]`): any callable funtion
Returns:
return (`List[B]`): A `List` of objected from `f`.
Raises: |
1,706 | def is_valid_mac(addr):
addrs = addr.split()
if len(addrs) != 6:
return False
for m in addrs:
try:
if int(m, 16) > 255:
return False
except ValueError:
return False
return True | Check the syntax of a given mac address.
The acceptable format is xx:xx:xx:xx:xx:xx |
1,707 | def analyze(problem, Y, calc_second_order=True, num_resamples=100,
conf_level=0.95, print_to_console=False, parallel=False,
n_processors=None, seed=None):
if seed:
np.random.seed(seed)
if not problem.get():
D = problem[]
else:
D = len(s... | Perform Sobol Analysis on model outputs.
Returns a dictionary with keys 'S1', 'S1_conf', 'ST', and 'ST_conf', where
each entry is a list of size D (the number of parameters) containing the
indices in the same order as the parameter file. If calc_second_order is
True, the dictionary also contains ... |
1,708 | def renumber(args):
from jcvi.algorithms.lis import longest_increasing_subsequence
from jcvi.utils.grouper import Grouper
p = OptionParser(renumber.__doc__)
p.set_annot_reformat_opts()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
bedfile, =... | %prog renumber Mt35.consolidated.bed > tagged.bed
Renumber genes for annotation updates. |
1,709 | def getNextService(self, discover):
manager = self.getManager()
if manager is not None and not manager:
self.destroyManager()
if not manager:
yadis_url, services = discover(self.url)
manager = self.createManager(services, yadis_url)
if manag... | Return the next authentication service for the pair of
user_input and session. This function handles fallback.
@param discover: a callable that takes a URL and returns a
list of services
@type discover: str -> [service]
@return: the next available service |
1,710 | def awake(self, procid):
logger.debug(f"Remove procid:{procid} from waitlists and reestablish it in the running list")
for wait_list in self.rwait:
if procid in wait_list:
wait_list.remove(procid)
for wait_list in self.twait:
if procid in wait_lis... | Remove procid from waitlists and reestablish it in the running list |
1,711 | def encode_username_password(
username: Union[str, bytes], password: Union[str, bytes]
) -> bytes:
if isinstance(username, unicode_type):
username = unicodedata.normalize("NFC", username)
if isinstance(password, unicode_type):
password = unicodedata.normalize("NFC", password)
return... | Encodes a username/password pair in the format used by HTTP auth.
The return value is a byte string in the form ``username:password``.
.. versionadded:: 5.1 |
1,712 | def set_translation(lang):
global translation
langs = list()
if lang:
if in lang:
lang = lang.split()[0]
langs += [lang, lang[:2]]
path = pkg_resources.resource_filename(, )
codeset = locale.getpreferredencoding()
if codeset == :
codeset =
... | Set the translation used by (some) pywws modules.
This sets the translation object ``pywws.localisation.translation``
to use a particular language.
The ``lang`` parameter can be any string of the form ``en``,
``en_GB`` or ``en_GB.UTF-8``. Anything after a ``.`` character is
ignored. In the case of... |
1,713 | def accept(self):
client, addr = self._socket.accept()
conn = Connection(self._context, client)
conn.set_accept_state()
return (conn, addr) | Call the :meth:`accept` method of the underlying socket and set up SSL
on the returned socket, using the Context object supplied to this
:class:`Connection` object at creation.
:return: A *(conn, addr)* pair where *conn* is the new
:class:`Connection` object created, and *address* i... |
1,714 | def attach_related_file(self, path, mimetype=None):
filename = os.path.basename(path)
content = open(path, ).read()
self.attach_related(filename, content, mimetype) | Attaches a file from the filesystem. |
1,715 | def convertPrice(variant, regex=None, short_regex=None, none_regex=none_price_regex):
if isinstance(variant, int) and not isinstance(variant, bool):
return variant
elif isinstance(variant, float):
return round(variant * 100)
elif isinstance(variant, str):
match = (regex or defau... | Helper function to convert the given input price into integers (cents
count). :obj:`int`, :obj:`float` and :obj:`str` are supported
:param variant: Price
:param re.compile regex: Regex to convert str into price. The re should
contain two named groups `euro` and `cent`
:para... |
1,716 | def margin(
self,
axis=None,
weighted=True,
include_missing=False,
include_transforms_for_dims=None,
prune=False,
include_mr_cat=False,
):
axis = self._calculate_correct_axis_for_cube(axis)
hs_dims = self._hs_dims_for_cube(include_tra... | Return ndarray representing slice margin across selected axis.
A margin (or basis) can be calculated for a contingency table, provided
that the dimensions of the desired directions are marginable. The
dimensions are marginable if they represent mutualy exclusive data,
such as true categ... |
1,717 | def get_entry_categories(self, category_nodes):
categories = []
for category_node in category_nodes:
domain = category_node.attrib.get()
if domain == :
categories.append(self.categories[category_node.text])
return categories | Return a list of entry's categories
based on imported categories. |
1,718 | def get_input(problem):
input_data = load_input()
pbsplit = problem.split(":")
problem_input = input_data[][pbsplit[0]]
if isinstance(problem_input, dict) and "filename" in problem_input and "value" in problem_input:
if len(pbsplit) > 1 and pbsplit[1] == :
return problem_input["... | Returns the specified problem answer in the form
problem: problem id
Returns string, or bytes if a file is loaded |
1,719 | def solubility_parameter(self):
rNH3
return solubility_parameter(T=self.T, Hvapm=self.Hvapm, Vml=self.Vml,
Method=self.solubility_parameter_method,
CASRN=self.CAS) | r'''Solubility parameter of the chemical at its
current temperature and pressure, in units of [Pa^0.5].
.. math::
\delta = \sqrt{\frac{\Delta H_{vap} - RT}{V_m}}
Calculated based on enthalpy of vaporization and molar volume.
Normally calculated at STP. For uses of this prop... |
1,720 | def withAttribute(*args,**attrDict):
if args:
attrs = args[:]
else:
attrs = attrDict.items()
attrs = [(k,v) for k,v in attrs]
def pa(s,l,tokens):
for attrName,attrValue in attrs:
if attrName not in tokens:
raise ParseException(s,l,"no matching att... | Helper to create a validating parse action to be used with start
tags created with :class:`makeXMLTags` or
:class:`makeHTMLTags`. Use ``withAttribute`` to qualify
a starting tag with a required attribute value, to avoid false
matches on common tags such as ``<TD>`` or ``<DIV>``.
Call ``withAttribut... |
1,721 | def register_blueprints(app, application_package_name=None, blueprint_directory=None):
if not application_package_name:
application_package_name =
if not blueprint_directory:
blueprint_directory = os.path.join(os.getcwd(), application_package_name)
blueprint_directories = get_child_d... | Register Flask blueprints on app object |
1,722 | def UpdateFlow(self,
client_id,
flow_id,
flow_obj=db.Database.unchanged,
flow_state=db.Database.unchanged,
client_crash_info=db.Database.unchanged,
pending_termination=db.Database.unchanged,
processing... | Updates flow objects in the database. |
1,723 | def remove_accounts_from_group(accounts_query, group):
query = accounts_query.filter(date_deleted__isnull=True)
for account in query:
remove_account_from_group(account, group) | Remove accounts from group. |
1,724 | def __read_device(self):
state = XinputState()
res = self.manager.xinput.XInputGetState(
self.__device_number, ctypes.byref(state))
if res == XINPUT_ERROR_SUCCESS:
return state
if res != XINPUT_ERROR_DEVICE_NOT_CONNECTED:
raise RuntimeError(
... | Read the state of the gamepad. |
1,725 | def execute_catch(c, sql, vars=None):
try:
c.execute(sql, vars)
except Exception as err:
cmd = sql.split(, 1)[0]
log.error("Error executing %s: %s", cmd, err) | Run a query, but ignore any errors. For error recovery paths where the error handler should not raise another. |
1,726 | def create_intent(self,
parent,
intent,
language_code=None,
intent_view=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
... | Creates an intent in the specified agent.
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2.IntentsClient()
>>>
>>> parent = client.project_agent_path('[PROJECT]')
>>>
>>> # TODO: Initialize ``intent``:
... |
1,727 | def from_bytes(OverwinterTx, byte_string):
header = byte_string[0:4]
group_id = byte_string[4:8]
if header != b or group_id != b:
raise ValueError(
.format(b.hex(),
b.hex(),
header.hex(),
... | byte-like -> OverwinterTx |
1,728 | def add_to_stage(self, paths):
cmd = self._command.add(paths)
(code, stdout, stderr) = self._exec(cmd)
if code:
raise errors.VCSError(t add paths to VCS. Process exited with code %d and message: %s' % (
code, stderr + stdout)) | Stage given files
:param paths:
:return: |
1,729 | def convert_runsummary_to_json(
df, comment=, prefix=
):
data_field = []
comment += ", by {}".format(getpass.getuser())
for det_id, det_data in df.groupby():
runs_field = []
data_field.append({"DetectorId": det_id, "Runs": runs_field})
for run, run_data in det_data.grou... | Convert a Pandas DataFrame with runsummary to JSON for DB upload |
1,730 | def add_method(obj, func, name=None):
if name is None:
name = func.__name__
if sys.version_info < (3,):
method = types.MethodType(func, obj, obj.__class__)
else:
method = types.MethodType(func, obj)
setattr(obj, name, method) | Adds an instance method to an object. |
1,731 | def _histogram_move_keys_by_game(sess, ds, batch_size=8*1024):
ds = ds.batch(batch_size)
ds = ds.map(lambda x: tf.strings.substr(x, 0, 12))
iterator = ds.make_initializable_iterator()
sess.run(iterator.initializer)
get_next = iterator.get_next()
h = collections.Counter()
try:
... | Given dataset of key names, return histogram of moves/game.
Move counts are written by the game players, so
this is mostly useful for repair or backfill.
Args:
sess: TF session
ds: TF dataset containing game move keys.
batch_size: performance tuning parameter |
1,732 | def _limit_features(self, X, vocabulary, high=None, low=None,
limit=None):
if high is None and low is None and limit is None:
return X, set()
dfs = X.map(_document_frequency).sum()
tfs = X.map(lambda x: np.asarray(x.sum(axis=0))).sum().ravel... | Remove too rare or too common features.
Prune features that are non zero in more samples than high or less
documents than low, modifying the vocabulary, and restricting it to
at most the limit most frequent.
This does not prune samples with zero features. |
1,733 | def _parse_args(self,freqsAngles=True,_firstFlip=False,*args):
from galpy.orbit import Orbit
RasOrbit= False
integrated= True
if len(args) == 5 or len(args) == 3:
raise IOError("Must specify phi for actionAngleIsochroneApprox")
if len(args) == 6 or len(args... | Helper function to parse the arguments to the __call__ and actionsFreqsAngles functions |
1,734 | def get_user_presence(self, userid):
response, status_code = self.__pod__.Presence.get_v2_user_uid_presence(
sessionToken=self.__session__,
uid=userid
).result()
self.logger.debug( % (status_code, response))
return status_code, response | check on presence of a user |
1,735 | def get_child_by_name(parent, name):
def iterate_children(widget, name):
if widget.get_name() == name:
return widget
try:
for w in widget.get_children():
result = iterate_children(w, name)
if result is not None:
re... | Iterate through a gtk container, `parent`,
and return the widget with the name `name`. |
1,736 | def add_item_metadata(self, handle, key, value):
_mkdir_if_missing(self._metadata_fragments_abspath)
prefix = self._handle_to_fragment_absprefixpath(handle)
fpath = prefix + .format(key)
_put_obj(fpath, value) | Store the given key:value pair for the item associated with handle.
:param handle: handle for accessing an item before the dataset is
frozen
:param key: metadata key
:param value: metadata value |
1,737 | def create_embeded_pkcs7_signature(data, cert, key):
assert isinstance(data, bytes)
assert isinstance(cert, str)
try:
pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key)
signcert = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
except crypto.Error as e:
raise exc... | Creates an embeded ("nodetached") pkcs7 signature.
This is equivalent to the output of::
openssl smime -sign -signer cert -inkey key -outform DER -nodetach < data
:type data: bytes
:type cert: str
:type key: str |
1,738 | def convert_to_consumable_types (self, project, name, prop_set, sources, only_one=False):
if __debug__:
from .targets import ProjectTarget
assert isinstance(name, basestring) or name is None
assert isinstance(project, ProjectTarget)
assert isinstance(prop... | Attempts to convert 'source' to the types that this generator can
handle. The intention is to produce the set of targets can should be
used when generator is run.
only_one: convert 'source' to only one of source types
if there's more that one possibility, re... |
1,739 | def set_host_finished(self, scan_id, target, host):
finished_hosts = self.scans_table[scan_id][]
finished_hosts[target].extend(host)
self.scans_table[scan_id][] = finished_hosts | Add the host in a list of finished hosts |
1,740 | def dist(src, tar, method=sim_levenshtein):
if callable(method):
return 1 - method(src, tar)
else:
raise AttributeError( + str(method)) | Return a distance between two strings.
This is a generalized function for calling other distance functions.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
method : function
Specifies the similarity metric (:py:func:`s... |
1,741 | def _select_index(self, row, col):
nr, nc = self._size
nr = nr-1
nc = nc-1
if (row > nr and col >= nc) or (row >= nr and col > nc):
self._select_index(0, 0)
elif (row <= 0 and col < 0) or (row < 0 and col <= 0):
self._select_i... | Change the selection index, and make sure it stays in the right range
A little more complicated than just dooing modulo the number of row columns
to be sure to cycle through all element.
horizontaly, the element are maped like this :
to r <-- a b c d e f --> to g
to f <-- g h i... |
1,742 | def addFilter(self, filterMethod=FILTER_METHOD_AND, **kwargs):
AND
filterMethod = filterMethod.upper()
if filterMethod not in FILTER_METHODS:
raise ValueError( %(str(filterMethod), repr(FILTER_METHODS)))
self.filters.append((filterMethod, kwargs)) | addFilter - Add a filter to this query.
@param filterMethod <str> - The filter method to use (AND or OR), default: 'AND'
@param additional args - Filter arguments. @see QueryableListBase.filter
@raises ValueError if filterMethod is not one of known methods. |
1,743 | def lbd_to_XYZ_jac(*args,**kwargs):
out= sc.zeros((6,6))
if len(args) == 3:
l,b,D= args
vlos, pmll, pmbb= 0., 0., 0.
elif len(args) == 6:
l,b,D,vlos,pmll,pmbb= args
if kwargs.get(,False):
l*= _DEGTORAD
b*= _DEGTORAD
cl= sc.cos(l)
sl= sc.sin(l)
cb=... | NAME:
lbd_to_XYZ_jac
PURPOSE:
calculate the Jacobian of the Galactic spherical coordinates to Galactic rectangular coordinates transformation
INPUT:
l,b,D- Galactic spherical coordinates
vlos,pmll,pmbb- Galactic spherical velocities (some as proper motions)
if 6 inputs:... |
1,744 | def get_alert(thing_name, key, session=None):
return _request(, .format(thing_name), params={: key}, session=session) | Set an alert on a thing with the given condition |
1,745 | def show_lbaas_healthmonitor(self, lbaas_healthmonitor, **_params):
return self.get(self.lbaas_healthmonitor_path % (lbaas_healthmonitor),
params=_params) | Fetches information for a lbaas_healthmonitor. |
1,746 | def handle_url_build_error(self, error: Exception, endpoint: str, values: dict) -> str:
for handler in self.url_build_error_handlers:
result = handler(error, endpoint, values)
if result is not None:
return result
raise error | Handle a build error.
Ideally this will return a valid url given the error endpoint
and values. |
1,747 | def tdSensorValue(self, protocol, model, sid, datatype):
value = create_string_buffer(20)
timestamp = c_int()
self._lib.tdSensorValue(protocol, model, sid, datatype,
value, sizeof(value), byref(timestamp))
return {: self._to_str(value), : timesta... | Get the sensor value for a given sensor.
:return: a dict with the keys: value, timestamp. |
1,748 | def robust_outer_product(vec_1, vec_2):
mantissa_1, exponents_1 = np.frexp(vec_1)
mantissa_2, exponents_2 = np.frexp(vec_2)
new_mantissas = mantissa_1[None, :] * mantissa_2[:, None]
new_exponents = exponents_1[None, :] + exponents_2[:, None]
return new_mantissas * np.exp2(new_exponents) | Calculates a 'robust' outer product of two vectors that may or may not
contain very small values.
Parameters
----------
vec_1 : 1D ndarray
vec_2 : 1D ndarray
Returns
-------
outer_prod : 2D ndarray. The outer product of vec_1 and vec_2 |
1,749 | def sort_tiers(self, key=lambda x: x.name):
self.tiers.sort(key=key) | Sort the tiers given the key. Example key functions:
Sort according to the tiername in a list:
``lambda x: ['name1', 'name2' ... 'namen'].index(x.name)``.
Sort according to the number of annotations:
``lambda x: len(list(x.get_intervals()))``
:param func key: A key function.... |
1,750 | def business_rule_notification_is_blocked(self, hosts, services):
acknowledged = 0
for src_prob_id in self.source_problems:
if src_prob_id in hosts:
src_prob = hosts[src_prob_id]
else:
src_prob = services[src_pro... | Process business rule notifications behaviour. If all problems have
been acknowledged, no notifications should be sent if state is not OK.
By default, downtimes are ignored, unless explicitly told to be treated
as acknowledgements through with the business_rule_downtime_as_ack set.
:ret... |
1,751 | def generate_single_simulation(self, x):
if x:
self.__rng = np.random.RandomState(x)
time_points, species_over_time = self._gssa(self.__initial_conditions, self.__t_max)
descriptors = []
for i, s in enumerate(self.__species):
... | Generate a single SSA simulation
:param x: an integer to reset the random seed. If None, the initial random number generator is used
:return: a list of :class:`~means.simulation.Trajectory` one per species in the problem
:rtype: list[:class:`~means.simulation.Trajectory`] |
1,752 | def create_untl_xml_subelement(parent, element, prefix=):
subelement = SubElement(parent, prefix + element.tag)
if element.content is not None:
subelement.text = element.content
if element.qualifier is not None:
subelement.attrib["qualifier"] = element.qualifier
if element.children ... | Create a UNTL XML subelement. |
1,753 | def _bundle_generic(bfile, addhelper, fmt, reffmt, data_dir):
ext = converters.get_format_extension(fmt)
refext = refconverters.get_format_extension(reffmt)
subdir = + fmt + + reffmt
readme_path = os.path.join(subdir, )
addhelper(bfile, readme_path, _create_readme(fmt, reffmt))
for nam... | Loop over all basis sets and add data to an archive
Parameters
----------
bfile : object
An object that gets passed through to the addhelper function
addhelper : function
A function that takes bfile and adds data to the bfile
fmt : str
Format of the basis set to create
r... |
1,754 | def snapshot(self):
self._snapshot = {
: self.muted,
: self.volume,
: self.stream
}
_LOGGER.info(, self.friendly_name) | Snapshot current state. |
1,755 | def transform_q(q, query):
for i, child in enumerate(q.children):
if isinstance(child, Q):
transform_q(child, query)
else:
where_node = query.build_filter(child)
q.children[i] = where_node | Replaces (lookup, value) children of Q with equivalent WhereNode objects.
This is a pre-prep of our Q object, ready for later rendering into SQL.
Modifies in place, no need to return.
(We could do this in render_q, but then we'd have to pass the Query object
from ConditionalAggregate down into SQLCond... |
1,756 | def migrate_passwords_to_leader_storage(self, excludes=None):
if not is_leader():
log("Skipping password migration as not the lead unit",
level=DEBUG)
return
dirname = os.path.dirname(self.root_passwd_file_template)
path = os.path.join(dirname, )
... | Migrate any passwords storage on disk to leader storage. |
1,757 | def main(sample_id, assembly_file, minsize):
logger.info("Starting assembly file processing")
warnings = []
fails = ""
logger.info("Starting assembly parsing")
assembly_obj = Assembly(assembly_file, 0, 0,
sample_id, minsize)
if in assembly_file:
... | Main executor of the process_mapping template.
Parameters
----------
sample_id : str
Sample Identification string.
assembly: str
Path to the fatsa file generated by the assembler.
minsize: str
Min contig size to be considered a complete ORF |
1,758 | def _connect(self):
try:
if self.ca_cert is None or self.certfile is None or \
self.keyfile is None or self.crlfile is None:
client = pymongo.MongoClient(self.host,
... | Try to connect to the database.
Raises:
:exc:`~ConnectionError`: If the connection to the database
fails.
:exc:`~AuthenticationError`: If there is a OperationFailure due to
Authentication failure after connecting to the database.
:exc:`~Config... |
1,759 | def exception_wrapper(f):
@wraps(f)
def wrapper(*args, **kwds):
try:
return f(*args, **kwds)
except dbus.exceptions.DBusException as err:
_args = err.args
raise PyMPRISException(*_args)
return wrapper | Decorator to convert dbus exception to pympris exception. |
1,760 | def set_affinity_matrix(self, affinity_mat):
affinity_mat = check_array(affinity_mat, accept_sparse=sparse_formats)
if affinity_mat.shape[0] != affinity_mat.shape[1]:
raise ValueError("affinity matrix is not square")
self.affinity_matrix = affinity_mat | Parameters
----------
affinity_mat : sparse matrix (N_obs, N_obs).
The adjacency matrix to input. |
1,761 | def encrypt(self):
value = self.parameters.get("Plaintext")
if isinstance(value, six.text_type):
value = value.encode()
return json.dumps({"CiphertextBlob": base64.b64encode(value).decode("utf-8"), : }) | We perform no encryption, we just encode the value as base64 and then
decode it in decrypt(). |
1,762 | def find_additional_rels(self, all_models):
for model_name, model in iteritems(all_models):
if model_name != self.name:
for field_name in model.field_names:
field = model.fields[field_name]
if field.field_type == s... | Attempts to scan for additional relationship fields for this model based on all of the other models'
structures and relationships. |
1,763 | def get_instance_property(instance, property_name):
name = get_name(instance)
while True:
try:
value = getattr(instance, property_name)
if value is not None:
break
print(f"retrieving {property_name} on {name} produced None, retrying")
time.sleep(RETRY_INTERVAL_SEC)
inst... | Retrieves property of an instance, keeps retrying until getting a non-None |
1,764 | def memoizedmethod(method):
method_name = method.__name__
@wraps(method)
def patched(self, *args, **kwargs):
try:
return self._cache[method_name]
except KeyError:
result = self._cache[method_name] = method(
self, *args... | Decorator that caches method result.
Args:
method (function): Method
Returns:
function: Memoized method.
Notes:
Target method class needs as "_cache" attribute (dict).
It is the case of "ObjectIOBase" and all its subclasses. |
1,765 | def ReadTrigger(self, trigger_link, options=None):
if options is None:
options = {}
path = base.GetPathFromLink(trigger_link)
trigger_id = base.GetResourceIdOrFullNameFromLink(trigger_link)
return self.Read(path, , trigger_id, None, options) | Reads a trigger.
:param str trigger_link:
The link to the trigger.
:param dict options:
The request options for the request.
:return:
The read Trigger.
:rtype:
dict |
1,766 | def shadow_hash(crypt_salt=None, password=None, algorithm=):
*My5alTMyP@asswd
return salt.utils.pycrypto.gen_hash(crypt_salt, password, algorithm) | Generates a salted hash suitable for /etc/shadow.
crypt_salt : None
Salt to be used in the generation of the hash. If one is not
provided, a random salt will be generated.
password : None
Value to be salted and hashed. If one is not provided, a random
password will be generated... |
1,767 | def check_type_and_values_of_specification_dict(specification_dict,
unique_alternatives):
for key in specification_dict:
specification = specification_dict[key]
if isinstance(specification, str):
if specification not in ["all_same", "a... | Verifies that the values of specification_dict have the correct type, have
the correct structure, and have valid values (i.e. are actually in the set
of possible alternatives). Will raise various errors if / when appropriate.
Parameters
----------
specification_dict : OrderedDict.
Keys are ... |
1,768 | def fit(self, X, y=None):
self.opt_ = None
self.cputime_ = None
self.iters_ = None
self.duality_gap_ = None
self.sample_covariance_ = None
self.lam_scale_ = None
self.is_fitted_ = False
X = check_array(X, ensure_min_fe... | Fits the GraphLasso covariance model to X.
Closely follows sklearn.covariance.graph_lasso.GraphLassoCV.
Parameters
----------
X : ndarray, shape (n_samples, n_features)
Data from which to compute the covariance estimate |
1,769 | def com_google_fonts_check_fstype(ttFont):
value = ttFont[].fsType
if value != 0:
FSTYPE_RESTRICTIONS = {
0x0002: ("* The font must not be modified, embedded or exchanged in"
" any manner without first obtaining permission of"
" the legal owner."),
0x0004: ("The font... | Checking OS/2 fsType.
Fonts must have their fsType field set to zero.
This setting is known as Installable Embedding, meaning
that none of the DRM restrictions are enabled on the fonts.
More info available at:
https://docs.microsoft.com/en-us/typography/opentype/spec/os2#fstype |
1,770 | def _parse_hparams(hparams):
prefixes = ["agent_", "optimizer_", "runner_", "replay_buffer_"]
ret = []
for prefix in prefixes:
ret_dict = {}
for key in hparams.values():
if prefix in key:
par_name = key[len(prefix):]
ret_dict[par_name] = hparams.get(key)
ret.append(ret_dict)
... | Split hparams, based on key prefixes.
Args:
hparams: hyperparameters
Returns:
Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer. |
1,771 | def generate(env):
link.generate(env)
if env[] == :
env[] = SCons.Util.CLVar()
env[] =
env[] =
env[] =
| Add Builders and construction variables for gnulink to an Environment. |
1,772 | def get_data_length(self):
if not self._initialized:
raise pycdlibexception.PyCdlibInternalError()
if self.inode is not None:
return self.inode.get_data_length()
return self.data_length | A method to get the length of the data that this Directory Record
points to.
Parameters:
None.
Returns:
The length of the data that this Directory Record points to. |
1,773 | def ProbGreater(self, x):
t = [prob for (val, prob) in self.d.iteritems() if val > x]
return sum(t) | Probability that a sample from this Pmf exceeds x.
x: number
returns: float probability |
1,774 | def pack(self, remaining_size):
arguments_count, payload = self.pack_data(remaining_size - self.header_size)
payload_length = len(payload)
if payload_length % 8 != 0:
payload += b"\x00" * (8 - payload_length % 8)
self.header = PartHeader(self.kind, self.at... | Pack data of part into binary format |
1,775 | def decrypt_subtitle(self, subtitle):
return self.decrypt(self._build_encryption_key(int(subtitle.id)),
subtitle[][0].text.decode(),
subtitle[][0].text.decode()) | Decrypt encrypted subtitle data in high level model object
@param crunchyroll.models.Subtitle subtitle
@return str |
1,776 | def clinvar_submission_header(submission_objs, csv_type):
complete_header = {}
custom_header = {}
if csv_type == :
complete_header = CLINVAR_HEADER
else:
complete_header = CASEDATA_HEADER
for header_key, header_value in complete_header.items():
for clinvar_obj in... | Determine which fields to include in csv header by checking a list of submission objects
Args:
submission_objs(list): a list of objects (variants or casedata) to include in a csv file
csv_type(str) : 'variant_data' or 'case_data'
Returns:
custom_header(dict): A dict... |
1,777 | def https_connection(self):
endpoint = self.endpoint
host, remainder = endpoint.split(, 1)
port = remainder
if in remainder:
port, _ = remainder.split(, 1)
conn = HTTPSConnection(
host, int(port),
context=self._get_ssl(self.cacert),
... | Return an https connection to this Connection's endpoint.
Returns a 3-tuple containing::
1. The :class:`HTTPSConnection` instance
2. Dictionary of auth headers to be used with the connection
3. The root url path (str) to be used for requests. |
1,778 | def add_number_widget(self, ref, x=1, value=1):
if ref not in self.widgets:
widget = widgets.NumberWidget(screen=self, ref=ref, x=x, value=value)
self.widgets[ref] = widget
return self.widgets[ref] | Add Number Widget |
1,779 | def _handle_ticker(self, dtype, data, ts):
self.log.debug("_handle_ticker: %s - %s - %s", dtype, data, ts)
channel_id, *data = data
channel_identifier = self.channel_directory[channel_id]
entry = (data, ts)
self.tickers[channel_identifier].put(entry) | Adds received ticker data to self.tickers dict, filed under its channel
id.
:param dtype:
:param data:
:param ts:
:return: |
1,780 | def singularity_build(script=None, src=None, dest=None, **kwargs):
singularity = SoS_SingularityClient()
singularity.build(script, src, dest, **kwargs)
return 0 | docker build command. By default a script is sent to the docker build command but
you can also specify different parameters defined inu//docker-py.readthedocs.org/en/stable/api/#build |
1,781 | def _normalized_keys(self, section, items):
normalized = {}
for name, val in items:
key = section + "." + _normalize_name(name)
normalized[key] = val
return normalized | Normalizes items to construct a dictionary with normalized keys.
This routine is where the names become keys and are made the same
regardless of source - configuration files or environment. |
1,782 | def _make_publisher(catalog_or_dataset):
level = catalog_or_dataset
keys = [k for k in ["publisher_name", "publisher_mbox"] if k in level]
if keys:
level["publisher"] = {
key.replace("publisher_", ""): level.pop(key) for key in keys
}
return level | De estar presentes las claves necesarias, genera el diccionario
"publisher" a nivel catálogo o dataset. |
1,783 | def transitions_for(self, roles=None, actor=None, anchors=[]):
proxy = self.obj.access_for(roles, actor, anchors)
return {name: transition for name, transition in self.transitions(current=False).items()
if name in proxy} | For use on :class:`~coaster.sqlalchemy.mixins.RoleMixin` classes:
returns currently available transitions for the specified
roles or actor as a dictionary of name: :class:`StateTransitionWrapper`. |
1,784 | def strftime(dt, fmt):
if _illegal_s.search(fmt):
raise TypeError("This strftime implementation does not handle %s")
if dt.year > 1900:
return dt.strftime(fmt)
fmt = fmt.replace(, )\
.replace(, str(dt.year))\
.replace(, .format(dt.year)[-2:])
year = dt.ye... | `strftime` implementation working before 1900 |
1,785 | def parse_options_header(value, multiple=False):
if not value:
return "", {}
result = []
value = "," + value.replace("\n", ",")
while value:
match = _option_header_start_mime_type.match(value)
if not match:
break
result.append(match.group(1))
... | Parse a ``Content-Type`` like header into a tuple with the content
type and the options:
>>> parse_options_header('text/html; charset=utf8')
('text/html', {'charset': 'utf8'})
This should not be used to parse ``Cache-Control`` like headers that use
a slightly different format. For these headers u... |
1,786 | def rename_ligand(self,ligand_name,mol_file):
self.universe.ligand = self.universe.select_atoms(ligand_name)
self.universe.ligand.residues.resnames = "LIG"
self.universe.ligand.resname = "LIG"
if mol_file is None:
self.universe.ligand.write("lig.pdb")
... | Get an atom selection for the selected from both topology and trajectory. Rename the ligand LIG
to help with ligand names that are not standard, e.g. contain numbers.
Takes:
* ligand_name * - MDAnalysis atom selection for the ligand selected by user
Output:
... |
1,787 | def _optimize_with_progs(format_module, filename, image_format):
filesize_in = os.stat(filename).st_size
report_stats = None
for func in format_module.PROGRAMS:
if not getattr(Settings, func.__name__):
continue
report_stats = _optimize_image_external(
filename, ... | Use the correct optimizing functions in sequence.
And report back statistics. |
1,788 | def push(self, item):
self.server.lpush(self.key, self._encode_item(item)) | Push an item |
1,789 | def get_prep_value(self, value):
if isinstance(value, JSON.JsonDict):
return json.dumps(value, cls=JSON.Encoder)
if isinstance(value, JSON.JsonList):
return value.json_string
if isinstance(value, JSON.JsonString):
return json.dumps(value)
retu... | The psycopg adaptor returns Python objects,
but we also have to handle conversion ourselves |
1,790 | def convert_radian(coord, *variables):
if any(v.attrs.get() == for v in variables):
return coord * 180. / np.pi
return coord | Convert the given coordinate from radian to degree
Parameters
----------
coord: xr.Variable
The variable to transform
``*variables``
The variables that are on the same unit.
Returns
-------
xr.Variable
The transformed variable if one of the given `variables` has uni... |
1,791 | def _print_foreign_playlist_message(self):
self.operation_mode = self.window_mode = NORMAL_MODE
self.refreshBody()
txt=.format(self._cnf.foreign_filename_only_no_extension,
self._cnf.stations_filename_only_no_extension)
self._show_help(txt, FOREIGN_P... | reset previous message |
1,792 | def observe(matcher):
@functools.wraps(matcher)
def observer(self, subject, *expected, **kw):
if hasattr(self, ):
self.before(subject, *expected, **kw)
result = matcher(self, subject, *expected, **kw)
i... | Internal decorator to trigger operator hooks before/after
matcher execution. |
1,793 | def trace(
data, name, format=, datarange=(None, None), suffix=, path=, rows=1, columns=1,
num=1, last=True, fontmap = None, verbose=1):
if fontmap is None:
fontmap = {1: 10, 2: 8, 3: 6, 4: 5, 5: 4}
standalone = rows == 1 and columns == 1 and num == 1
if standalone:
... | Generates trace plot from an array of data.
:Arguments:
data: array or list
Usually a trace from an MCMC sample.
name: string
The name of the trace.
datarange: tuple or list
Preferred y-range of trace (defaults to (None,None)).
format (optional... |
1,794 | def formatMessageForBuildResults(self, mode, buildername, buildset, build, master, previous_results, blamelist):
ss_list = buildset[]
results = build[]
ctx = dict(results=build[],
mode=mode,
buildername=buildername,
workername=bu... | Generate a buildbot mail message and return a dictionary
containing the message body, type and subject. |
1,795 | def update_user(resource_root, user):
return call(resource_root.put,
% (USERS_PATH, user.name), ApiUser, data=user) | Update a user.
Replaces the user's details with those provided.
@param resource_root: The root Resource object
@param user: An ApiUser object
@return: An ApiUser object |
1,796 | def Clouds(name=None, deterministic=False, random_state=None):
if name is None:
name = "Unnamed%s" % (ia.caller_name(),)
return meta.SomeOf((1, 2), children=[
CloudLayer(
intensity_mean=(196, 255), intensity_freq_exponent=(-2.5, -2.0), intensity_coarse_scale=10,
alp... | Augmenter to draw clouds in images.
This is a wrapper around ``CloudLayer``. It executes 1 to 2 layers per image, leading to varying densities
and frequency patterns of clouds.
This augmenter seems to be fairly robust w.r.t. the image size. Tested with ``96x128``, ``192x256``
and ``960x1280``.
dt... |
1,797 | def points(self, points):
if not isinstance(points, np.ndarray):
raise TypeError()
x = np.unique(points[:,0])
y = np.unique(points[:,1])
z = np.unique(points[:,2])
nx, ny, nz = len(x), len(y), len(z)
dx, dy, dz = np.unique(np.diff(x)... | set points without copying |
1,798 | def encode(in_bytes):
final_zero = True
out_bytes = []
idx = 0
search_start_idx = 0
for in_char in in_bytes:
if in_char == :
final_zero = True
out_bytes.append(chr(idx - search_start_idx + 1))
out_bytes.append(in_bytes[search_start_idx:idx])
... | Encode a string using Consistent Overhead Byte Stuffing (COBS).
Input is any byte string. Output is also a byte string.
Encoding guarantees no zero bytes in the output. The output
string will be expanded slightly, by a predictable amount.
An empty string is encoded to '\\x01 |
1,799 | def run(self):
super().run()
if not isinstance(self._executable, Program):
raise ValueError("Please `load` an appropriate executable.")
quil_program = self._executable
trials = quil_program.num_shots
classical_addresses = get_clas... | Run a Quil program on the QVM multiple times and return the values stored in the
classical registers designated by the classical_addresses parameter.
:return: An array of bitstrings of shape ``(trials, len(classical_addresses))`` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.