Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
3,300 | def walk_egg(egg_dir):
walker = os.walk(egg_dir)
base,dirs,files = walker.next()
if in dirs:
dirs.remove()
yield base,dirs,files
for bdf in walker:
yield bdf | Walk an unpacked egg's contents, skipping the metadata directory |
3,301 | def log(self, uuid=None, organization=None, from_date=None, to_date=None):
try:
enrollments = api.enrollments(self.db, uuid, organization,
from_date, to_date)
self.display(, enrollments=enrollments)
except (NotFoundError, Invalid... | List enrollment information available in the registry.
Method that returns a list of enrollments. If <uuid> parameter is set,
it will return the enrollments related to that unique identity;
if <organization> parameter is given, it will return the enrollments
related to that organization... |
3,302 | def if_has_delegate(delegate):
if isinstance(delegate, list):
delegate = tuple(delegate)
if not isinstance(delegate, tuple):
delegate = (delegate,)
return lambda fn: _IffHasDelegate(fn, delegate) | Wrap a delegated instance attribute function.
Creates a decorator for methods that are delegated in the presence of a
results wrapper. This enables duck-typing by ``hasattr`` returning True
according to the sub-estimator.
This function was adapted from scikit-learn, which defines
``if_delegate_has... |
3,303 | def ping(self):
if self.finished is not None:
raise AlreadyFinished()
with self._db_conn() as conn:
success = conn.query( % self._queue.table_name,
now=datetime.utcnow(),
task_id=self.task_id,
execution_id=self.execution_i... | Notify the queue that this task is still active. |
3,304 | def isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0):
try:
return math.isclose(a, b, rel_tol=rel_tol, abs_tol=abs_tol)
except AttributeError:
if (rel_tol < 0.0) or (abs_tol < 0.0):
raise ValueError("Tolerances must be non-negative, but are rel_tol: {} and abs_tol: {}".forma... | Python 3.4 does not have math.isclose, so we need to steal it and add it here. |
3,305 | def run_foreach_or_conditional(self, context):
logger.debug("starting")
if self.foreach_items:
self.foreach_loop(context)
else:
self.run_conditional_decorators(context)
logger.debug("done") | Run the foreach sequence or the conditional evaluation.
Args:
context: (pypyr.context.Context) The pypyr context. This arg will
mutate. |
3,306 | def toggle_item(self, item, test_func, field_name=None):
if test_func(item):
self.add_item(item, field_name)
return True
else:
self.remove_item(item, field_name)
return False | Toggles the section based on test_func.
test_func takes an item and returns a boolean. If it returns True, the
item will be added to the given section. It will be removed from the
section otherwise.
Intended for use with items of settings.ARMSTRONG_SECTION_ITEM_MODEL.
Behavior ... |
3,307 | def get_beam(header):
if "BPA" not in header:
log.warning("BPA not present in fits header, using 0")
bpa = 0
else:
bpa = header["BPA"]
if "BMAJ" not in header:
log.warning("BMAJ not present in fits header.")
bmaj = None
else:
bmaj = header["BMAJ"]
... | Create a :class:`AegeanTools.fits_image.Beam` object from a fits header.
BPA may be missing but will be assumed to be zero.
if BMAJ or BMIN are missing then return None instead of a beam object.
Parameters
----------
header : HDUHeader
The fits header.
Returns
-------
beam : ... |
3,308 | def _elect_source_replication_group(
self,
over_replicated_rgs,
partition,
):
return max(
over_replicated_rgs,
key=lambda rg: rg.count_replica(partition),
) | Decide source replication-group based as group with highest replica
count. |
3,309 | def _remove_qs(self, url):
scheme, netloc, path, query, fragment = urlsplit(url)
return urlunsplit((scheme, netloc, path, , fragment)) | Removes a query string from a URL before signing.
:param url: The URL to strip.
:type url: str |
3,310 | def config(self, config):
for section, data in config.items():
for variable, value in data.items():
self.set_value(section, variable, value) | Set config values from config dictionary. |
3,311 | def _Load(self,location):
for network in clc.v2.API.Call(, % (self.alias,location),{},session=self.session):
self.networks.append(Network(id=network[],alias=self.alias,network_obj=network,session=self.session)) | Load all networks associated with the given location.
https://www.centurylinkcloud.com/api-docs/v2/#get-network-list#request |
3,312 | def update_store_credit_by_id(cls, store_credit_id, store_credit, **kwargs):
kwargs[] = True
if kwargs.get():
return cls._update_store_credit_by_id_with_http_info(store_credit_id, store_credit, **kwargs)
else:
(data) = cls._update_store_credit_by_id_with_http_inf... | Update StoreCredit
Update attributes of StoreCredit
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_store_credit_by_id(store_credit_id, store_credit, async=True)
>>> result = thread.get... |
3,313 | def compile_foreign_key(line, context, attributes, primary_key, attr_sql, foreign_key_sql, index_sql):
from .table import Table
from .expression import Projection
new_style = True
try:
result = foreign_key_parser.parseString(line)
except pp.ParseException:
try:
... | :param line: a line from a table definition
:param context: namespace containing referenced objects
:param attributes: list of attribute names already in the declaration -- to be updated by this function
:param primary_key: None if the current foreign key is made from the dependent section. Otherwise it is ... |
3,314 | def gen_table(self, inner_widths, inner_heights, outer_widths):
if self.outer_border:
yield self.horizontal_border(, outer_widths)
row_count = len(self.table_data)
last_row_index, before_last_row_index = row_count - 1, row_count - 2
for i, row in e... | Combine everything and yield every line of the entire table with borders.
:param iter inner_widths: List of widths (no padding) for each column.
:param iter inner_heights: List of heights (no padding) for each row.
:param iter outer_widths: List of widths (with padding) for each column.
... |
3,315 | def traceroute(host):
*
ret = []
if not salt.utils.path.which():
log.info()
return ret
cmd = .format(salt.utils.network.sanitize_host(host))
out = __salt__[](cmd)
if salt.utils.platform.is_sunos() or salt.utils.platform.is_aix():
traceroute_version = [0, 0, 0]
... | Performs a traceroute to a 3rd party host
.. versionchanged:: 2015.8.0
Added support for SunOS
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' network.traceroute archlinux.org |
3,316 | def create(self, create_missing=None):
return type(self)(
self._server_config,
id=self.create_json(create_missing)[],
).read() | Do extra work to fetch a complete set of attributes for this entity.
For more information, see `Bugzilla #1381129
<https://bugzilla.redhat.com/show_bug.cgi?id=1381129>`_. |
3,317 | def compile(self, session=None):
if not self.num_data == self.X.shape[0]:
self.num_data = self.X.shape[0]
self.q_alpha = Parameter(np.zeros((self.num_data, self.num_latent)))
self.q_lambda = Parameter(np.ones((self.num_data, self.num_latent)),
... | Before calling the standard compile function, check to see if the size
of the data has changed and add variational parameters appropriately.
This is necessary because the shape of the parameters depends on the
shape of the data. |
3,318 | def config_xml_to_dict(contents, result, parse_job=True):
from lxml import etree
try:
root = etree.fromstring(contents)
pairs = []
if parse_job:
for elem in root:
if (elem.tag != gc.CONFIG_XML_TASKS_TAG) and (elem.text is not None):
... | Convert the contents of a XML config file
into the corresponding dictionary ::
dictionary[key_1] = value_1
dictionary[key_2] = value_2
...
dictionary[key_n] = value_n
:param bytes contents: the XML configuration contents
:param bool parse_job: if ``True``, parse the job pro... |
3,319 | def authorized_purchase_object(self, oid, price, huid):
return self.request(
,
safeformat(, oid),
json.dumps({
: price,
: huid,
: True
})) | Does delegated (pre-authorized) purchase of `oid` in the name of
`huid`, at price `price` (vingd transferred from `huid` to consumer's
acc).
:raises GeneralException:
:resource: ``objects/<oid>/purchases``
:access: authorized users with ACL flag ``purchase.objec... |
3,320 | def move_editorstack_data(self, start, end):
if start < 0 or end < 0:
return
else:
steps = abs(end - start)
direction = (end-start) // steps
data = self.data
self.blockSignals(True)
for i in range(start, end, direction):
... | Reorder editorstack.data so it is synchronized with the tab bar when
tabs are moved. |
3,321 | def groups_setPurpose(self, *, channel: str, purpose: str, **kwargs) -> SlackResponse:
kwargs.update({"channel": channel, "purpose": purpose})
return self.api_call("groups.setPurpose", json=kwargs) | Sets the purpose for a private channel.
Args:
channel (str): The channel id. e.g. 'G1234567890'
purpose (str): The new purpose for the channel. e.g. 'My Purpose' |
3,322 | def optimize(function, x0, cons=[], ftol=0.2, disp=0, plot=False):
if disp > 0:
print
print
print
print , function, , x0
points = []
values = []
def recordfunction(x):
v = function(x)
points.append(x)
values.append(v)
return v
(a, b, c), (va, vb, vc) = seek_minimum_bracket(recordfunction, x0, co... | **Optimization method based on Brent's method**
First, a bracket (a b c) is sought that contains the minimum (b value is
smaller than both a or c).
The bracket is then recursively halfed. Here we apply some modifications
to ensure our suggested point is not too close to either a or c,
because that could be pr... |
3,323 | def __process_equalities(self, equalities, momentequalities):
monomial_sets = []
n_rows = 0
le = 0
if equalities is not None:
for equality in equalities:
le += 1
if equality.is_Relational:
equality ... | Generate localizing matrices
Arguments:
equalities -- list of equality constraints
equalities -- list of moment equality constraints |
3,324 | def create_topology(self, topologyName, topology):
if not topology or not topology.IsInitialized():
raise_(StateException("Topology protobuf not init properly",
StateException.EX_TYPE_PROTOBUF_ERROR), sys.exc_info()[2])
path = self.get_topology_path(topologyName)
LOG.... | crate topology |
3,325 | def _collect_block_lines(self, msgs_store, node, msg_state):
for child in node.get_children():
self._collect_block_lines(msgs_store, child, msg_state)
first = node.fromlineno
last = node.tolineno
... | Recursively walk (depth first) AST to collect block level options
line numbers. |
3,326 | def api_version(self, v):
self._api_version = v
if (self._api_version >= ):
self.default_quality =
self.allowed_qualities = [, , , ]
else:
self.default_quality =
self.allowed_qualities = [, , , ] | Set the api_version and associated configurations. |
3,327 | def unscale_and_snap_to_nearest(x, tune_params, eps):
x_u = [i for i in x]
for i, v in enumerate(tune_params.values()):
pad = 0.5*eps
linspace = numpy.linspace(pad, (eps*len(v))-pad, len(v))
idx = numpy.abs(linspace-x[i]).argmin()
... | helper func that snaps a scaled variable to the nearest config |
3,328 | def add_item(self, item, replace = False):
if item.jid in self._jids:
if replace:
self.remove_item(item.jid)
else:
raise ValueError("JID already in the roster")
index = len(self._items)
self._items.append(item)
self._jids[i... | Add an item to the roster.
This will not automatically update the roster on the server.
:Parameters:
- `item`: the item to add
- `replace`: if `True` then existing item will be replaced,
otherwise a `ValueError` will be raised on conflict
:Types:
... |
3,329 | def get_colors(n, cmap=, start=0., stop=1., alpha=1., return_hex=False):
colors = [cm.get_cmap(cmap)(x) for x in np.linspace(start, stop, n)]
colors = [(r, g, b, alpha) for r, g, b, _ in colors]
if return_hex:
colors = rgb_color_list_to_hex(colors)
return colors | Return n-length list of RGBa colors from the passed colormap name and alpha.
Parameters
----------
n : int
number of colors
cmap : string
name of a colormap
start : float
where to start in the colorspace
stop : float
where to end in the colorspace
alpha : flo... |
3,330 | def check_known_host(user=None, hostname=None, key=None, fingerprint=None,
config=None, port=None, fingerprint_hash_type=None):
s enough to set up either key or fingerprint, you dont match with stored value, return
"update", if no value is found for a given host, return "add", otherwise
... | Check the record in known_hosts file, either by its value or by fingerprint
(it's enough to set up either key or fingerprint, you don't need to set up
both).
If provided key or fingerprint doesn't match with stored value, return
"update", if no value is found for a given host, return "add", otherwise
... |
3,331 | def send(*args, **kwargs):
queue_flag = kwargs.pop("queue", False)
now_flag = kwargs.pop("now", False)
assert not (queue_flag and now_flag), " and cannot both be True."
if queue_flag:
return queue(*args, **kwargs)
elif now_flag:
return send_now(*args, **kwargs)
else:
... | A basic interface around both queue and send_now. This honors a global
flag NOTIFICATION_QUEUE_ALL that helps determine whether all calls should
be queued or not. A per call ``queue`` or ``now`` keyword argument can be
used to always override the default global behavior. |
3,332 | def get_es_label(obj, def_obj):
label_flds = LABEL_FIELDS
if def_obj.es_defs.get():
label_flds = def_obj.es_defs[] + LABEL_FIELDS
try:
for label in label_flds:
if def_obj.cls_defs.get(label):
obj[] = def_obj.cls_defs[label][0]
break
... | Returns object with label for an object that goes into the elacticsearch
'label' field
args:
obj: data object to update
def_obj: the class instance that has defintion values |
3,333 | def p_param_def_type(p):
if p[2] is not None:
api.check.check_type_is_explicit(p.lineno(1), p[1], p[2])
p[0] = make_param_decl(p[1], p.lineno(1), p[2]) | param_def : ID typedef |
3,334 | def save_stream(self, key, binary=False):
s = io.BytesIO() if binary else io.StringIO()
yield s
self.save_value(key, s.getvalue()) | Return a managed file-like object into which the calling code can write
arbitrary data.
:param key:
:return: A managed stream-like object |
3,335 | def get_placeholders(self, format_string):
placeholders = set()
for token in self.tokens(format_string):
if token.group("placeholder"):
placeholders.add(token.group("key"))
elif token.group("command"):
commands = ... | Parses the format_string and returns a set of placeholders. |
3,336 | def reset(self, value=None):
if value is None:
value = time.clock()
self.start = value
if self.value_on_reset:
self.value = self.value_on_reset | Resets the start time of the interval to now or the specified value. |
3,337 | def featurewise_norm(x, mean=None, std=None, epsilon=1e-7):
if mean:
x = x - mean
if std:
x = x / (std + epsilon)
return x | Normalize every pixels by the same given mean and std, which are usually
compute from all examples.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
mean : float
Value for subtraction.
std : float
Value for division.
ep... |
3,338 | def _getStrippedValue(value, strip):
if strip is None:
value = value.strip()
elif isinstance(strip, str):
value = value.strip(strip)
elif strip is False:
pass
return value | Like the strip() string method, except the strip argument describes
different behavior:
If strip is None, whitespace is stripped.
If strip is a string, the characters in the string are stripped.
If strip is False, nothing is stripped. |
3,339 | def clean_helper(B, obj, clean_func):
try:
clean_func(obj)
except B.validation_error() as e:
fields = B.detect_uniqueness_error(e)
missing = B.detect_missing_relations(obj, e)
return fields, missing
return (None, None) | Clean object, intercepting and collecting any missing-relation or
unique-constraint errors and returning the relevant resource ids/fields.
Returns:
- tuple: (<dict of non-unique fields>, <dict of missing refs>) |
3,340 | def _generate_event_listener_caller(executables: List[str]) -> LockEventListener:
def event_listener_caller(key: str):
for executable in executables:
try:
process = subprocess.Popen([executable, key], stderr=subprocess.PIPE, stdout=subprocess.PIPE)
output, st... | TODO
:param executables:
:return: |
3,341 | def skip(self, content):
if self.optional(content):
v = content.value
if v is None:
return True
if isinstance(v, (list, tuple)) and not v:
return True
return False | Get whether to skip this I{content}.
Should be skipped when the content is optional and value is either None
or an empty list.
@param content: Content to skip.
@type content: L{Object}
@return: True if content is to be skipped.
@rtype: bool |
3,342 | def log_combinations(n, counts, name="log_combinations"):
with tf.name_scope(name):
n = tf.convert_to_tensor(value=n, name="n")
counts = tf.convert_to_tensor(value=counts, name="counts")
total_permutations = tf.math.lgamma(n + 1)
counts_factorial = tf.math.lgamma(counts + 1)
redu... | Multinomial coefficient.
Given `n` and `counts`, where `counts` has last dimension `k`, we compute
the multinomial coefficient as:
```n! / sum_i n_i!```
where `i` runs over all `k` classes.
Args:
n: Floating-point `Tensor` broadcastable with `counts`. This represents `n`
outcomes.
counts: Fl... |
3,343 | def report_error(title=None, data={}, caught=None, is_fatal=False):
status, code = ,
if in data:
status = data[].get(, status)
code = data[].get(, code)
title_details = "%s %s %s" % (ApiPool().current_server_name, status, code)
else:
title_details = "%s %s()" % (... | Format a crash report and send it somewhere relevant. There are two
types of crashes: fatal crashes (backend errors) or non-fatal ones (just
reporting a glitch, but the api call did not fail) |
3,344 | def get_response_handler(self):
assert self.response_handler is not None, \
\
% self.__class__.__name__
return self.response_handler(self, **self.get_response_handler_params()) | Return the Endpoints defined :attr:`Endpoint.response_handler`.
:returns: A instance of the Endpoint specified :class:`ResonseHandler`.
:rtype: :class:`ResponseHandler` |
3,345 | def load_HEP_data(
ROOT_filename = "output.root",
tree_name = "nominal",
maximum_number_of_events = None
):
ROOT_file = open_ROOT_file(ROOT_filename)
tree = ROOT_file.Get(tree_name)
number_of_events = tree.GetEntries()
data = ... | Load HEP data and return dataset. |
3,346 | def refresh_ip(self, si, logger, session, vcenter_data_model, resource_model, cancellation_context,
app_request_json):
self._do_not_run_on_static_vm(app_request_json=app_request_json)
default_network = VMLocation.combine(
[vcenter_data_model.default_datacenter, v... | Refreshes IP address of virtual machine and updates Address property on the resource
:param vim.ServiceInstance si: py_vmomi service instance
:param logger:
:param vCenterShell.driver.SecureCloudShellApiSession session: cloudshell session
:param GenericDeployedAppResourceModel resource_... |
3,347 | def _npy_num2fits(d, table_type=, write_bitcols=False):
dim = None
name = d[0]
npy_dtype = d[1][1:]
if npy_dtype[0] == or npy_dtype[0] == :
raise ValueError("got S or U type: use _npy_string2fits")
if npy_dtype not in _table_npy2fits_form:
raise ValueError("unsupported type... | d is the full element from the descr
For vector,array columns the form is the total counts
followed by the code.
For array columns with dimension greater than 1, the dim is set to
(dim1, dim2, ...)
So it is treated like an extra dimension |
3,348 | def hwstatus_send(self, Vcc, I2Cerr, force_mavlink1=False):
return self.send(self.hwstatus_encode(Vcc, I2Cerr), force_mavlink1=force_mavlink1) | Status of key hardware
Vcc : board voltage (mV) (uint16_t)
I2Cerr : I2C error count (uint8_t) |
3,349 | def delta(x_i, j, s, N):
flag = j == EMMMixPLAggregator.c(x_i, s)
if flag and s < len(x_i):
return 1
elif s == N:
found_equal = False
for l in range(len(x_i)):
if j == EMMMixPLAggregator.c(x_i, l):
found_equal = Tru... | delta_i_j_s |
3,350 | def setAnimation(self,obj,animation,transition=None,force=False):
self.ensureModelData(obj)
data = obj._modeldata
if animation not in self.modeldata["animations"]:
raise ValueError("There is no animation of name for model "%(animation,self.modelname))
... | Sets the animation to be used by the object.
See :py:meth:`Actor.setAnimation()` for more information. |
3,351 | def get_detail_view(self, request, object, opts=None):
view = self.get_view(request, self.view_class, opts)
view.object = object
return view | Instantiates and returns the view class that will generate the actual
context for this plugin. |
3,352 | def coef_(self):
if getattr(self, , None) is not None and self.booster != :
raise AttributeError(
.format(self.booster))
b = self.get_booster()
coef = np.array(json.loads(b.get_dump(dump_format=)[0])[])
n_classes = getattr(se... | Coefficients property
.. note:: Coefficients are defined only for linear learners
Coefficients are only defined when the linear model is chosen as base
learner (`booster=gblinear`). It is not defined for other base learner types, such
as tree learners (`booster=gbtree`).
... |
3,353 | def url_for(self, endpoint, explicit=False, **items):
if not explicit and not endpoint.startswith(self._namespace):
endpoint = % (self._namespace, endpoint)
return self._plugin.url_for(endpoint, **items) | Returns a valid XBMC plugin URL for the given endpoint name.
endpoint can be the literal name of a function, or it can
correspond to the name keyword arguments passed to the route
decorator.
Currently, view names must be unique across all plugins and
modules. There are not names... |
3,354 | def matchToString(dnaMatch, read1, read2, matchAmbiguous=True, indent=,
offsets=None):
match = dnaMatch[]
identicalMatchCount = match[]
ambiguousMatchCount = match[]
gapMismatchCount = match[]
gapGapMismatchCount = match[]
nonGapMismatchCount = match[]
if offsets:
... | Format a DNA match as a string.
@param dnaMatch: A C{dict} returned by C{compareDNAReads}.
@param read1: A C{Read} instance or an instance of one of its subclasses.
@param read2: A C{Read} instance or an instance of one of its subclasses.
@param matchAmbiguous: If C{True}, ambiguous nucleotides that ar... |
3,355 | def configure(self, component, all_dependencies):
r = {}
builddir = self.buildroot
} | Ensure all config-time files have been generated. Return a
dictionary of generated items. |
3,356 | def sort_by_list_order(sortlist, reflist, reverse=False, fltr=False,
slemap=None):
def keyfunc(entry):
if slemap is not None:
rle = slemap(entry)
if rle in reflist:
return reflist.index(rle)
else:
... | Sort a list according to the order of entries in a reference list.
Parameters
----------
sortlist : list
List to be sorted
reflist : list
Reference list defining sorting order
reverse : bool, optional (default False)
Flag indicating whether to sort in reverse order
fltr : bool... |
3,357 | def load_modules(self, data=None, proxy=None):
self.functions = self.wrapper
self.utils = salt.loader.utils(self.opts)
self.serializers = salt.loader.serializers(self.opts)
locals_ = salt.loader.minion_mods(self.opts, utils=self.utils)
self.states = salt.loader.states(se... | Load up the modules for remote compilation via ssh |
3,358 | def remove_instance(self):
with fields.FieldLock(self.related_field):
related_pks = self()
for pk in related_pks:
related_instance = self.related_field._model(pk)
related_field = getattr(related_instance, self.related_field.name)... | Remove the instance from the related fields (delete the field if it's
a simple one, or remove the instance from the field if it's a set/list/
sorted_set) |
3,359 | def artifacts(self):
if self._artifact_manager is None:
self._artifact_manager = ArtifactManager(session=self._session)
return self._artifact_manager | Property for accessing :class:`ArtifactManager` instance, which is used to manage artifacts.
:rtype: yagocd.resources.artifact.ArtifactManager |
3,360 | def update_points(self):
n = max(8, min(72, int(2*sqrt(self.r_x+self.r_y))))
d = pi * 2 / n
x, y, r_x, r_y = self.x, self.y, self.r_x, self.r_y
ps = []
for i in range(n):
ps += [(x + r_x * sin(d * i)), (y + r_y * cos(d * i))]
self.points = tuple(ps) | 椭圆的近似图形:72边形 |
3,361 | def _raise_if_null(self, other):
if self.is_null():
raise ValueError("Cannot compare null Intervals!")
if hasattr(other, ) and other.is_null():
raise ValueError("Cannot compare null Intervals!") | :raises ValueError: if either self or other is a null Interval |
3,362 | def populate_initial_services():
services_list = (
(
,
,
,
),
(
,
,
,
),
(
,
,
,
),
(
,
... | Populate a fresh installed Hypermap instances with basic services. |
3,363 | def _request(self, req_type, url, **kwargs):
logger.debug( % (req_type, url))
result = self.session.request(req_type, url, **kwargs)
try:
result.raise_for_status()
except requests.HTTPError:
error = result.text
try:
error = jso... | Make a request via the `requests` module. If the result has an HTTP
error status, convert that to a Python exception. |
3,364 | def auto_no_thousands(self):
if self._value >= 1000000000000:
return self.TiB,
if self._value >= 1000000000:
return self.GiB,
if self._value >= 1000000:
return self.MiB,
if self._value >= 1000:
return self.KiB,
else:
... | Like self.auto but calculates the next unit if >999.99. |
3,365 | def activate(self, tourfile=None, minsize=10000, backuptour=True):
if tourfile and (not op.exists(tourfile)):
logging.debug("Tourfile `{}` not found".format(tourfile))
tourfile = None
if tourfile:
logging.debug("Importing tourfile `{}`".format(tourfile))
... | Select contigs in the current partition. This is the setup phase of the
algorithm, and supports two modes:
- "de novo": This is useful at the start of a new run where no tours
available. We select the strong contigs that have significant number
of links to other contigs in the parti... |
3,366 | def transformer_clean():
hparams = transformer_base_v2()
hparams.label_smoothing = 0.0
hparams.layer_prepostprocess_dropout = 0.0
hparams.attention_dropout = 0.0
hparams.relu_dropout = 0.0
hparams.max_length = 0
return hparams | No dropout, label smoothing, max_length. |
3,367 | def image_bytes(b, filename=None, inline=1, width=, height=,
preserve_aspect_ratio=None):
if preserve_aspect_ratio is None:
if width != and height != :
preserve_aspect_ratio = False
else:
preserve_aspect_ratio = True
data = {
: base64.b64encode((filename... | Return a bytes string that displays image given by bytes b in the terminal
If filename=None, the filename defaults to "Unnamed file"
width and height are strings, following the format
N: N character cells.
Npx: N pixels.
N%: N percent of the session's width or height.
'auto... |
3,368 | def decrease_user_property(self, user_id, property_name, value=0, headers=None, endpoint_url=None):
endpoint_url = endpoint_url or self._endpoint_url
url = endpoint_url + "/users/" + user_id + "/properties/" + property_name + "/decrease/" + value.__str__()
headers = headers or self._de... | Decrease a user's property by a value.
:param str user_id: identified user's ID
:param str property_name: user property name to increase
:param number value: amount by which to decrease the property
:param dict headers: custom request headers (if isn't set default values are used)
... |
3,369 | def to_dict(self, properties=None):
if not properties:
skip = {, , }
properties = [p for p in dir(Compound) if isinstance(getattr(Compound, p), property) and p not in skip]
return {p: [i.to_dict() for i in getattr(self, p)] if p in {, } else getattr(self, p) for p in pro... | Return a dictionary containing Compound data. Optionally specify a list of the desired properties.
synonyms, aids and sids are not included unless explicitly specified using the properties parameter. This is
because they each require an extra request. |
3,370 | def to_n_ref(self, fill=0, dtype=):
out = np.empty(self.shape[:-1], dtype=dtype)
np.sum(self.values == 0, axis=-1, out=out)
if fill != 0:
m = self.is_missing()
out[m] = fill
if self.mask is not None:
out[self.mask... | Transform each genotype call into the number of
reference alleles.
Parameters
----------
fill : int, optional
Use this value to represent missing calls.
dtype : dtype, optional
Output dtype.
Returns
-------
out : ndarray, int8, sh... |
3,371 | def remove_targets(self, type, kept=None):
if kept is None:
kept = [
i for i, x in enumerate(self._targets)
if not isinstance(x, type)
]
if len(kept) == len(self._targets):
return self
self._targets = [self._targets[x] ... | Remove targets of certain type |
3,372 | def tile_to_path(self, tile):
return os.path.join(self.cache_path, self.service, tile.path()) | return full path to a tile |
3,373 | def create_poll(title, options, multi=True, permissive=True, captcha=False, dupcheck=):
query = {
: title,
: options,
: multi,
: permissive,
: captcha,
: dupcheck
}
return StrawPoll(requests.post(, data=json.dumps(query))) | Create a strawpoll.
Example:
new_poll = strawpy.create_poll('Is Python the best?', ['Yes', 'No'])
:param title:
:param options:
:param multi:
:param permissive:
:param captcha:
:param dupcheck:
:return: strawpy.Strawpoll object |
3,374 | def generate_namelist_file(self, rapid_namelist_file):
log("Generating RAPID namelist file ...",
"INFO")
try:
os.remove(rapid_namelist_file)
except OSError:
pass
with open(rapid_namelist_file, ) as new_file:
new_file.write()
... | Generate rapid_namelist file.
Parameters
----------
rapid_namelist_file: str
Path of namelist file to generate from
parameters added to the RAPID manager. |
3,375 | def get_extract_method(path):
info_path = _get_info_path(path)
info = _read_info(info_path)
fname = info.get(, path) if info else path
return _guess_extract_method(fname) | Returns `ExtractMethod` to use on resource at path. Cannot be None. |
3,376 | def instantiate(config):
for handle, cfg in list(config["apps"].items()):
if not cfg.get("enabled", True):
continue
app = get_application(handle)
instances[app.handle] = app(cfg) | instantiate all registered vodka applications
Args:
config (dict or MungeConfig): configuration object |
3,377 | def _get_programs_dict():
global __programs_dict
if __programs_dict is not None:
return __programs_dict
d = __programs_dict = OrderedDict()
for pkgname in COLLABORATORS_S:
try:
package = importlib.import_module(pkgname)
except ImportError:
... | Builds and returns programs dictionary
This will have to import the packages in COLLABORATORS_S in order to get their absolute path.
Returns:
dictionary: {"packagename": [ExeInfo0, ...], ...}
"packagename" examples: "f311.explorer", "numpy" |
3,378 | def scalarVectorDecorator(func):
@wraps(func)
def scalar_wrapper(*args,**kwargs):
if numpy.array(args[1]).shape == () \
and numpy.array(args[2]).shape == ():
scalarOut= True
args= (args[0],numpy.array([args[1]]),numpy.array([args[2]]))
elif numpy.arr... | Decorator to return scalar outputs as a set |
3,379 | def get_en_words() -> Set[str]:
pull_en_words()
with open(config.EN_WORDS_PATH) as words_f:
raw_words = words_f.readlines()
en_words = set([word.strip().lower() for word in raw_words])
NA_WORDS_IN_EN_DICT = set(["kore", "nani", "karri", "imi", "o", "yaw", "i",
"... | Returns a list of English words which can be used to filter out
code-switched sentences. |
3,380 | def load_stubs(self, log_mem=False):
if log_mem:
import psutil
process = psutil.Process(os.getpid())
rss = process.memory_info().rss
LOG_MEMORY_INT = 1000
MEMORY_LIMIT = 1000.0
def _add_stub_manually(_fname):
... | Load all events in their `stub` (name, alias, etc only) form.
Used in `update` mode. |
3,381 | def get_gammadot(F, mc, q, e):
mc *= SOLAR2S
m = (((1+q)**2)/q)**(3/5) * mc
dgdt = 6*np.pi*F * (2*np.pi*F*m)**(2/3) / (1-e**2) * \
(1 + 0.25*(2*np.pi*F*m)**(2/3)/(1-e**2)*(26-15*e**2))
return dgdt | Compute gamma dot from Barack and Cutler (2004)
:param F: Orbital frequency [Hz]
:param mc: Chirp mass of binary [Solar Mass]
:param q: Mass ratio of binary
:param e: Eccentricity of binary
:returns: dgamma/dt |
3,382 | def is_std_string(type_):
if utils.is_str(type_):
return type_ in string_equivalences
type_ = remove_alias(type_)
type_ = remove_reference(type_)
type_ = remove_cv(type_)
return type_.decl_string in string_equivalences | Returns True, if type represents C++ `std::string`, False otherwise. |
3,383 | def Write(self, packet):
out = bytearray([0] + packet)
os.write(self.dev, out) | See base class. |
3,384 | def add_batch(self, nlive=500, wt_function=None, wt_kwargs=None,
maxiter=None, maxcall=None, save_bounds=True,
print_progress=True, print_func=None, stop_val=None):
if maxcall is None:
maxcall = sys.maxsize
if maxiter is None:
... | Allocate an additional batch of (nested) samples based on
the combined set of previous samples using the specified
weight function.
Parameters
----------
nlive : int, optional
The number of live points used when adding additional samples
in the batch. Def... |
3,385 | def row(self):
row = OrderedDict()
row[] = self.retro_game_id
row[] = self.game_type
row[] = self.game_type_des
row[] = self.st_fl
row[] = self.regseason_fl
row[] = self.playoff_fl
row[] = self.local_game_time
row[] = self.game_id
... | Game Dataset(Row)
:return: {
'retro_game_id': Retrosheet Game id
'game_type': Game Type(S/R/F/D/L/W)
'game_type_des': Game Type Description
(Spring Training or Regular Season or Wild-card Game or Divisional Series or LCS or World Series)
'st_fl': Sprin... |
3,386 | def check_coin_a_phrase_from(text):
err = "misc.illogic.coin"
msg = "You canborrow'?"
regex = "to coin a phrase from"
return existence_check(text, [regex], err, msg, offset=1) | Check the text. |
3,387 | def size(self):
t = self._type
if t.startswith():
return int(t[len():])
if t.startswith():
return int(t[len():])
if t == :
return int(8)
if t == :
return int(160)
if t.startswith():
return int(t[len():])... | Return the size in bits
Return None if the size is not known
Returns:
int |
3,388 | def _add_blockhash_to_state_changes(storage: SQLiteStorage, cache: BlockHashCache) -> None:
batch_size = 50
batch_query = storage.batch_query_state_changes(
batch_size=batch_size,
filters=[
(, ),
(, ),
],
logical_and=False,
)
for state_change... | Adds blockhash to ContractReceiveXXX and ActionInitChain state changes |
3,389 | def ray_shooting(self, x, y, kwargs, k=None):
return self.lens_model.ray_shooting(x, y, kwargs, k=k) | maps image to source position (inverse deflection)
:param x: x-position (preferentially arcsec)
:type x: numpy array
:param y: y-position (preferentially arcsec)
:type y: numpy array
:param kwargs: list of keyword arguments of lens model parameters matching the lens model classe... |
3,390 | def write_matrix_to_tsv(net, filename=None, df=None):
import pandas as pd
if df is None:
df = net.dat_to_df()
return df[].to_csv(filename, sep=) | This will export the matrix in net.dat or a dataframe (optional df in
arguments) as a tsv file. Row/column categories will be saved as tuples in
tsv, which can be read back into the network object. |
3,391 | def generate_variables(name, n_vars=1, hermitian=None, commutative=True):
variables = []
for i in range(n_vars):
if n_vars > 1:
var_name = % (name, i)
else:
var_name = % name
if commutative:
if hermitian is None or hermitian:
va... | Generates a number of commutative or noncommutative variables
:param name: The prefix in the symbolic representation of the noncommuting
variables. This will be suffixed by a number from 0 to
n_vars-1 if n_vars > 1.
:type name: str.
:param n_vars: The number of variables.
... |
3,392 | def analog_write(self, pin, value):
if self._command_handler.ANALOG_MESSAGE + pin < 0xf0:
command = [self._command_handler.ANALOG_MESSAGE + pin, value & 0x7f, (value >> 7) & 0x7f]
self._command_handler.send_command(command)
else:
self.extended_analog(pin, va... | Set the specified pin to the specified value.
:param pin: Pin number
:param value: Pin value
:return: No return value |
3,393 | def shutdown(self):
self.stop_balance.set()
self.motor_left.stop()
self.motor_right.stop()
self.gyro_file.close()
self.touch_file.close()
self.encoder_left_file.close()
self.encoder_right_file.close()
self.dc_left_file.close()
self.dc_ri... | Close all file handles and stop all motors. |
3,394 | async def _unwatch(self, conn):
"Unwatches all previously specified keys"
await conn.send_command()
res = await conn.read_response()
return self.watching and res or True | Unwatches all previously specified keys |
3,395 | def get_mean_threshold_from_calibration(gdac, mean_threshold_calibration):
interpolation = interp1d(mean_threshold_calibration[], mean_threshold_calibration[], kind=, bounds_error=True)
return interpolation(gdac) | Calculates the mean threshold from the threshold calibration at the given gdac settings. If the given gdac value was not used during caluibration
the value is determined by interpolation.
Parameters
----------
gdacs : array like
The GDAC settings where the threshold should be determined from th... |
3,396 | def plotAccuracyDuringSequenceInference(dirName, title="", yaxis=""):
with open(os.path.join(dirName,
"sequence_batch_high_dec_normal_features.pkl"), "rb") as f:
results = cPickle.load(f)
locationRange = []
featureRange = []
for r in results:
if r["numLocations"] not in locationRange:... | Plot accuracy vs number of locations |
3,397 | def get_sample_size(self, key=None):
if key is None:
return len(self.Y)
else:
return len(self.get_partitions(self.persistence)[key]) | Returns the number of samples in the input data
@ In, key, an optional 2-tuple specifying a min-max id pair
used for determining which partition size should be
returned. If not specified then the size of the entire data
set will be returned.
@ Out, an integer ... |
3,398 | def _request_auth(self, registry):
if registry:
if registry.auth:
registry.auth.load_dockercfg()
try:
self._client_session.login(username=registry.auth.user,
password=registry.auth.passwd,
... | self, username, password=None, email=None, registry=None,
reauth=False, insecure_registry=False, dockercfg_path=None): |
3,399 | def main(args):
cmd = [,args.reference,,,args.tempdir,,
str(args.threads),,args.tempdir+]
sys.stderr.write(cmd+"\n")
gpd_sort(cmd)
cmd = [,args.gpd,,,args.tempdir,,
str(args.threads),,args.tempdir+]
sys.stderr.write(cmd+"\n")
gpd_sort(cmd)
rstream = GPDStream(open(args.tempdir+))
ms... | first we need sorted genepreds |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.