Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
356,200 | def get_properties(self):
properties = self.__reference.get_properties()
properties.update(self.__properties)
for key in pelix.constants.OBJECTCLASS, pelix.constants.SERVICE_ID:
properties[key] = self.__reference.get_property(key)
... | Returns merged properties
:return: Endpoint merged properties |
356,201 | def _insert_command(self, command):
self._clear_user_buffer()
tc = self.edit.textCursor()
tc.insertText(command)
self.edit.setTextCursor(tc) | Insert command by replacing the current input buffer and display it on the text edit. |
356,202 | def trimSegments(self, minPermanence=None, minNumSyns=None):
if minPermanence is None:
minPermanence = 0.0
if minNumSyns is None:
minNumSyns = 0
if self.verbosity >= 5:
print "Cells, all segments:"
self.printCells(predictedOnly=False)
return self.cells4.trimSegme... | Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.trimSegments`. |
356,203 | def is_greater_then_zero_bytes(self, path):
return self._getReturnCodeCmd([self._hadoop_cmd, , , , self._full_hdfs_path(path)]) == 0 | Return True if file <path> is greater than zero bytes in size, False otherwise |
356,204 | def get_finder(import_path):
Finder = import_string(import_path)
if not issubclass(Finder, BaseFileSystemFinder):
raise ImproperlyConfigured(.format(import_path))
return Finder() | Get a finder class from an import path.
Raises ``demosys.core.exceptions.ImproperlyConfigured`` if the finder is not found.
This function uses an lru cache.
:param import_path: string representing an import path
:return: An instance of the finder |
356,205 | def G(w, Xs):
n = len(Xs)
P = projection_matrix(w)
Ys = [np.dot(P, X) for X in Xs]
A = calc_A(Ys)
A_hat = calc_A_hat(A, skew_matrix(w))
u = sum(np.dot(Y, Y) for Y in Ys) / n
v = np.dot(A_hat, sum(np.dot(Y, Y) * Y for Y in Ys)) / np.trace(np.dot(A_hat, A))
return sum((np.dot(Y... | Calculate the G function given a cylinder direction w and a
list of data points Xs to be fitted. |
356,206 | def resolve(
requirements: typing.List[str],
index_urls: list = None,
python_version: int = 3,
exclude_packages: set = None,
transitive: bool = True,
subgraph_check_api: str = None,
) -> dict:
assert python_version in (2, 3), "Unknown Python version"
if subgraph_check_api and not t... | Resolve given requirements for the given Python version. |
356,207 | def remove_cache_tier(self, cache_pool):
mode = get_cache_mode(self.service, cache_pool)
if mode == :
check_call([, , self.service, , , , cache_pool, ])
check_call([, , self.service, , , , self.name, cache_pool])
elif mode == :
pool_forward_... | Removes a cache tier from Ceph. Flushes all dirty objects from writeback pools and waits for that to complete.
:param cache_pool: six.string_types. The cache tier pool name to remove.
:return: None |
356,208 | def Geldart_Ling(mp, rhog, D, mug):
r
Gs = mp/(pi/4*D**2)
if Gs/D <= 47000:
V = 1.5*Gs**0.465*D**-0.01*mug**0.055*rhog**-0.42
else:
V = 8.7*Gs**0.302*D**0.153*mug**0.055*rhog**-0.42
return V | r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_ as described in [2]_ and [3]_.
if Gs/D < 47000, use equation 1, otherwise use equation 2.
.. math::
V_{salt} = 1.5G_s^{0.465}D^{-0.01} \mu^{0.055}\rho_f^{-0.42}
V_{salt} = 8.7G_s^{0.302}D^{0.153} \mu^{... |
356,209 | def _handle_task(self):
headers = self.request.headers
message = None
try:
status_code, output = process_async_task(
headers, self.request.body)
except AbortAndRestart as restart:
status_code = 549
message =
... | Pass request info to the async framework. |
356,210 | def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):
local_buffer = utils.BytearrayStream()
if self._located_items:
self._located_items.write(local_buffer, kmip_version=kmip_version)
if self._unique_identifiers:
for unique_identifier in self... | Write the data encoding the Locate response payload to a buffer.
Args:
output_buffer (stream): A data buffer in which to encode object
data, supporting a write method.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the obj... |
356,211 | def _ir_cum2(self, alpha=1.0):
code, _ = self.encode()
N = self.n_states
BL = np.zeros(N - 1)
h0 = np.log2(np.cumsum(
[1.0 if sfx == 0 else 0.0 for sfx in self.sfx[1:]])
)
h1 = np.array([np.log2(i + 1) if m == 0 else np.log2(i + 1) + np.log2(m)
... | h1 = np.array([h if m == 0 else h+np.log2(m)
for h,m in zip(h0,self.lrs[1:])])
h1 = np.array([h if m == 0 else h+np.log2(m)
for h,m in zip(h0,self.max_lrs[1:])])
h1 = np.array([h if m == 0 else h+np.log2(m)
for h,m in zip(h0,self.av... |
356,212 | async def slowlog_get(self, num=None):
args = []
if num is not None:
args.append(num)
return await self.execute_command(*args) | Get the entries from the slowlog. If ``num`` is specified, get the
most recent ``num`` items. |
356,213 | def put(self, item, block=True, **kws):
return QPut(self, item, block, **kws) | Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available wi... |
356,214 | def prepend(self, node):
if not isinstance(node, grammar.STATEMENTS):
raise ValueError
self.to_prepend[-1].appendleft(node) | Prepend a statement to the current statement.
Note that multiple calls to prepend will result in the last statement to be
prepended to end up at the top.
Args:
node: The statement to prepend.
Raises:
ValueError: If the given node is not a statement. |
356,215 | def update_defaults(self, defaults):
config = {}
for section in (, self.name):
config.update(
self.normalize_keys(self.get_config_section(section))
)
if not self.isolated:
config.update(self.normalize_keys(se... | Updates the given defaults with values from the config files and
the environ. Does a little special handling for certain types of
options (lists). |
356,216 | def list_subnets(auth=None, **kwargs):
**{"tenant_id": "1dcac318a83b4610b7a7f7ba01465548"}
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.list_subnets(**kwargs) | List subnets
filters
A Python dictionary of filter conditions to push down
CLI Example:
.. code-block:: bash
salt '*' neutronng.list_subnets
salt '*' neutronng.list_subnets \
filters='{"tenant_id": "1dcac318a83b4610b7a7f7ba01465548"}' |
356,217 | def use_isolated_objective_bank_view(self):
self._objective_bank_view = ISOLATED
for session in self._get_provider_sessions():
try:
session.use_isolated_objective_bank_view()
except AttributeError:
pass | Pass through to provider ObjectiveLookupSession.use_isolated_objective_bank_view |
356,218 | def nlmsg_append(n, data, len_, pad):
tmp = nlmsg_reserve(n, len_, pad)
if tmp is None:
return -NLE_NOMEM
tmp[:len_] = data.bytearray[:len_]
_LOGGER.debug(, id(n), len_, pad)
return 0 | Append data to tail of a Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L442
Extends the Netlink message as needed and appends the data of given length to the message.
Positional arguments:
n -- Netlink message (nl_msg class instance).
data -- data to add.
len_ -... |
356,219 | def ck_portf_004(self):
return self.a.SD < 0.25 and self.a.stock_vol[-1] > 1000*1000 and self.a.raw_data[-1] > 10 | 價走平一個半月。(箱型整理、盤整) |
356,220 | def collect(since, to, top=DEFAULT_TOP):
summary = CspReportSummary(since, to, top=top)
queryset = CSPReport.objects.filter(created__range=(since, to))
valid_queryset = queryset.filter(is_valid=True)
invalid_queryset = queryset.filter(is_valid=False)
summary.total_count = queryset.count()
... | Collect the CSP report.
@returntype: CspReportSummary |
356,221 | def mfe(self, strand, degenerate=False, temp=37.0, pseudo=False,
material=None, dangles=, sodium=1.0, magnesium=0.0):
mfe\dnarnarna1999none\some\A dangle energy is incorporated for
each unpaired base flanking a duplex\allmfedotparenspairlist
material = self._... | Compute the MFE for an ordered complex of strands. Runs the \'mfe\'
command.
:param strand: Strand on which to run mfe. Strands must be either
coral.DNA or coral.RNA).
:type strand: coral.DNA or coral.RNA
:param degenerate: Setting to True will result in returning... |
356,222 | def build_machine_type(cls, min_cores, min_ram):
min_cores = min_cores or job_model.DEFAULT_MIN_CORES
min_ram = min_ram or job_model.DEFAULT_MIN_RAM
min_ram *= GoogleV2CustomMachine._MB_PER_GB
cores = cls._validate_cores(min_cores)
ram = cls._validate_ram(min_ram)
mem... | Returns a custom machine type string. |
356,223 | def cli(env, context_id):
manager = SoftLayer.IPSECManager(env.client)
manager.get_tunnel_context(context_id)
succeeded = manager.apply_configuration(context_id)
if succeeded:
env.out(
.format(context_id))
else:
raise CLIHalt(
.format(... | Request configuration of a tunnel context.
This action will update the advancedConfigurationFlag on the context
instance and further modifications against the context will be prevented
until all changes can be propgated to network devices. |
356,224 | def add_user_to_group(self, group_name, user_name):
params = { : group_name,
: user_name}
return self.get_response(, params) | Add a user to a group
:type group_name: string
:param group_name: The name of the group
:type user_name: string
:param user_name: The to be added to the group. |
356,225 | def all(self, data={}, **kwargs):
return super(Settlement, self).all(data, **kwargs) | Fetch all Settlement entities
Returns:
Dictionary of Settlement data |
356,226 | def update(self, E=None, **F):
if E is not None:
if hasattr(E, ):
for K in E:
self.replace(K, E[K])
elif hasattr(E, ):
for K, V in E.items():
self.replace(K, V)
else:
for K, V in ... | Update ContextDict from dict/iterable E and F
:return: Nothing
:rtype: None |
356,227 | def search_alert_for_facets(self, **kwargs):
kwargs[] = True
if kwargs.get():
return self.search_alert_for_facets_with_http_info(**kwargs)
else:
(data) = self.search_alert_for_facets_with_http_info(**kwargs)
return data | Lists the values of one or more facets over the customer's non-deleted alerts # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.search_alert_for_facets(async_req=True)
... |
356,228 | def reduce_data_frame_evenly_with_gaps (df, valcol, target_len, maxgap, **kwargs):
return reduce_data_frame (df,
slice_evenly_with_gaps (df[valcol], target_len, maxgap),
**kwargs) | Reduce" a DataFrame by collapsing rows in grouped chunks, grouping based on
gaps in one of the columns.
This function combines :func:`reduce_data_frame` with
:func:`slice_evenly_with_gaps`. |
356,229 | def _get_entity_prop(self, entity, prop):
variant = self.params.get()
lang = self.params.get()
if entity.get(prop):
ent = entity[prop]
try:
return ent[variant or lang].get()
except AttributeError:
return ent.get() | returns Wikidata entity property value |
356,230 | def validate_items(all_items):
validation = []
for item in all_items:
if item.talk is not None and item.page is not None:
validation.append(item)
elif item.talk is None and item.page is None:
validation.append(item)
elif item.talk and item.talk.status not in ... | Find errors in the schedule. Check for:
- pending / rejected talks in the schedule
- items with both talks and pages assigned
- items with neither talks nor pages assigned |
356,231 | def get_viewer_names(self, dataobj):
res = []
for bnch in self.viewer_db.values():
for vtype in bnch.vtypes:
if isinstance(dataobj, vtype):
res.append(bnch.vname)
return res | Returns a list of viewer names that are registered that
can view `dataobj`. |
356,232 | def update(self):
uri = self.parent.uri
script = r
self.res = c.evaluate_featurescript(uri.as_dict(), script) | Update all local variable names to match OnShape. |
356,233 | def instruments(
self,
accountID,
**kwargs
):
request = Request(
,
)
request.set_path_param(
,
accountID
)
request.set_param(
,
kwargs.get()
)
respons... | Get the list of tradeable instruments for the given Account. The list
of tradeable instruments is dependent on the regulatory division that
the Account is located in, thus should be the same for all Accounts
owned by a single user.
Args:
accountID:
Account Id... |
356,234 | def delete_policy(vhost, name, runas=None):
*
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_user()
res = __salt__[](
[RABBITMQCTL, , , vhost, name],
reset_system_locale=False,
runas=runas,
python_shell=False)
log.debug(, re... | Delete a policy based on rabbitmqctl clear_policy.
Reference: http://www.rabbitmq.com/ha.html
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.delete_policy / HA |
356,235 | def timed_for(iterable,
name=None,
rgstr_stamps=None,
save_itrs=SET[],
loop_end_stamp=None,
end_stamp_unique=SET[],
keep_prev_subdivisions=SET[],
keep_end_subdivisions=SET[],
quick_print=SET[]):
retu... | Instantiate a TimedLoop object for measuring for loop iteration timing data.
Can be used only on for loops.
Example::
for i in gtimer.timed_for(iterable, ..):
<body of loop with gtimer stamps>
Notes:
Can be used as a context manager around the loop. When breaking out of
... |
356,236 | def _spectrum(self, photon_energy):
outspecene = _validate_ene(photon_energy)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
self.nhat = 1.0
if np.any(outspecene < self.Etrans) and np.any(
outspecene >= self.Etrans
... | Compute differential spectrum from pp interactions using Eq.71 and
Eq.58 of Kelner, S.R., Aharonian, F.A., and Bugayov, V.V., 2006
PhysRevD 74, 034018 (`arXiv:astro-ph/0606058
<http://www.arxiv.org/abs/astro-ph/0606058>`_).
Parameters
----------
photon_energy : :class:`~... |
356,237 | def gap(lamda, sigma, mode=):
if numpy.isscalar(lamda):
lamda = [lamda]
lamda = numpy.array(lamda)
if numpy.isscalar(sigma):
sigma = [sigma]
sigma = numpy.array(sigma)
if not numpy.isreal(lamda).all() or not numpy.isreal(sigma).all():
raise ArgumentError()
if ... | Compute spectral gap.
Useful for eigenvalue/eigenvector bounds. Computes the gap
:math:`\delta\geq 0` between two sets of real numbers ``lamda`` and
``sigma``. The gap can be computed in several ways and may not exist, see
the ``mode`` parameter.
:param lamda: a non-empty set
:math:`\Lambda=... |
356,238 | def partitions(device=""):
partitions_list = {}
with settings(hide(, )):
res = run_as_root( % locals())
spart = re.compile(r)
for line in res.splitlines():
m = spart.search(line)
if m:
partitions_list[m.group()] = int(m.group(), 16)
retu... | Get a partition list for all disk or for selected device only
Example::
from burlap.disk import partitions
spart = {'Linux': 0x83, 'Swap': 0x82}
parts = partitions()
# parts = {'/dev/sda1': 131, '/dev/sda2': 130, '/dev/sda3': 131}
r = parts['/dev/sda1'] == spart['Linux']
... |
356,239 | def pack(self, out: IO):
out.write(pack(, len(self)))
for field in self._table:
field.pack(out) | Write the FieldTable to the file-like object `out`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when saving a ClassFile.
:param out: Any file-like object providing `write()` |
356,240 | def to_naf(self):
if self.type == :
for node in self.__get_entity_nodes():
node.set(,node.get())
del node.attrib[] | Converts the layer from NAF to KAF |
356,241 | def create_header(self):
try:
self.check_valid()
_header_list = []
for k,v in self.inputs.items():
if v is None:
return {self.__class__.__name__.replace(,):None}
elif k == :
_header_list.insert(0,str(v))
elif isinstance(v,bool):
if v is True:
_header_list.append(k)
el... | return header dict |
356,242 | def run(state, command, args):
from ..core import do_run
do_run(
command=command, args=args, three=state.three, python=state.python, pypi_mirror=state.pypi_mirror
) | Spawns a command installed into the virtualenv. |
356,243 | def order_status(self, order_id):
data = {: order_id}
return self._post("order_status/", data=data, return_json=True,
version=1) | Returns dictionary.
- status: 'Finished'
or 'In Queue'
or 'Open'
- transactions: list of transactions
Each transaction is a dictionary with the following keys:
btc, usd, price, type, fee, datetime, tid
or btc, eur, ....
or eur, ... |
356,244 | def cos(cls, x: ) -> :
return cls._unary_op(x, tf.cos, tf.float32) | Returns a TensorFluent for the cos function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the cos function. |
356,245 | def wrap_application(application, before_run, on_start, shutdown):
before_run = [] if before_run is None else before_run
on_start = [] if on_start is None else on_start
shutdown = [] if shutdown is None else shutdown
if not isinstance(application, Application):
application = _ApplicationA... | Wrap a tornado application in a callback-aware wrapper.
:param tornado.web.Application application: application to wrap.
:param list|NoneType before_run: optional list of callbacks
to invoke before the IOLoop is started.
:param list|NoneType on_start: optional list of callbacks to
register ... |
356,246 | def execute_work(self, key, command):
if key is None:
return
self.log.info("%s running %s", self.__class__.__name__, command)
try:
subprocess.check_call(command, close_fds=True)
state = State.SUCCESS
except subprocess.CalledProcessError as e:
... | Executes command received and stores result state in queue.
:param key: the key to identify the TI
:type key: tuple(dag_id, task_id, execution_date)
:param command: the command to execute
:type command: str |
356,247 | def parse(cls, datestr):
m = DATE_RE.match(datestr)
if m is not None:
day = None if m.group(2) is None else int(m.group(2))
return cls(m.group(4), m.group(3), day, m.group(1)) | Parse <DATE> string and make :py:class:`CalendarDate` from it.
:param str datestr: String with GEDCOM date. |
356,248 | def _init_seqarray(self, quiet=False):
try:
spath = open(self.files.data, )
except IOError:
raise IPyradWarningExit(NO_SNP_FILE.format(self.files.data))
line = spath.readline().strip().split()
ntax = int(line[0])
nbp = int(line[1])
... | Fills the seqarr with the full data set, and creates a bootsarr copy
with the following modifications:
1) converts "-" into "N"s, since they are similarly treated as missing.
2) randomly resolve ambiguities (RSKWYM)
3) convert to uint8 for smaller memory load and faster computation |
356,249 | def matchToFeatures(fiContainer, specContainer, specfiles=None, fMassKey=,
sMassKey=, isotopeErrorList=(0),
precursorTolerance=5, toleranceUnit=,
rtExpansionUp=0.10, rtExpansionDown=0.05, matchCharge=True,
scoreKey=, largerBetter=False):
... | Annotate :class:`Fi <maspy.core.Fi>` (Feature items) by matching
:class:`Si <maspy.core.Si>` (Spectrum items) or :class:`Sii
<maspy.core.Sii>` (Spectrum identification items).
:param fiContainer: :class:`maspy.core.FeatureContainer`, contains ``Fi``.
:param specContainer: :class:`maspy.core.MsrunContai... |
356,250 | def search_obsgroups(self, search):
b = search_obsgroups_sql_builder(search)
sql = b.get_select_sql(columns=
,
skip=search.skip,
limit=search.limit,
order=)
... | Search for :class:`meteorpi_model.ObservationGroup` entities
:param search:
an instance of :class:`meteorpi_model.ObservationGroupSearch` used to constrain the observations returned
from the DB
:return:
a structure of {count:int total rows of an unrestricted search, ... |
356,251 | def watch_crc(params, ctxt, scope, stream, coord):
if len(params) <= 1:
raise errors.InvalidArguments(coord, "{} args".format(len(params)), "at least two arguments")
to_update = params[0]
total_data = utils.binary("")
for param in params[1:]:
total_data += param._pfp__build()
... | WatchCrc32 - Watch the total crc32 of the params.
Example:
The code below uses the ``WatchCrc32`` update function to update
the ``crc`` field to the crc of the ``length`` and ``data`` fields ::
char length;
char data[length];
int crc<watch=length;data, updat... |
356,252 | def symm_reduce(self, coords_set, threshold=1e-6):
surf_sg = SpacegroupAnalyzer(self.slab, 0.1)
symm_ops = surf_sg.get_symmetry_operations()
unique_coords = []
coords_set = [self.slab.lattice.get_fractional_coords(coords)
for coords in coords_set]
... | Reduces the set of adsorbate sites by finding removing
symmetrically equivalent duplicates
Args:
coords_set: coordinate set in cartesian coordinates
threshold: tolerance for distance equivalence, used
as input to in_coord_list_pbc for dupl. checking |
356,253 | def get_limits_for_pool(self, pool):
pool_limits = self.cache.get("LIMIT:%s" % pool)
if pool_limits is None:
return {}
return json_loads(pool_limits) | meterer.get_limits_for_pool(pool) -> dict
Returns the limits for the given pool. If the pool does not have limits
set, {} is returned.
The resulting dict has the following format. Each item is optional and
indicates no limit for the specified time period.
{
"year": ... |
356,254 | def strip_xext(filepath):
ext_size = len(file_xext(filepath).split()) - 1
for i in xrange(0, ext_size):
filepath = os.path.splitext(filepath)[0]
return filepath | Strips the compression extension from the filename
:param filepath: Path to compressed file.
:return str filepath: Path to the file with the compression extension stripped off. |
356,255 | def update(self, value=None):
if value is None:
value = self._current_value + 1
self._current_value = value
if self._ipython_widget:
try:
self._update_ipython_widget(value)
except RuntimeError:
pass
... | Update progress bar via the console or notebook accordingly. |
356,256 | def update_complex(tree_to_update, xpath_root, xpath_map, prop, values):
remove_element(tree_to_update, xpath_root, True)
values = reduce_value(values, {})
if not values:
updated = update_property(tree_to_update, xpath_root, xpath_root, prop, values)
else:
for subprop, v... | Updates and returns the updated complex Element parsed from tree_to_update.
:param tree_to_update: the XML tree compatible with element_utils to be updated
:param xpath_root: the XPATH location of the root of the complex Element
:param xpath_map: a Dictionary of XPATHs corresponding to the complex structure... |
356,257 | def _getue(self):
try:
value, newpos = self._readue(0)
if value is None or newpos != self.len:
raise ReadError
except ReadError:
raise InterpretError("Bitstring is not a single exponential-Golomb code.")
return value | Return data as unsigned exponential-Golomb code.
Raises InterpretError if bitstring is not a single exponential-Golomb code. |
356,258 | def grant(self, fail_on_found=False, **kwargs):
return self.role_write(fail_on_found=fail_on_found, **kwargs) | Add a user or a team to a role. Required information:
1) Type of the role
2) Resource of the role, inventory, credential, or any other
3) A user or a team to add to the role
=====API DOCS=====
Add a user or a team to a role. Required information:
* Type of the role.
... |
356,259 | def validate(self, obj, pointer=None):
pointer = pointer or
validator = deepcopy(self)
validator.errors = []
validator.fail_fast = False
obj = deepcopy(obj)
obj = validator.validate_enum(obj, pointer)
obj = validator.validate_type(obj, pointer)
... | Validate object against validator
:param obj: the object to validate |
356,260 | def get_images(config, name=None, quiet=False, all=True, *args, **kwargs):
err = "Unknown"
client = _get_client(config)
try:
infos = client.images(name=name, quiet=quiet, all=all)
for i in range(len(infos)):
inf = _set_id(infos[i])
try:
inf[] = _s... | List docker images
:type name: string
:param name: A repository name to filter on
:type quiet: boolean
:param quiet: Only show image ids
:type all: boolean
:param all: Show all images
:rtype: dict
:returns: the images |
356,261 | def _cached(f):
attr_name = + f.__name__
def wrapper(obj, *args, **kwargs):
if not hasattr(obj, attr_name):
setattr(obj, attr_name, f(obj, *args, **kwargs))
return getattr(obj, attr_name)
return wrapper | Decorator that makes a method cached. |
356,262 | def grok_for_node(element, default_vars):
if isinstance(element.iter, jinja2.nodes.Filter):
if element.iter.name == \
and element.iter.node.name not in default_vars:
default_vars.append(element.iter.node.name)
default_vars = default_vars + grok_vars(element)
return... | Properly parses a For loop element |
356,263 | def get_valid_indentations(self, idx):
stack_top = -1
if (
self._tokens.token(idx) in ("}", "for")
and self._cont_stack[-1].token == ":"
):
stack_top = -2
indent = self._cont_stack[stack_top]
if self._tokens.token(idx... | Returns the valid offsets for the token at the given position. |
356,264 | def get_import_data_url(deployment_name,
token_manager=None,
app_url=defaults.APP_URL):
return get_data_url(deployment_name,
endpoint_type=,
app_url=app_url,
token_manager=token_manager) | return the import data url |
356,265 | def analyze_overs(self1):
self1.dif1 = [self1.overs[i][0]-self1.overs[i-1][0] for i in range(1,len(self1.overs))]
self1.dif2 = [self1.overs[i][1]-self1.overs[i-1][1] for i in range(1,len(self1.overs))]
self1.start1 = self1.overs[0][0] == 0
self1.start2 = self1.overs[0][1] ==... | A helper function that prepares overlap and consecutive matches data |
356,266 | def get_tags_of_reminder_per_page(self, reminder_id, per_page=1000, page=1):
return self._get_resource_per_page(
resource=REMINDER_TAGS,
per_page=per_page,
page=page,
params={: reminder_id},
) | Get tags of reminder per page
:param reminder_id: the reminder id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list |
356,267 | def save_htmlid(html_id, skiplint=False):
global html_ids
global lint_errors
html_id_clean = html_id.strip()
html_id_clean = html_id_clean.strip()
if re.match(r, html_id_clean) is None:
html_id_clean = .format(html_id_clean)
html_id_clean = re.sub(, , html_id... | Take a HTML ID, sanitise for HTML, check for duplicates and save.
Returns sanitised, unique ID |
356,268 | def get_user_details(self, response):
data = {}
data[] = response.get(, None)
data[] = response.get(, None)
if not data[]:
data[] = response.get(, None)
data[] = response.get(, None)
data[] = response.get(
, None)
data[] =... | Complete with additional information from original LTI POST data, as available. |
356,269 | def from_py_func(cls, code):
from bokeh.util.deprecation import deprecated
deprecated(" is deprecated and will be removed in an eventual 2.0 release. "
"Use CustomJSHover directly instead.")
if not isinstance(code, FunctionType):
raise ValueError()
... | Create a ``CustomJSHover`` instance from a Python functions. The
function is translated to JavaScript using PScript.
The python functions must have no positional arguments. It is
possible to pass Bokeh models (e.g. a ``ColumnDataSource``) as keyword
arguments to the functions.
... |
356,270 | def extract(self, searches, tree=None, as_dict=True):
if self.tree is None or self.pq is None:
self.load()
if tree is None:
pq = self.pq
else:
pq = PyQuery(tree, css_translator=PDFQueryTranslator())
results = []
formatter = No... | >>> foo = pdf.extract([['pages', 'LTPage']])
>>> foo
{'pages': [<LTPage>, <LTPage>]}
>>> pdf.extract([['bar', ':in_bbox("100,100,400,400")']], foo['pages'][0])
{'bar': [<LTTextLineHorizontal>, <LTTextBoxHorizontal>,... |
356,271 | def visit_insert(self, insert_stmt, asfrom=False, **kw):
self.stack.append(
{: set(),
"asfrom_froms": set(),
"selectable": insert_stmt})
self.isinsert = True
crud_params = crud._get_crud_params(self, insert_stmt, **kw)
if not crud_params ... | used to compile <sql.expression.Insert> expressions.
this function wraps insert_from_select statements inside
parentheses to be conform with earlier versions of CreateDB. |
356,272 | def sortino_ratio(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None,
_downside_risk=None):
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
return... | Determines the Sortino ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable re... |
356,273 | def tmpfile(root=TEMPS_DIR, prefix=TEMPS_PREFIX, suffix=TEMPS_SUFFIX):
path = tmppath(root, prefix, suffix)
try:
yield path
finally:
if os.path.isfile(path):
os.unlink(path) | For use in a with statement, this function returns a context manager that
yields a path directly under root guaranteed to be unique by using the uuid
module. This path is not created. However if the path is an existing file
when the with statement is exited, the file will be removed.
This function is... |
356,274 | def list_subtitles(self, video, languages):
subtitles = []
for name in self.providers:
if name in self.discarded_providers:
logger.debug(, name)
continue
provider_subtitles = self.list_subtitles_provider(name, v... | List subtitles.
:param video: video to list subtitles for.
:type video: :class:`~subliminal.video.Video`
:param languages: languages to search for.
:type languages: set of :class:`~babelfish.language.Language`
:return: found subtitles.
:rtype: list of :class:`~subliminal... |
356,275 | def get_hash_for(self, value):
if isinstance(value,dict) and in value:
return self.get_hash_for(value[])
serialized_value = self._serializer(value)
if isinstance(serialized_value, dict):
return hash(frozenset([
self.get_hash_for(x)
... | Get hash for a given value.
:param value: The value to be indexed
:type value: object
:return: Hashed value
:rtype: str |
356,276 | def sign(self, encoded):
signature = self._hmac.copy()
signature.update(encoded)
return signature.hexdigest().encode() | Return authentication signature of encoded bytes |
356,277 | def _include_paths_from_environ(env_prefix=):
paths = os.environ.get(env_prefix + )
if not paths:
return []
return paths.split() | Environment value via `/login;/register` |
356,278 | def command(name=None, cls=None, **attrs):
if cls is None:
cls = Command
def decorator(func):
if isinstance(func, Command):
raise TypeError()
return cls(func, name=name, **attrs)
return decorator | A decorator that transforms a function into a :class:`.Command`
or if called with :func:`.group`, :class:`.Group`.
By default the ``help`` attribute is received automatically from the
docstring of the function and is cleaned up with the use of
``inspect.cleandoc``. If the docstring is ``bytes``, then i... |
356,279 | def value(self, key, default=None):
if self._customFormat:
return self._customFormat.value(key, default)
else:
return unwrapVariant(super(XSettings, self).value(key)) | Returns the value for the given key for this settings instance.
:return <variant> |
356,280 | def rm_pawn(self, name, *args):
if name not in self.pawn:
raise KeyError("No Pawn named {}".format(name))
self.rm_arrows_to_and_from(name)
pwn = self.pawn.pop(name)
if pwn in self.selection_candidates:
self.selection_candidates.remove(pw... | Remove the :class:`Pawn` by the given name. |
356,281 | def emit_pdf(outputs, options):
cmd = options.pdf_cmd
cmd = cmd.replace(, options.pdfname)
if len(outputs) > 2:
cmd_print = cmd.replace(, .join(outputs[:2] + []))
else:
cmd_print = cmd.replace(, .join(outputs))
cmd = cmd.replace(, .join(outputs))
if not options.quiet:
... | Runs the PDF conversion command to generate the PDF. |
356,282 | def anm_score(self, x, y):
gp = GaussianProcessRegressor().fit(x, y)
y_predict = gp.predict(x)
indepscore = normalized_hsic(y_predict - y, x)
return indepscore | Compute the fitness score of the ANM model in the x->y direction.
Args:
a (numpy.ndarray): Variable seen as cause
b (numpy.ndarray): Variable seen as effect
Returns:
float: ANM fit score |
356,283 | def _declarations_as_string(self, declarations):
return .join( % (
d.name,
d.value.as_css(),
+ d.priority if d.priority else ) for d in declarations) | Returns a list of declarations as a formatted CSS string
:param declarations: The list of tinycss Declarations to format
:type declarations: list of tinycss.css21.Declaration
:returns: The CSS string for the declarations list
:rtype: str |
356,284 | def _run_custom_data_engine(self, start_id_obj, end_id_obj, start_timeperiod, end_timeperiod):
collection_name = context.process_context[self.process_name].source
iteration = 0
while True:
cursor = self.ds.cursor_fine(collection_name,
... | fine-tuned data engine. MongoDB legacy |
356,285 | def disvec(self, x, y, aq=None):
if aq is None: aq = self.model.aq.find_aquifer_data(x, y)
return np.sum(self.parameters * self.disvecinf(x, y, aq), 1) | Returns array of size (2, nparam, naq) |
356,286 | def compose(self, type, data):
try:
return self.registered_formats[type][](data)
except KeyError:
raise NotImplementedError("No composer found for "
"type ".format(type=type)) | Compose text as a format.
:param type: The unique name of the format
:param data: The text to compose as the format |
356,287 | def is_pigalle_class(kls: ClassVar) -> bool:
return (kls is PygalleBaseClass) or (issubclass(type(kls), PygalleBaseClass)) | Return true if the passed object as argument is a class being to the Pigalle framework.
# Arguments
kls: The class to check.
# Returns:
bool:
* True if class is Pigalle.
* False else. |
356,288 | def _index_document(self, document, force=False):
from ambry.util import int_maybe
time_coverage = document.pop(, [])
from_year = None
to_year = None
if time_coverage:
from_year = int_maybe(time_coverage[0])
to_year = int_maybe(time_coverage[-1])
... | Adds parition document to the index. |
356,289 | def add_params_to_qs(query, params):
if isinstance(params, dict):
params = params.items()
queryparams = urlparse.parse_qsl(query, keep_blank_values=True)
queryparams.extend(params)
return urlencode(queryparams) | Extend a query with a list of two-tuples. |
356,290 | async def add_relation(self, local_relation, remote_relation):
if not in local_relation:
local_relation = .format(self.name, local_relation)
return await self.model.add_relation(local_relation, remote_relation) | Add a relation to another application.
:param str local_relation: Name of relation on this application
:param str remote_relation: Name of relation on the other
application in the form '<application>[:<relation_name>]' |
356,291 | def set_device(self, dev):
log.debug("setting device to ".format(dev))
self.dev = dev
self.set_apps_list() | set the current device (that will be used for following API calls)
:param dict dev: device that should be used for the API calls
(can be obtained via get_devices function) |
356,292 | def getCallSourceLines(callFrame, icNames, icMethod):
code = callFrame.f_code
try:
if code.co_name == :
parentBlockStartLine = 1
lines = inspect.findsource(code)[0]
parentBlockSource = .join(lines)
... | Raises NoSourceAvailableError. |
356,293 | def save_schedule(self):
self.persist()
evt = salt.utils.event.get_event(, opts=self.opts, listen=False)
evt.fire_event({: True},
tag=) | Save the current schedule |
356,294 | def get_collection(self, folderid, username="", offset=0, limit=10):
if not username and self.standard_grant_type == "authorization_code":
response = self._req(.format(folderid), {
"offset":offset,
"limit":limit
})
else:
if n... | Fetch collection folder contents
:param folderid: UUID of the folder to list
:param username: The user to list folders for, if omitted the authenticated user is used
:param offset: the pagination offset
:param limit: the pagination limit |
356,295 | def create_application(connection: Optional[str] = None) -> Flask:
app = Flask(__name__)
flask_bootstrap.Bootstrap(app)
Admin(app)
connection = connection or DEFAULT_CACHE_CONNECTION
engine, session = build_engine_session(connection)
for name, add_admin in add_admins.items():
url... | Create a Flask application. |
356,296 | def do_setup(self, arg, arguments):
if arguments["init"]:
Console.ok("Initialize cmd3.yaml file")
from cmd3.yaml_setup import create_cmd3_yaml_file
force = arguments["--force"]
create_cmd3_yaml_file(force=force) | ::
Usage:
setup init [--force]
Copies a cmd3.yaml file into ~/.cloudmesh/cmd3.yaml |
356,297 | def get_Sb(data):
Sb, N = 0., 0.
for rec in data:
delta = 90. - abs(rec[])
if rec[] != 0:
k = rec[]
L = rec[] * np.pi / 180.
Nsi = rec[]
K = old_div(k, (2. * (1. + 3. * np.sin(L)**2) /
(5. - 3. * np.sin(L)**2)))
... | returns vgp scatter for data set |
356,298 | def save(self, path):
data = self.encode()
with open(path, "wb") as out:
out.write(data) | Save a binary copy of this report
Args:
path (string): The path where we should save the binary copy of the report |
356,299 | def _save(self):
collection = JSONClientValidated(,
collection=,
runtime=self._runtime)
collection.save(self._my_map) | Saves the current state of this AssessmentTaken.
Should be called every time the sections map changes. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.