Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
10,800 | def is_visit_primitive(obj):
from .base import visit
if (isinstance(obj, tuple(PRIMITIVE_TYPES)) and not isinstance(obj, STR)
and not isinstance(obj, bytes)):
return True
if (isinstance(obj, CONTAINERS) and not isinstance(obj, STR) and not
isinstance(obj, bytes)):
return... | Returns true if properly visiting the object returns only the object itself. |
10,801 | def _handle_inotify_event(self, wd):
b = os.read(wd, 1024)
if not b:
return
self.__buffer += b
while 1:
length = len(self.__buffer)
if length < _STRUCT_HEADER_LENGTH:
_LOGGER.debug("Not enough bytes for a header.")
... | Handle a series of events coming-in from inotify. |
10,802 | def part(self):
part_id = self._json_data[]
return self._client.part(pk=part_id, category=self._json_data[]) | Retrieve the part that holds this Property.
:returns: The :class:`Part` associated to this property
:raises APIError: if the `Part` is not found |
10,803 | def _readResponse(self):
traps = []
reply_word = None
while reply_word != :
reply_word, words = self._readSentence()
if reply_word == :
traps.append(TrapError(**words))
elif reply_word in (, ) and words:
yield words
... | Yield each row of response untill !done is received.
:throws TrapError: If one !trap is received.
:throws MultiTrapError: If > 1 !trap is received. |
10,804 | def responds(self):
contacted_text = self._contacted_xpb.\
get_text_(self.profile_tree).lower()
if not in contacted_text:
return contacted_text.strip().replace(, ) | :returns: The frequency with which the user associated with this profile
responds to messages. |
10,805 | def save(self, save_json=True, save_xml=True):
if self.layer_is_file_based:
if save_json:
self.write_to_file(self.json_uri)
if save_xml:
self.write_to_file(self.xml_uri)
else:
self.write_to_db(save_json, save_xml) | Saves the metadata json and/or xml to a file or DB.
:param save_json: flag to save json
:type save_json: bool
:param save_xml: flag to save xml
:type save_xml: bool |
10,806 | def reset_env(exclude=[]):
if os.getenv(env.INITED):
wandb_keys = [key for key in os.environ.keys() if key.startswith(
) and key not in exclude]
for key in wandb_keys:
del os.environ[key]
return True
else:
return False | Remove environment variables, used in Jupyter notebooks |
10,807 | def str_replace(x, pat, repl, n=-1, flags=0, regex=False):
sl = _to_string_sequence(x).replace(pat, repl, n, flags, regex)
return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl) | Replace occurences of a pattern/regex in a column with some other string.
:param str pattern: string or a regex pattern
:param str replace: a replacement string
:param int n: number of replacements to be made from the start. If -1 make all replacements.
:param int flags: ??
:param bool regex: If Tr... |
10,808 | def updatePassword(self,
user,
currentPassword,
newPassword):
return self.__post(,
data={
: user,
: currentPassword,
... | Change the password of a user. |
10,809 | def _loadData(self, data):
self._data = data
for elem in data:
id = utils.lowerFirst(elem.attrib[])
if id in self._settings:
self._settings[id]._loadData(elem)
continue
self._settings[id] = Setting(self._server, elem, self._ini... | Load attribute values from Plex XML response. |
10,810 | def ghuser_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
app = inliner.document.settings.env.app
ref = + text
node = nodes.reference(rawtext, text, refuri=ref, **options)
return [node], [] | Link to a GitHub user.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:param rawtext: The entire markup snippet, with role.
:param text: The text marked wit... |
10,811 | def OnShowFindReplace(self, event):
data = wx.FindReplaceData(wx.FR_DOWN)
dlg = wx.FindReplaceDialog(self.grid, data, "Find & Replace",
wx.FR_REPLACEDIALOG)
dlg.data = data
dlg.Show(True) | Calls the find-replace dialog |
10,812 | def set_content(self, data):
content = self._get_content(data, )
if content == :
content = self._get_content(data, )
if content == :
if data.get():
content = data.get()
return content | handle the content from the data
:param data: contains the data from the provider
:type data: dict
:rtype: string |
10,813 | def SetSerializersProfiler(self, serializers_profiler):
self._serializers_profiler = serializers_profiler
if self._storage_file:
self._storage_file.SetSerializersProfiler(serializers_profiler) | Sets the serializers profiler.
Args:
serializers_profiler (SerializersProfiler): serializers profiler. |
10,814 | def _filtdim(items, shape, dim, nsl):
normshape = tuple(stop - start for start, stop in shape)
nsl_type = type(nsl)
newitems = list()
num = reduce(operator.mul, normshape[:dim+1])
size = len(items) // num
n = normshape[dim]
if nsl_type is int:
for i in range(num):... | Return items, shape filtered by a dimension slice. |
10,815 | def put_encryption_materials(self, cache_key, encryption_materials, plaintext_length, entry_hints=None):
return CryptoMaterialsCacheEntry(cache_key=cache_key, value=encryption_materials) | Does not add encryption materials to the cache since there is no cache to which to add them.
:param bytes cache_key: Identifier for entries in cache
:param encryption_materials: Encryption materials to add to cache
:type encryption_materials: aws_encryption_sdk.materials_managers.EncryptionMate... |
10,816 | def _process_genes(self, limit=None):
LOG.info("Processing genes")
if self.test_mode:
graph = self.testgraph
else:
graph = self.graph
model = Model(graph)
line_counter = 0
raw = .join((self.rawdir, self.files[][]))
geno = Genotype... | This table provides the ZFIN gene id, the SO type of the gene,
the gene symbol, and the NCBI Gene ID.
Triples created:
<gene id> a class
<gene id> rdfs:label gene_symbol
<gene id> equivalent class <ncbi_gene_id>
:param limit:
:return: |
10,817 | def setup(app):
global _is_sphinx
_is_sphinx = True
app.add_config_value(, False, )
app.add_source_parser(, M2RParser)
app.add_directive(, MdInclude) | When used for spinx extension. |
10,818 | def add_handler(
self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int
) -> None:
raise NotImplementedError() | Registers the given handler to receive the given events for ``fd``.
The ``fd`` argument may either be an integer file descriptor or
a file-like object with a ``fileno()`` and ``close()`` method.
The ``events`` argument is a bitwise or of the constants
``IOLoop.READ``, ``IOLoop.WRITE``,... |
10,819 | def get_self_host(request_data):
if in request_data:
current_host = request_data[]
elif in request_data:
current_host = request_data[]
else:
raise Exception()
if in current_host:
current_host_data = current_host.split()
... | Returns the current host.
:param request_data: The request as a dict
:type: dict
:return: The current host
:rtype: string |
10,820 | def list_provincies(self, gewest=2):
try:
gewest_id = gewest.id
except AttributeError:
gewest_id = gewest
def creator():
return [Provincie(p[0], p[1], Gewest(p[2])) for p in self.provincies if p[2] == gewest_id]
if self.caches[].is_configure... | List all `provincies` in a `gewest`.
:param gewest: The :class:`Gewest` for which the \
`provincies` are wanted.
:param integer sort: What field to sort on.
:rtype: A :class:`list` of :class:`Provincie`. |
10,821 | def match(self, objects: List[Any]) -> bool:
s = self._make_string(objects)
m = self._compiled_expression.match(s)
return m is not None | Return True if the list of objects matches the expression. |
10,822 | def rmdir_p(self):
try:
self.rmdir()
except OSError:
_, e, _ = sys.exc_info()
if e.errno != errno.ENOTEMPTY and e.errno != errno.EEXIST:
raise
return self | Like :meth:`rmdir`, but does not raise an exception if the
directory is not empty or does not exist. |
10,823 | def make_back_notes(self, body):
for notes in self.article.root.xpath():
notes_sec = deepcopy(notes.find())
notes_sec.tag =
notes_sec.attrib[] =
body.append(notes_sec) | The notes element in PLoS articles can be employed for posting notices
of corrections or adjustments in proof. The <notes> element has a very
diverse content model, but PLoS practice appears to be fairly
consistent: a single <sec> containing a <title> and a <p> |
10,824 | def detect(self):
if PY3:
import subprocess
else:
import commands as subprocess
try:
theip = subprocess.getoutput(self.opts_command)
except Exception:
theip = None
self.set_current_value(theip)
return theip | Detect and return the IP address. |
10,825 | def error_msg_wx(msg, parent=None):
dialog =wx.MessageDialog(parent = parent,
message = msg,
caption = ,
style=wx.OK | wx.CENTRE)
dialog.ShowModal()
dialog.Destroy()
return None | Signal an error condition -- in a GUI, popup a error dialog |
10,826 | def hsepd_pdf(sigma1, sigma2, xi, beta,
sim=None, obs=None, node=None, skip_nan=False):
sim, obs = prepare_arrays(sim, obs, node, skip_nan)
sigmas = _pars_h(sigma1, sigma2, sim)
mu_xi, sigma_xi, w_beta, c_beta = _pars_sepd(xi, beta)
x, mu = obs, sim
a = (x-mu)/sigmas
a_xi = nu... | Calculate the probability densities based on the
heteroskedastic skewed exponential power distribution.
For convenience, the required parameters of the probability density
function as well as the simulated and observed values are stored
in a dictonary:
>>> import numpy
>>> from hydpy import ro... |
10,827 | def from_country(cls, country):
result = cls.list({: })
dc_countries = {}
for dc in result:
if dc[] not in dc_countries:
dc_countries[dc[]] = dc[]
return dc_countries.get(country) | Retrieve the first datacenter id associated to a country. |
10,828 | def get_info(self):
if not self.info:
ci = win32pdh.GetCounterInfo(self.handle, 0)
self.info = {
: ci[0],
: ci[1],
: ci[2],
: ci[3],
: ci[4],
: ci[5],
: ci[6],
... | Get information about the counter
.. note::
GetCounterInfo sometimes crashes in the wrapper code. Fewer crashes
if this is called after sampling data. |
10,829 | def analyze(problem, Y, M=4, print_to_console=False, seed=None):
if seed:
np.random.seed(seed)
D = problem[]
if Y.size % (D) == 0:
N = int(Y.size / D)
else:
print()
exit()
omega = np.zeros([D])
omega[0] = math.floor((N - 1) / (2 * M))
... | Performs the Fourier Amplitude Sensitivity Test (FAST) on model outputs.
Returns a dictionary with keys 'S1' and 'ST', where each entry is a list of
size D (the number of parameters) containing the indices in the same order
as the parameter file.
Parameters
----------
problem : dict
... |
10,830 | def global_matches(self, text):
matches = []
match_append = matches.append
n = len(text)
for lst in [keyword.kwlist,
__builtin__.__dict__.keys(),
self.namespace.keys(),
self.global_namespace.keys()]:
... | Compute matches when text is a simple name.
Return a list of all keywords, built-in functions and names currently
defined in self.namespace or self.global_namespace that match. |
10,831 | def compute(self, runner_results, setup=False, poll=False, ignore_errors=False):
for (host, value) in runner_results.get(, {}).iteritems():
if not ignore_errors and (( in value and bool(value[])) or
( in value and value[] != 0)):
self._increment(, host)
... | walk through all results and increment stats |
10,832 | def debug_variable_node_render(self, context):
try:
output = self.filter_expression.resolve(context)
output = template_localtime(output, use_tz=context.use_tz)
output = localize(output, use_l10n=context.use_l10n)
output = force_text(output)
except Exception as e:
if ... | Like DebugVariableNode.render, but doesn't catch UnicodeDecodeError. |
10,833 | def fan_speed(self, speed: int = None) -> bool:
body = helpers.req_body(self.manager, )
body[] = self.uuid
head = helpers.req_headers(self.manager)
if self.details.get() != :
self.mode_toggle()
else:
if speed is not None:
level = i... | Adjust Fan Speed by Specifying 1,2,3 as argument or cycle
through speeds increasing by one |
10,834 | def get_connection(self, command_name, *keys, **options):
"Get a connection from the pool"
self._checkpid()
try:
connection = self._available_connections.pop()
except IndexError:
connection = self.make_connection()
self._in_use_connections.add(connection)
... | Get a connection from the pool |
10,835 | def headerData(self, section, orientation, role):
if role == QtCore.Qt.DisplayRole:
if orientation == QtCore.Qt.Horizontal:
return self.headers[section] | Get the Header for the columns in the table
Required by view, see :qtdoc:`subclassing<qabstractitemmodel.subclassing>`
:param section: column of header to return
:type section: int |
10,836 | def get_total_size_trans(self, entries):
size = 0
for entry in entries:
if entry[][] > 0:
size += entry[][]
return size | Returns the total size of a collection of entries - transferred.
NOTE: use with har file generated with chrome-har-capturer
:param entries: ``list`` of entries to calculate the total size of. |
10,837 | def version_router(self, request, response, api_version=None, versions={}, not_found=None, **kwargs):
request_version = self.determine_version(request, api_version)
if request_version:
request_version = int(request_version)
versions.get(request_version or False, versions.get... | Intelligently routes a request to the correct handler based on the version being requested |
10,838 | def is_valid(self, request_data, request_id=None, raise_exceptions=False):
self.__error = None
try:
if self.document.get(, None) != :
raise OneLogin_Saml2_ValidationError(
,
OneLogin_Saml2_ValidationError.UNSUPPORT... | Validates the response object.
:param request_data: Request Data
:type request_data: dict
:param request_id: Optional argument. The ID of the AuthNRequest sent by this SP to the IdP
:type request_id: string
:param raise_exceptions: Whether to return false on failure or raise a... |
10,839 | def mk_set_headers(self, data, columns):
columns = tuple(columns)
lens = []
for key in columns:
value_len = max(len(str(each.get(key, ))) for each in data)
lens.append(max(value_len, len(self._get_name(key))))
fmt = self.mk_fmt(*lens)
... | figure out sizes and create header fmt |
10,840 | def _root(path, root):
if root:
return os.path.join(root, os.path.relpath(path, os.path.sep))
else:
return path | Relocate an absolute path to a new root directory. |
10,841 | def __generate_cluster_centers(self, width):
centers = []
default_offset = max(width) * 4.0
for i in range(self.__amount_clusters):
center = [ random.gauss(i * default_offset, width[i] / 2.0) for _ in range(self.__dimension) ]
centers.append(center)
... | !
@brief Generates centers (means in statistical term) for clusters.
@param[in] width (list): Width of generated clusters.
@return (list) Generated centers in line with normal distribution. |
10,842 | def generate_id(self):
if self.use_repeatable_ids:
self.repeatable_id_counter += 1
return .format(self.repeatable_id_counter)
else:
return str(uuid4()) | Generate a fresh id |
10,843 | def _find_keep_files(root, keep):
real_keep = set()
real_keep.add(root)
if isinstance(keep, list):
for fn_ in keep:
if not os.path.isabs(fn_):
continue
fn_ = os.path.normcase(os.path.abspath(fn_))
real_keep.add(fn_)
while True:
... | Compile a list of valid keep files (and directories).
Used by _clean_dir() |
10,844 | def value(self):
val = (round(i / 1000, 3) for i in self.__serial_price(1))
return list(val) | 成交量序列(張)
:rtype: list |
10,845 | def either(self):
if not hasattr(self, ):
return Either(Required(self))
else:
ret = []
groups = [[self]]
while groups:
children = groups.pop(0)
types = [type(c) for c in children]
i... | Transform pattern into an equivalent, with only top-level Either. |
10,846 | def f_delete_links(self, iterator_of_links, remove_from_trajectory=False):
to_delete_links = []
group_link_pairs = []
for elem in iterator_of_links:
if isinstance(elem, str):
split_names = elem.split()
parent_name = .join(split_names[:-1])
... | Deletes several links from the hard disk.
Links can be passed as a string ``'groupA.groupB.linkA'``
or as a tuple containing the node from which the link should be removed and the
name of the link ``(groupWithLink, 'linkA')``. |
10,847 | def check_labels(self):
for entry in self.labels:
self.check_is_declared(entry.name, entry.lineno, CLASS.label) | Checks if all the labels has been declared |
10,848 | def supports(cls, template_file=None):
if anytemplate.compat.IS_PYTHON_3:
cls._priority = 99
return False
return super(Engine, cls).supports(template_file=template_file) | :return: Whether the engine can process given template file or not. |
10,849 | def threshold_monitor_hidden_threshold_monitor_sfp_policy_area_threshold_high_threshold(self, **kwargs):
config = ET.Element("config")
threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor")
threshold_monitor =... | Auto Generated Code |
10,850 | def log_normalize(a, axis=None):
with np.errstate(under="ignore"):
a_lse = logsumexp(a, axis)
a -= a_lse[:, np.newaxis] | Normalizes the input array so that the exponent of the sum is 1.
Parameters
----------
a : array
Non-normalized input data.
axis : int
Dimension along which normalization is performed.
Notes
-----
Modifies the input **inplace**. |
10,851 | def _save_model(self, steps=0):
for brain_name in self.trainers.keys():
self.trainers[brain_name].save_model()
self.logger.info() | Saves current model to checkpoint folder.
:param steps: Current number of steps in training process.
:param saver: Tensorflow saver for session. |
10,852 | def compress_table(condition, tbl, axis=None, out=None, blen=None, storage=None,
create=, **kwargs):
if axis is not None and axis != 0:
raise NotImplementedError()
if out is not None:
raise NotImplementedError()
storage = _util.get_storage(storage)
... | Return selected rows of a table. |
10,853 | def read_plain_int64(file_obj, count):
return struct.unpack("<{}q".format(count).encode("utf-8"), file_obj.read(8 * count)) | Read `count` 64-bit ints using the plain encoding. |
10,854 | def _is_duplicate_record(self, rtype, name, content):
records = self._list_records(rtype, name, content)
is_duplicate = len(records) >= 1
if is_duplicate:
LOGGER.info(, rtype, name, content)
return is_duplicate | Check if DNS entry already exists. |
10,855 | def estimate_parameters(self, max_dist_kb, size_bin_kb, display_graph):
logger.info("estimation of the parameters of the model")
self.bins = np.arange(
size_bin_kb, max_dist_kb + size_bin_kb, size_bin_kb
)
self.mean_contacts = np.zeros_like(self.bins, dtype=np.float... | estimation by least square optimization of Rippe parameters on the
experimental data
:param max_dist_kb:
:param size_bin_kb: |
10,856 | def reverse_mapping(mapping):
keys, values = zip(*mapping.items())
return dict(zip(values, keys)) | For every key, value pair, return the mapping for the
equivalent value, key pair
>>> reverse_mapping({'a': 'b'}) == {'b': 'a'}
True |
10,857 | def set_itunes_element(self):
self.set_itunes_author_name()
self.set_itunes_block()
self.set_itunes_closed_captioned()
self.set_itunes_duration()
self.set_itunes_explicit()
self.set_itune_image()
self.set_itunes_order()
self.set_itunes_subtitle()
... | Set each of the itunes elements. |
10,858 | def install_plugin(self, dir, entry_script=None):
self.runtimepath.append(dir)
if entry_script is not None:
self.command(.format(entry_script), False) | Install *Vim* plugin.
:param string dir: the root directory contains *Vim* script
:param string entry_script: path to the initializing script |
10,859 | def active_brokers(self):
return {
broker for broker in six.itervalues(self.brokers)
if not broker.inactive and not broker.decommissioned
} | Set of brokers that are not inactive or decommissioned. |
10,860 | def is_equal(self, other):
other = IntervalCell.coerce(other)
return other.low == self.low and other.high == self.high | If two intervals are the same |
10,861 | def read_data(self, **kwargs):
trigger_id = kwargs.get()
data = list()
kwargs[] =
kwargs[] =
super(ServiceTumblr, self).read_data(**kwargs)
cache.set( + str(trigger_id), data)
return data | get the data from the service
as the pocket service does not have any date
in its API linked to the note,
add the triggered date to the dict data
thus the service will be triggered when data will be found
:param kwargs: contain keyword args : trigger_id at le... |
10,862 | def honeypot_exempt(view_func):
def wrapped(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped.honeypot_exempt = True
return wraps(view_func, assigned=available_attrs(view_func))(wrapped) | Mark view as exempt from honeypot validation |
10,863 | def get_feature_state_for_scope(self, feature_id, user_scope, scope_name, scope_value):
route_values = {}
if feature_id is not None:
route_values[] = self._serialize.url(, feature_id, )
if user_scope is not None:
route_values[] = self._serialize.url(, user_scope,... | GetFeatureStateForScope.
[Preview API] Get the state of the specified feature for the given named scope
:param str feature_id: Contribution id of the feature
:param str user_scope: User-Scope at which to get the value. Should be "me" for the current user or "host" for all users.
:param s... |
10,864 | def is_child_of_bin(self, id_, bin_id):
if self._catalog_session is not None:
return self._catalog_session.is_child_of_catalog(id_=id_, catalog_id=bin_id)
return self._hierarchy_session.is_child(id_=bin_id, child_id=id_) | Tests if a bin is a direct child of another.
arg: id (osid.id.Id): an ``Id``
arg: bin_id (osid.id.Id): the ``Id`` of a bin
return: (boolean) - ``true`` if the ``id`` is a child of
``bin_id,`` ``false`` otherwise
raise: NotFound - ``bin_id`` is not found
r... |
10,865 | def create_translation_field(translated_field, language):
cls_name = translated_field.__class__.__name__
if not isinstance(translated_field, tuple(SUPPORTED_FIELDS.keys())):
raise ImproperlyConfigured("%s is not supported by Linguist." % cls_name)
translation_class = field_factory(translated_... | Takes the original field, a given language, a decider model and return a
Field class for model. |
10,866 | def deepish_copy(org):
out = dict().fromkeys(org)
for k, v in org.items():
if isinstance(v, dict):
out[k] = deepish_copy(v)
else:
try:
out[k] = v.copy()
except AttributeError:
try:
out[k] = v[:]
... | Improved speed deep copy for dictionaries of simple python types.
Thanks to Gregg Lind:
http://writeonly.wordpress.com/2009/05/07/deepcopy-is-a-pig-for-simple-data/ |
10,867 | def _generate_token(self, length=32):
return .join(choice(ascii_letters + digits) for x in range(length)) | _generate_token - internal function for generating randomized alphanumberic
strings of a given length |
10,868 | def bulk_exports(self):
if self._bulk_exports is None:
self._bulk_exports = BulkExports(self)
return self._bulk_exports | :returns: Version bulk_exports of preview
:rtype: twilio.rest.preview.bulk_exports.BulkExports |
10,869 | def unmajority(p, a, b, c):
p.ccx(a, b, c)
p.cx(c, a)
p.cx(a, b) | Unmajority gate. |
10,870 | def to_xml(self, opts = defaultdict(lambda: None)):
if not self.launch_url or not self.secure_launch_url:
raise InvalidLTIConfigError()
root = etree.Element(, attrib = {
%(NSMAP[], ): ,
:
}, nsmap = NSMAP)
... | Generate XML from the current settings. |
10,871 | def git_list_refs(repo_dir):
command = [, , , ]
raw = execute_git_command(command, repo_dir=repo_dir).splitlines()
output = [l.strip() for l in raw if l.strip()]
return {ref: commit_hash for commit_hash, ref in
[l.split(None, 1) for l in output]} | List references available in the local repo with commit ids.
This is similar to ls-remote, but shows the *local* refs.
Return format:
.. code-block:: python
{<ref1>: <commit_hash1>,
<ref2>: <commit_hash2>,
...,
<refN>: <commit_hashN>,
} |
10,872 | def iter(self, count=0, func=sum):
while True:
yield self.roll(count, func) | Iterator of infinite dice rolls.
:param count: [0] Return list of ``count`` sums
:param func: [sum] Apply func to list of individual die rolls func([]) |
10,873 | def add(self, field, data_type=None, nullable=True, metadata=None):
if isinstance(field, StructField):
self.fields.append(field)
self.names.append(field.name)
else:
if isinstance(field, str) and data_type is None:
raise ValueError("Must specif... | Construct a StructType by adding new elements to it to define the schema. The method accepts
either:
a) A single parameter which is a StructField object.
b) Between 2 and 4 parameters as (name, data_type, nullable (optional),
metadata(optional). The data_type parameter ma... |
10,874 | def _scheduleUpgrade(self,
ev_data: UpgradeLogData,
failTimeout) -> None:
logger.info(
"{}{}' to version {} "
"has been scheduled on {}"
.format(ev_data.pkg_name, self.nodeName,
ev_data.version, ev... | Schedules node upgrade to a newer version
:param ev_data: upgrade event parameters |
10,875 | def clean_gff(gff, cleaned, add_chr=False, chroms_to_ignore=None,
featuretypes_to_ignore=None):
logger.info("Cleaning GFF")
chroms_to_ignore = chroms_to_ignore or []
featuretypes_to_ignore = featuretypes_to_ignore or []
with open(cleaned, ) as fout:
for i in gffutils.iterators... | Cleans a GFF file by removing features on unwanted chromosomes and of
unwanted featuretypes. Optionally adds "chr" to chrom names. |
10,876 | def get_params(url, ignore_empty=False):
try:
params_start_index = url.index()
except ValueError:
params_start_index = 0
params_string = url[params_start_index + 1:]
params_dict = {}
for pair in params_string.split():
if not pair:
... | Static method that parses a given `url` and retrieves `url`'s parameters. Could also ignore empty value parameters.
Handles parameters-only urls as `q=banana&peel=false`.
:param str url: url to parse
:param bool ignore_empty: ignore empty value parameter or not
:return: dictionary of pa... |
10,877 | def add_term_facet(self, *args, **kwargs):
self.facets.append(TermFacet(*args, **kwargs)) | Add a term factory facet |
10,878 | def wait_for_servers(session, servers):
nclient = nova.Client(NOVA_VERSION, session=session,
region_name=os.environ[])
while True:
deployed = []
undeployed = []
for server in servers:
c = nclient.servers.get(server.id)
if c.addresses... | Wait for the servers to be ready.
Note(msimonin): we don't garantee the SSH connection to be ready. |
10,879 | def to_html(self):
if self.text is None:
return
else:
return % (
self.html_attributes(), self.html_icon(), self.text.to_html()) | Render a Paragraph MessageElement as html
:returns: The html representation of the Paragraph MessageElement |
10,880 | def _migrate_db_pre010(self, dbname, newslab):
dbnamedbname
donekey = f
if self.metadict.get(donekey, False):
return
if not self.layrslab.dbexists(dbname):
self.metadict.set(donekey, True)
return False
oldslab = self.layrslab
olddb =... | Check for any pre-010 entries in 'dbname' in my slab and migrate those to the new slab.
Once complete, drop the database from me with the name 'dbname'
Returns (bool): True if a migration occurred, else False |
10,881 | def get_version_info():
from astropy import __version__
astropy_version = __version__
from photutils import __version__
photutils_version = __version__
return .format(astropy_version,
photutils_version) | Return astropy and photutils versions.
Returns
-------
result : str
The astropy and photutils versions. |
10,882 | def datetime_to_ns(then):
if then == datetime(1970, 1, 1, 0, 0):
return
now = datetime.utcnow()
delta = now - then
seconds = delta.total_seconds()
| Transform a :any:`datetime.datetime` into a NationStates-style
string.
For example "6 days ago", "105 minutes ago", etc. |
10,883 | def _apply_dvs_config(config_spec, config_dict):
if config_dict.get():
config_spec.name = config_dict[]
if config_dict.get() or config_dict.get():
if not config_spec.contact:
config_spec.contact = vim.DVSContactInfo()
config_spec.contact.contact = config_dict.get()
... | Applies the values of the config dict dictionary to a config spec
(vim.VMwareDVSConfigSpec) |
10,884 | def validate_enum_attribute(fully_qualified_name: str, spec: Dict[str, Any], attribute: str,
candidates: Set[Union[str, int, float]]) -> Optional[InvalidValueError]:
if attribute not in spec:
return
if spec[attribute] not in candidates:
return InvalidValueError... | Validates to ensure that the value of an attribute lies within an allowed set of candidates |
10,885 | def _qmed_from_pot_records(self):
pot_dataset = self.catchment.pot_dataset
if not pot_dataset:
raise InsufficientDataError("POT dataset must be set for catchment {} to estimate QMED from POT data."
.format(self.catchment.id))
complete... | Return QMED estimate based on peaks-over-threshold (POT) records.
Methodology source: FEH, Vol. 3, pp. 77-78
:return: QMED in m³/s
:rtype: float |
10,886 | def _vowelinstem(self, stem):
for i in range(len(stem)):
if not self._cons(stem, i):
return True
return False | vowelinstem(stem) is TRUE <=> stem contains a vowel |
10,887 | def _write_adminfile(kwargs):
email = kwargs.get(, )
instance = kwargs.get(, )
partial = kwargs.get(, )
runlevel = kwargs.get(, )
idepend = kwargs.get(, )
rdepend = kwargs.get(, )
space = kwargs.get(, )
setuid = kwargs.get(, )
conflict = kwargs.get(, )
action = kwargs.g... | Create a temporary adminfile based on the keyword arguments passed to
pkg.install. |
10,888 | def job_get_log(object_id, input_params={}, always_retry=False, **kwargs):
return DXHTTPRequest( % object_id, input_params, always_retry=always_retry, **kwargs) | Invokes the /job-xxxx/getLog API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Applets-and-Entry-Points#API-method%3A-%2Fjob-xxxx%2FgetLog |
10,889 | def visit_Dict(self, node: AST, dfltChaining: bool = True) -> str:
items = (.join((self.visit(key), self.visit(value)))
for key, value in zip(node.keys, node.values))
return f"{{{.join(items)}}}" | Return dict representation of `node`s elements. |
10,890 | def locality_preserving_projections(self, coordinates, num_dims=None):
X = np.atleast_2d(coordinates)
L = self.laplacian(normed=True)
u,s,_ = np.linalg.svd(X.T.dot(X))
Fplus = np.linalg.pinv(u * np.sqrt(s))
n, d = X.shape
if n >= d:
T = Fplus.dot(X.T.dot(L.dot(X))).dot(Fplus.T... | Locality Preserving Projections (LPP, linearized Laplacian Eigenmaps). |
10,891 | def _init_go2ntpresent(go_ntsets, go_all, gosubdag):
go2ntpresent = {}
ntobj = namedtuple(, " ".join(nt.hdr for nt in go_ntsets))
for goid_all in go_all:
present_true = [goid_all in nt.go_set for nt in go_ntsets]
present_str = [ if tf else for tf in pre... | Mark all GO IDs with an X if present in the user GO list. |
10,892 | def _create_data_files_directory(symlink=False):
current_directory = os.path.abspath(os.path.dirname(__file__))
etc_kytos = os.path.join(BASE_ENV, ETC_KYTOS)
if not os.path.exists(etc_kytos):
os.makedirs(etc_kytos)
src = os.path.join(current_directory, KYTOS_SKEL_... | Install data_files in the /etc directory. |
10,893 | def get_jids():
with _get_serv(ret=None, commit=True) as cur:
sql =
cur.execute(sql)
data = cur.fetchall()
ret = {}
for jid, load in data:
ret[jid] = salt.utils.jid.format_jid_instance(jid,
salt.uti... | Return a list of all job ids |
10,894 | def AddBlob(self, blob_hash, length, chunk_number):
if len(blob_hash.AsBytes()) != self._HASH_SIZE:
raise ValueError("Hash doesnre adding a new blob, we should increase the size. If were adding a new one and
if not self.ChunkExists(chunk_number):
if chunk_number > self.last_chunk:
... | Add another blob to this image using its hash. |
10,895 | def change_tz(cal, new_timezone, default, utc_only=False, utc_tz=icalendar.utc):
for vevent in getattr(cal, , []):
start = getattr(vevent, , None)
end = getattr(vevent, , None)
for node in (start, end):
if node:
dt = node.value
if (isinst... | Change the timezone of the specified component.
Args:
cal (Component): the component to change
new_timezone (tzinfo): the timezone to change to
default (tzinfo): a timezone to assume if the dtstart or dtend in cal
doesn't have an existing timezone
utc_only (bool): only ... |
10,896 | def determine_band_channel(kal_out):
band = ""
channel = ""
tgt_freq = ""
while band == "":
for line in kal_out.splitlines():
if "Using " in line and " channel " in line:
band = str(line.split()[1])
channel = str(line.split()[3])
t... | Return band, channel, target frequency from kal output. |
10,897 | def rolling_window(array, axis, window, center, fill_value):
if isinstance(array, dask_array_type):
return dask_array_ops.rolling_window(
array, axis, window, center, fill_value)
else:
return nputils.rolling_window(
array, axis, window, center, fill_value) | Make an ndarray with a rolling window of axis-th dimension.
The rolling dimension will be placed at the last dimension. |
10,898 | def _ensure_programmer_executable():
updater_executable = shutil.which(,
mode=os.F_OK)
os.chmod(updater_executable, 0o777) | Find the lpc21isp executable and ensure it is executable |
10,899 | def tarball_files(work_dir, tar_name, uuid=None, files=None):
with tarfile.open(os.path.join(work_dir, tar_name), ) as f_out:
for fname in files:
if uuid:
f_out.add(os.path.join(work_dir, fname), arcname=uuid + + fname)
else:
f_out.add(os.path.jo... | Tars a group of files together into a tarball
work_dir: str Current Working Directory
tar_name: str Name of tarball
uuid: str UUID to stamp files with
files: str(s) List of filenames to place in the tarball from working directory |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.