Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
348,600 | def find_packages(
self,
name,
constraint=None,
extras=None,
allow_prereleases=False,
):
if constraint is None:
constraint = "*"
if not isinstance(constraint, VersionConstraint):
constraint = parse_constraint(constra... | Find packages on the remote server. |
348,601 | def _prepare_coords(lons1, lats1, lons2, lats2):
lons1 = numpy.radians(lons1)
lats1 = numpy.radians(lats1)
assert lons1.shape == lats1.shape
lons2 = numpy.radians(lons2)
lats2 = numpy.radians(lats2)
assert lons2.shape == lats2.shape
return lons1, lats1, lons2, lats2 | Convert two pairs of spherical coordinates in decimal degrees
to numpy arrays of radians. Makes sure that respective coordinates
in pairs have the same shape. |
348,602 | def remove_na(self, data, remove_na_how):
data = data.dropna(how=remove_na_how)
return data | Remove NAs from dataframe.
Parameters
----------
data : pd.DataFrame()
Dataframe to remove NAs from.
remove_na_how : str
Specificies how to remove NA i.e. all, any...
Returns
-------
pd.DataFrame()
Dataframe with ... |
348,603 | def normalize_attr_values(a: Any) -> np.ndarray:
scalar = False
if np.isscalar(a):
a = np.array([a])
scalar = True
arr = normalize_attr_array(a)
if np.issubdtype(arr.dtype, np.integer) or np.issubdtype(arr.dtype, np.floating):
pass
elif np.issubdtype(arr.dtype, np.character) or np.issubdtype(arr.dtype, n... | Take all kinds of input values and validate/normalize them.
Args:
a List, tuple, np.matrix, np.ndarray or sparse matrix
Elements can be strings, numbers or bools
Returns
a_normalized An np.ndarray with elements conforming to one of the valid Loom attribute types
Remarks:
This method should be used ... |
348,604 | def entry_point(items=tuple()):
try:
if not items:
from .example import ExampleCommand
from .version import Version
items = [(ExampleCommand.NAME, ExampleCommand),
(Version.NAME, Version)]
main("yaclifw", items=items)
except Stop as s... | External entry point which calls main() and
if Stop is raised, calls sys.exit() |
348,605 | def tmarker(self, lat, long, text, color=None, icon=None, style=None):
try:
self.dsmap = self._marker(
lat, long, text, self.dsmap, color, icon, True, style)
return self.dsmap
except Exception as e:
self.err(e, self.tmarker, "Can not get text ... | Returns the map with a text marker to the default map |
348,606 | def background_bin_from_string(background_bins, data):
used = numpy.array([], dtype=numpy.uint32)
bins = {}
for mbin in background_bins:
name, bin_type, boundary = tuple(mbin.split())
if boundary[0:2] == :
member_func = lambda vals, bd=boundary : vals < float(bd[2:])
... | Return template ids for each bin as defined by the format string
Parameters
----------
bins: list of strings
List of strings which define how a background bin is taken from the
list of templates.
data: dict of numpy.ndarrays
Dict with parameter key values and numpy.ndarray value... |
348,607 | def set_indexing(self, index_template):
objs = object_session(self)
if self.index.indimp != index_template.imp_name:
self._refresh_datatable_schema()
self.index.name = index_template.name
self.index.indimp = index_template.imp_name
... | Update a symbol's indexing strategy
Parameters
----------
index_template : bIndex or bIndex-like
An index template used to overwrite all
details about the symbol's current index. |
348,608 | def _avgConnectedSpanForColumn2D(self, columnIndex):
assert(self._inputDimensions.size == 2)
connected = self._connectedSynapses[columnIndex]
(rows, cols) = connected.reshape(self._inputDimensions).nonzero()
if rows.size == 0 and cols.size == 0:
return 0
rowSpan = rows.max() - rows.min()... | The range of connectedSynapses per column, averaged for each dimension.
This value is used to calculate the inhibition radius. This variation of
the function only supports a 2 dimensional column topology.
Parameters:
----------------------------
:param columnIndex: The index identifying a column... |
348,609 | def intersection(self, other):
copy = self.copy()
copy.intersection_update(other)
return copy | Return the intersection of two RangeSets as a new RangeSet.
(I.e. all elements that are in both sets.) |
348,610 | def estimateAbsoluteMagnitude(spectralType):
from .astroclasses import SpectralType
specType = SpectralType(spectralType)
if specType.classLetter == :
return np.nan
elif specType.classNumber == :
specType.classNumber = 5
if specType.lumType == :
specType.lumType = ... | Uses the spectral type to lookup an approximate absolute magnitude for
the star. |
348,611 | def write(self, text):
if sys.version_info[0] == 2:
text_bytes = str(text.upper() + ).encode()
else:
text_bytes = bytes(text.upper() + , )
self.ser.write(text_bytes) | Write text out to the arm. |
348,612 | def cognito_identity_identity_pool_id(self, lookup, default=None):
list_limit = 60
client = EFAwsResolver.__CLIENTS["cognito-identity"]
response = client.list_identity_pools(MaxResults=list_limit)
while "IdentityPools" in response:
for pool in response["IdentityPools"]:
i... | Args:
lookup: Cognito Federated Identity name, proto0-cms-identity-pool
default: the optional value to return if lookup failed; returns None if not set
Returns:
the Cognito Identity Pool ID corresponding to the given lookup, else default/None |
348,613 | def run(self, element, outfolder):
filepath = self.relative_path_for_element(element)
if outfolder and not os.path.isabs(filepath):
filepath = os.path.join(outfolder, filepath)
_logger.debug(.format(element, filepath))
self.ensure_folder(filepath)
self.gene... | Apply this task to model element. |
348,614 | def postage_update(self, tid, post_fee, session):
request = TOPRequest()
request[] = tid
request[] = post_fee
self.create(self.execute(request, session)[])
return self | taobao.trade.postage.update 修改订单邮费价格
修改订单邮费接口,通过传入订单编号和邮费价格,修改订单的邮费,返回修改时间modified,邮费post_fee,总费用total_fee。 |
348,615 | def intensities_from_grid_radii(self, grid_radii):
np.seterr(all=)
return np.multiply(self.intensity, np.exp(
np.multiply(-self.sersic_constant,
np.add(np.power(np.divide(grid_radii, self.effective_radius), 1. / self.sersic_index), -1)))) | Calculate the intensity of the Sersic light profile on a grid of radial coordinates.
Parameters
----------
grid_radii : float
The radial distance from the centre of the profile. for each coordinate on the grid. |
348,616 | def parse_uri(self, uri=None):
if not uri:
return rdflib.term.URIRef(self.root)
elif type(uri) == str:
if type(uri) == str and not uri.startswith():
return rdflib.term.URIRef("%s%s" % (self.root, uri))
else:
return rdflib.term.URIRef(uri)
elif type(uri) == rdflib.term.UR... | parses and cleans up possible uri inputs, return instance of rdflib.term.URIRef
Args:
uri (rdflib.term.URIRef,str): input URI
Returns:
rdflib.term.URIRef |
348,617 | def concatenate_block_managers(mgrs_indexers, axes, concat_axis, copy):
concat_plans = [get_mgr_concatenation_plan(mgr, indexers)
for mgr, indexers in mgrs_indexers]
concat_plan = combine_concat_plans(concat_plans, concat_axis)
blocks = []
for placement, join_units in concat_pl... | Concatenate block managers into one.
Parameters
----------
mgrs_indexers : list of (BlockManager, {axis: indexer,...}) tuples
axes : list of Index
concat_axis : int
copy : bool |
348,618 | def extract(cls, keystr):
regex = r % cls.ALLOWED_KEY
return re.match(regex, keystr).group(1) | for #{key} returns key |
348,619 | def get_service_endpoint_details(self, project, endpoint_id):
route_values = {}
if project is not None:
route_values[] = self._serialize.url(, project, )
if endpoint_id is not None:
route_values[] = self._serialize.url(, endpoint_id, )
response = self._se... | GetServiceEndpointDetails.
[Preview API] Get the service endpoint details.
:param str project: Project ID or project name
:param str endpoint_id: Id of the service endpoint.
:rtype: :class:`<ServiceEndpoint> <azure.devops.v5_0.service_endpoint.models.ServiceEndpoint>` |
348,620 | def SetPlatformArchContext():
_CONFIG.AddContext("Platform:%s" % platform.system().title())
machine = platform.uname()[4]
if machine in ["x86_64", "AMD64", "i686"]:
if platform.architecture()[0] == "32bit":
arch = "i386"
else:
arch = "amd64"
elif machine == "x86":
arch = "i3... | Add the running contexts to the config system. |
348,621 | def from_samples(cls, samples_like, vectors, info, vartype, variable_labels=None):
try:
record = data_struct_array(samples, **vectors)
if variable_labels is None:
__, num_variables = record.sample.shape
variable_labels =... | Build a response from samples.
Args:
samples_like:
A collection of samples. 'samples_like' is an extension of NumPy's array_like
to include an iterable of sample dictionaries (as returned by
:meth:`.Response.samples`).
data_vectors (dict[... |
348,622 | def fast_inhomo_bloch_equations(Ep, epsilonp, detuning_knob, T, gamma,
omega_level, rm, xi, theta,
unfolding, inhomogeneity, matrix_form=False,
file_name=None, return_code=False):
r
if not unfolding.lower_triangular:... | r"""Return a fast function that returns the numeric right-hand sides of \
inhomogeneous Bloch equations.
We test a basic two-level system.
>>> import numpy as np
>>> from scipy.constants import physical_constants
>>> from sympy import Matrix, symbols
>>> from fast.electric_field import electri... |
348,623 | def do_set(parser, token):
code = token.contents
firstspace = code.find()
if firstspace >= 0:
code = code[firstspace+1:]
return Setter(code) | Calls an arbitrary method on an object. |
348,624 | def setup_datafind_runtime_frames_single_call_perifo(cp, scienceSegs,
outputDir, tags=None):
datafindcaches, _ = \
setup_datafind_runtime_cache_single_call_perifo(cp, scienceSegs,
outputDir, tags=tags)... | This function uses the glue.datafind library to obtain the location of all
the frame files that will be needed to cover the analysis of the data
given in scienceSegs. This function will not check if the returned frames
cover the whole time requested, such sanity checks are done in the
pycbc.workflow.set... |
348,625 | def parse(self, file_obj):
configs = [self._config[0]]
for line in file_obj:
line = line.rstrip().lstrip()
if (line == ) or (line[0] == ):
continue
if in line:
key, value = line.split(, 1)
key = key.strip().low... | Read an OpenSSH config from the given file object.
@param file_obj: a file-like object to read the config file from
@type file_obj: file |
348,626 | def post_roles_request(request):
uuid_ = request.matchdict[]
posted_roles = request.json
with db_connect() as db_conn:
with db_conn.cursor() as cursor:
cursor.execute(, (uuid_,))
try:
cursor.fetchone()[0]
except TypeError:
... | Submission to create a role acceptance request. |
348,627 | def ptb_producer(raw_data, batch_size, num_steps, name=None):
with tf.name_scope(name, "PTBProducer", [raw_data, batch_size, num_steps]):
raw_data = tf.convert_to_tensor(raw_data, name="raw_data", dtype=tf.int32)
data_len = tf.size(raw_data)
batch_len = data_len // batch_size
data = tf.reshape(raw... | Iterate on the raw PTB data.
This chunks up raw_data into batches of examples and returns Tensors that
are drawn from these batches.
Args:
raw_data: one of the raw data outputs from ptb_raw_data.
batch_size: int, the batch size.
num_steps: int, the number of unrolls.
name: the name of this opera... |
348,628 | def parse(self, symbol: str) -> (str, str):
symbol_parts = symbol.split(":")
namespace = None
mnemonic = symbol
if len(symbol_parts) > 1:
namespace = symbol_parts[0]
mnemonic = symbol_parts[1]
self.namespace = namespace
self.mnemonic = m... | Splits the symbol into namespace, symbol tuple |
348,629 | def _clear_context(context):
for var in (x for x in __context__ if x.startswith()):
context.pop(var) | Clear variables stored in __context__. Run this function when a new version
of chocolatey is installed. |
348,630 | def drop_columns(
self, max_na_values: int = None, max_unique_values: int = None
):
step = {}
if max_na_values is not None:
step = {
: self.iid,
: ,
: % max_na_values
}
if max_unique_values is not None... | When max_na_values was informed, remove columns when the proportion of
total NA values more than max_na_values threshold.
When max_unique_values was informed, remove columns when the proportion
of the total of unique values is more than the max_unique_values
threshold, just for columns ... |
348,631 | def get_track_info(track_id):
logger.info()
info_url = url["trackinfo"].format(track_id)
r = requests.get(info_url, params={: CLIENT_ID}, stream=True)
item = r.json()
logger.debug(item)
return item | Fetches track info from Soundcloud, given a track_id |
348,632 | def does_table_exist(self, model_class):
sql = "SELECT count() FROM system.tables WHERE database = AND name = "
r = self._send(sql % (self.db_name, model_class.table_name()))
return r.text.strip() == | Checks whether a table for the given model class already exists.
Note that this only checks for existence of a table with the expected name. |
348,633 | def search_phenotype_association_sets(self, dataset_id):
request = protocol.SearchPhenotypeAssociationSetsRequest()
request.dataset_id = dataset_id
request.page_size = pb.int(self._page_size)
return self._run_search_request(
request, "phenotypeassociationsets",
... | Returns an iterator over the PhenotypeAssociationSets on the server. |
348,634 | def add_renderer(self, klass, *args, **kwargs):
renderer = klass(self.widget, *args, **kwargs)
self.widget.renderers.append(renderer)
return renderer | Add a renderer to the current scene.
**Parameter**
klass: renderer class
The renderer class to be added
args, kwargs:
Arguments used by the renderer constructor,
except for the *widget* argument.
.. seealso:: :py:class:`~chem... |
348,635 | def preserve_namespace(newns=None):
ns = cmds.namespaceInfo(an=True)
try:
cmds.namespace(set=newns)
yield
finally:
cmds.namespace(set=ns) | Contextmanager that will restore the current namespace
:param newns: a name of namespace that should be set in the beginning. the original namespace will be restored afterwards.
If None, does not set a namespace.
:type newns: str | None
:returns: None
:rtype: None
:raises: None |
348,636 | def dict2namedtuple(*args, **kwargs):
d = collections.OrderedDict(*args)
d.update(**kwargs)
return collections.namedtuple(typename="dict2namedtuple",
field_names=list(d.keys()))(**d) | Helper function to create a :class:`namedtuple` from a dictionary.
Example:
>>> t = dict2namedtuple(foo=1, bar="hello")
>>> assert t.foo == 1 and t.bar == "hello"
>>> t = dict2namedtuple([("foo", 1), ("bar", "hello")])
>>> assert t[0] == t.foo and t[1] == t.bar
.. warning::
... |
348,637 | def trace(self, *attributes):
@wrapt.decorator
def wrapper(wrapped, instance, args, kwargs):
if self._trace_all:
return wrapped(*args, **kwargs)
handler = instance
with tracer_stack_context():
try:
self._... | Function decorator that traces functions
NOTE: Must be placed before the Tornado decorators
@param attributes any number of request attributes
(strings) to be set as tags on the created span |
348,638 | def split_every(n, iterable):
items = iter(iterable)
return itertools.takewhile(bool, (list(itertools.islice(items, n)) for _ in itertools.count())) | Returns a generator that spits an iteratable into n-sized chunks. The last chunk may have
less than n elements.
See http://stackoverflow.com/a/22919323/503377. |
348,639 | def is_valid_ip(ip_address):
try:
ip = ipaddress.ip_address(u + ip_address)
return True
except ValueError as e:
return False | Check Validity of an IP address |
348,640 | def drop_app_cache(self, appid):
with shelve.open(self.shelve_path) as appshelve:
try:
del appshelve[str(appid)]
except KeyError:
pass
for imgtype in (, ):
filename = % (appid, imgtype)
imagepath =... | Drop all info about an app (images from filesystem and app info from shelve) |
348,641 | def DOMDebugger_removeXHRBreakpoint(self, url):
assert isinstance(url, (str,)
), "Argument must be of type str. Received type: " % type(
url)
subdom_funcs = self.synchronous_command(,
url=url)
return subdom_funcs | Function path: DOMDebugger.removeXHRBreakpoint
Domain: DOMDebugger
Method name: removeXHRBreakpoint
Parameters:
Required arguments:
'url' (type: string) -> Resource URL substring.
No return value.
Description: Removes breakpoint from XMLHttpRequest. |
348,642 | def getOverlaySortOrder(self, ulOverlayHandle):
fn = self.function_table.getOverlaySortOrder
punSortOrder = c_uint32()
result = fn(ulOverlayHandle, byref(punSortOrder))
return result, punSortOrder.value | Gets the sort order of the overlay. See SetOverlaySortOrder for how this works. |
348,643 | def as_xml(self, parent = None):
if parent is not None:
element = ElementTree.SubElement(parent, ITEM_TAG)
else:
element = ElementTree.Element(ITEM_TAG)
element.set("jid", unicode(self.jid))
if self.name is not None:
element.set("name", self.n... | Make an XML element from self.
:Parameters:
- `parent`: Parent element
:Types:
- `parent`: :etree:`ElementTree.Element` |
348,644 | def _ParseTimestamp(self, parser_mediator, row):
timestamp = row.get(, None)
if timestamp is not None:
try:
timestamp = int(timestamp, 10)
except (ValueError, TypeError):
parser_mediator.ProduceExtractionWarning(
.format(timestamp))
return dfdatetime_posix_tim... | Provides a timestamp for the given row.
If the Trend Micro log comes from a version that provides a POSIX timestamp,
use that directly; it provides the advantages of UTC and of second
precision. Otherwise fall back onto the local-timezone date and time.
Args:
parser_mediator (ParserMediator): me... |
348,645 | def dirichlet_like(x, theta):
R
x = np.atleast_2d(x)
theta = np.atleast_2d(theta)
if (np.shape(x)[-1] + 1) != np.shape(theta)[-1]:
raise ValueError()
return flib.dirichlet(x, theta) | R"""
Dirichlet log-likelihood.
This is a multivariate continuous distribution.
.. math::
f(\mathbf{x}) = \frac{\Gamma(\sum_{i=1}^k \theta_i)}{\prod \Gamma(\theta_i)}\prod_{i=1}^{k-1} x_i^{\theta_i - 1}
\cdot\left(1-\sum_{i=1}^{k-1}x_i\right)^\theta_k
:Parameters:
x : (n, k-1) ar... |
348,646 | def total_weight(self):
weights = self._raw_weights()
if weights.shape[1] == 0:
return 0.0
elif weights.shape[1] < self._ntaps:
return np.sum(np.mean(weights, axis=1))
else:
return self._filter_coeffs.dot(np.sum(weights, axis=0)) | Read a weight from the sensor in grams.
Returns
-------
weight : float
The sensor weight in grams. |
348,647 | def satisfiable(self, **kwargs):
if o.ABSTRACT_SOLVER in self.options or o.SYMBOLIC not in self.options:
extra_constraints = kwargs.pop(, ())
for e in extra_constraints:
if self.solver.is_false(e):
return False
return self._satisf... | Whether the state's constraints are satisfiable |
348,648 | def lazy_callable(modname, *names, **kwargs):
if not names:
modname, _, name = modname.rpartition(".")
lazy_mod_class = _setdef(kwargs, , LazyModule)
lazy_call_class = _setdef(kwargs, , LazyCallable)
error_strings = _setdef(kwargs, , {})
_set_default_errornames(modname, error_strings, c... | Performs lazy importing of one or more callables.
:func:`lazy_callable` creates functions that are thin wrappers that pass
any and all arguments straight to the target module's callables. These can
be functions or classes. The full loading of that module is only actually
triggered when the returned laz... |
348,649 | def get_relationship_query_session_for_family(self, family_id):
if not self.supports_relationship_query():
raise errors.Unimplemented()
return sessions.RelationshipQuerySession(family_id, runtime=self._runtime) | Gets the ``OsidSession`` associated with the relationship query service for the given family.
arg: family_id (osid.id.Id): the ``Id`` of the family
return: (osid.relationship.RelationshipQuerySession) - a
``RelationshipQuerySession``
raise: NotFound - no ``Family`` found by ... |
348,650 | def create_package(package_format, owner, repo, **kwargs):
client = get_packages_api()
with catch_raise_api_exception():
upload = getattr(client, "packages_upload_%s_with_http_info" % package_format)
data, _, headers = upload(
owner=owner, repo=repo, data=make_create_payload(*... | Create a new package in a repository. |
348,651 | def _Operation(self,operation):
try:
return(clc.v2.Requests(clc.v2.API.Call(, % (self.alias,operation),
json.dumps(self.servers_lst),
session=self.session),
alias=self.alias,session=self.session))
except clc.APIFailedResponse as e:
re... | Execute specified operations task against one or more servers.
Returns a clc.v2.Requests object. If error due to server(s) already being in
the requested state this is not raised as an error at this level.
>>> clc.v2.Servers(["NY1BTDIPHYP0101","NY1BTDIWEB0101"]).Pause()
<clc.APIv2.queue.Requests object at 0x... |
348,652 | def fix_e711(self, result):
(line_index, offset, target) = get_index_offset_contents(result,
self.source)
right_offset = offset + 2
if right_offset >= len(target):
return []
left = target[:offset].rst... | Fix comparison with None. |
348,653 | def balanced_binning_reference(y, ax=None, target=, bins=4, **kwargs):
visualizer = BalancedBinningReference(ax=ax, bins=bins, target=target, **kwargs)
visualizer.fit(y)
visualizer.poof() | BalancedBinningReference generates a histogram with vertical lines
showing the recommended value point to bin your data so they can be evenly
distributed in each bin.
Parameters
----------
y : an array of one dimension or a pandas Series
ax : matplotlib Axes, default: None
This is ... |
348,654 | def get_addresses(self, start, count=1, step=1):
if count < 1:
raise with_context(
exc=ValueError(),
context={
: start,
: count,
: step,
},
)
if not ste... | Generates and returns one or more addresses at the specified
index(es).
This is a one-time operation; if you want to create lots of
addresses across multiple contexts, consider invoking
:py:meth:`create_iterator` and sharing the resulting generator
object instead.
Warni... |
348,655 | def heatmapf(func, scale=10, boundary=True, cmap=None, ax=None,
scientific=False, style=, colorbar=True,
permutation=None, vmin=None, vmax=None, cbarlabel=None,
cb_kwargs=None):
data = dict()
for i, j, k in simplex_iterator(scale=scale, boundary=boundary):
... | Computes func on heatmap partition coordinates and plots heatmap. In other
words, computes the function on lattice points of the simplex (normalized
points) and creates a heatmap from the values.
Parameters
----------
func: Function
A function of 3-tuples to be heatmapped
scale: Integer... |
348,656 | def poa_components(aoi, dni, poa_sky_diffuse, poa_ground_diffuse):
r
poa_direct = np.maximum(dni * np.cos(np.radians(aoi)), 0)
poa_diffuse = poa_sky_diffuse + poa_ground_diffuse
poa_global = poa_direct + poa_diffuse
irrads = OrderedDict()
irrads[] = poa_global
irrads[] = poa_direct
irr... | r'''
Determine in-plane irradiance components.
Combines DNI with sky diffuse and ground-reflected irradiance to calculate
total, direct and diffuse irradiance components in the plane of array.
Parameters
----------
aoi : numeric
Angle of incidence of solar rays with respect to the modu... |
348,657 | def __check_parameters(self):
if (self.__amount <= 0) or (self.__amount > len(self.__data)):
raise AttributeError("Amount of cluster centers should be at least 1 and "
"should be less or equal to amount of points in data.")
if self.__candidates != ... | !
@brief Checks input parameters of the algorithm and if something wrong then corresponding exception is thrown. |
348,658 | def _get_longest_hit_at_qry_end(self, nucmer_hits):
hits_at_end = [hit for hit in nucmer_hits if self._is_at_qry_end(hit)]
return self._get_longest_hit_by_ref_length(hits_at_end) | Input: list of nucmer hits to the same query. Returns the longest hit to the end of the query, or None if there is no such hit |
348,659 | def download_yield_bytes(url, chunk_size=1024 * 1024 * 10):
response = requests.get(url, stream=True)
response.raise_for_status()
total_length = response.headers.get()
if total_length is not None:
total_length = float(total_length)
length_str = "{0:.2f}Mb ".format(total_length... | Yield a downloaded url as byte chunks.
:param url: str or url
:param chunk_size: None or int in bytes
:yield: byte chunks |
348,660 | def get_edges(self):
edge_from_to = []
for parent, children in self.p_from_cs.items():
for child in children:
edge_from_to.append((child, parent))
for parent, children in self.c_from_ps.items():
for child in children:
edge_from_to.... | Get the directed edges from GO term to GO term. |
348,661 | async def render(
text: TransText,
request: Optional[],
multi_line=False) -> Union[Text, List[Text]]:
if isinstance(text, str):
out = [text]
elif isinstance(text, StringToTranslate):
out = await text.render_list(request)
else:
raise TypeError()
if m... | Render either a normal string either a string to translate into an actual
string for the specified request. |
348,662 | def update_hosts_file_from_port_spec(port_spec):
logging.info()
hosts_specs = port_spec[]
current_hosts = config_file.read(constants.HOSTS_PATH)
cleared_hosts = config_file.remove_current_dusty_config(current_hosts)
updated_hosts = cleared_hosts + _dusty_hosts_config(hosts_specs)
config_fil... | Given a port spec, update the hosts file specified at
constants.HOST_PATH to contain the port mappings specified
in the spec. Any existing Dusty configurations are replaced. |
348,663 | def to_package(self, repo_url):
return Package(name=self.name, url=repo_url + self.name) | Return the package representation of this repo. |
348,664 | def gen_key(self, *values):
key = md5()
KeyGen._recursive_convert(values, key)
return key.hexdigest() | Generate a key from one or more values. |
348,665 | def get_option_int(self, name, section=None, vars=None, expect=None):
val = self.get_option(name, section, vars, expect)
if val:
return int(val) | Just like ``get_option`` but parse as an integer. |
348,666 | def parse_directory_index(directory_index):
if not directory_index.endswith():
directory_index = directory_index +
site_index = urllib2.urlopen(directory_index)
parsed_site_index = bs(site_index)
rpm_link_tags = parsed_site_index.findAll(, href=re.compile(r))
rpm_names = [l... | Retrieve a directory index and make a list of the RPMs listed. |
348,667 | def rename_calendar_resource(self, r_description, new_r_name):
resp = self.request(, {
: self._get_or_fetch_id(r_description,
self.get_calendar_resource),
: new_r_name
})
return zobjects.CalendarResource.from_dict(resp[]) | :param r_description : a CalendarResource specifying either :
- id: the ressource ID
- r_description: the name of the ressource
:param new_r_name: new name of the list
:return: a zobjects.CalendarResource |
348,668 | def sde(self):
if self.approx_order is not None:
N = int(self.approx_order)
else:
N = 7
p_period = float(self.period)
p_lengthscale = 2*float(self.lengthscale)
p_variance = ... | Return the state space representation of the standard periodic covariance.
! Note: one must constrain lengthscale not to drop below 0.2. (independently of approximation order)
After this Bessel functions of the first becomes NaN. Rescaling
time variable might help.
... |
348,669 | def app_reverse(parser, token):
bits = token.split_contents()
if len(bits) < 3:
raise TemplateSyntaxError(
" takes at least two arguments"
" (path to a view and a urlconf)" % bits[0])
viewname = parser.compile_filter(bits[1])
urlconf = parser.compile_filter(bits[2])
... | Returns an absolute URL for applications integrated with ApplicationContent
The tag mostly works the same way as Django's own {% url %} tag::
{% load leonardo_tags %}
{% app_reverse "mymodel_detail" "myapp.urls" arg1 arg2 %}
or
{% load leonardo_tags %}
{% app_reverse "mymodel... |
348,670 | def off(self, event):
try:
self._once_events.remove(event)
except KeyError:
pass
self._callback_by_event.pop(event, None) | Remove an event handler |
348,671 | def _update_current(self):
prefix = self._current_text_cursor().selection().toPlainText()
if prefix:
items = self.findItems(prefix, (QtCore.Qt.MatchStartsWith |
QtCore.Qt.MatchCaseSensitive))
if items:
self.setC... | Updates the current item based on the current text. |
348,672 | def value_counts(values, sort=True, ascending=False, normalize=False,
bins=None, dropna=True):
from pandas.core.series import Series, Index
name = getattr(values, , None)
if bins is not None:
try:
from pandas.core.reshape.tile import cut
values = Series... | Compute a histogram of the counts of non-null values.
Parameters
----------
values : ndarray (1-d)
sort : boolean, default True
Sort by values
ascending : boolean, default False
Sort in ascending order
normalize: boolean, default False
If True then compute a relative his... |
348,673 | def make_virtualenv(env):
if find_executable("virtualenv") is not None:
cmd = ["virtualenv"] + [env]
subprocess.check_call(cmd)
else:
path = urlretrieve(VENV_URL)[0]
subprocess.check_call(["tar", "xzf", path])
subprocess.check_call(
[sys.executab... | Create a virtualenv |
348,674 | def get_visible_items(self):
items = []
iterator = QTreeWidgetItemIterator(self)
while iterator.value():
item = iterator.value()
if not item.isHidden():
if item.parent():
if item.parent().isExpanded():
... | Return a list of all visible items in the treewidget. |
348,675 | def register(self, username, password, attr_map=None):
attributes = self.base_attributes.copy()
if self.custom_attributes:
attributes.update(self.custom_attributes)
cognito_attributes = dict_to_cognito(attributes, attr_map)
params = {
: self.client_id,
... | Register the user. Other base attributes from AWS Cognito User Pools
are address, birthdate, email, family_name (last name), gender,
given_name (first name), locale, middle_name, name, nickname,
phone_number, picture, preferred_username, profile, zoneinfo,
updated at, website
:p... |
348,676 | def html_for_env_var(key):
value = os.getenv(key)
return KEY_VALUE_TEMPLATE.format(key, value) | Returns an HTML snippet for an environment variable.
Args:
key: A string representing an environment variable name.
Returns:
String HTML representing the value and variable. |
348,677 | def split_strings(string, separators):
logger = logging.getLogger()
logger.debug("splitting string with separators {1}".format(
string, separators
))
results = []
def recursion(recursive_string, separators, i=1):
if i == len(separators):
for value in r... | Split a string with arbitrary number of separators.
Return a list with the splitted values
Arguments:
string (str): ex. "a:1|2,b:2"
separators (list): ex. [',',':','|']
Returns:
results (list) : ex. ['a','1','2','b','2'] |
348,678 | def is_comment_deleted(comid):
query =
params = (comid,)
res = run_sql(query, params)
if res and res[0][0] != :
return True
return False | Return True of the comment is deleted. Else False
:param comid: ID of comment to check |
348,679 | def label_from_attrs(da, extra=):
if da.attrs.get():
name = da.attrs[]
elif da.attrs.get():
name = da.attrs[]
elif da.name is not None:
name = da.name
else:
name =
if da.attrs.get():
units = .format(da.attrs[])
else:
units =
return .j... | Makes informative labels if variable metadata (attrs) follows
CF conventions. |
348,680 | def _init_dataframes(self):
df = pd.read_sql_query("SELECT elapsed, epoch, scriptrun_time, custom_timers FROM result ORDER BY epoch ASC",
db.get_conn())
self._get_all_timers(df)
self.main_results = self._get_processed_dataframe(df)
for k... | Initialise the main dataframe for the results and the custom timers dataframes |
348,681 | def create_cname(data, **api_opts):
infoblox = _get_infoblox(**api_opts)
host = infoblox.create_cname(data=data)
return host | Create a cname record.
CLI Example:
.. code-block:: bash
salt-call infoblox.create_cname data={ \
"comment": "cname to example server", \
"name": "example.example.com", \
"zone": "example.com", \
"view": "Internal", \
"canonical": "example-h... |
348,682 | def fielddefsql_from_fieldspec(fieldspec: FIELDSPEC_TYPE) -> str:
sql = fieldspec["name"] + " " + fieldspec["sqltype"]
if "notnull" in fieldspec and fieldspec["notnull"]:
sql += " NOT NULL"
if "autoincrement" in fieldspec and fieldspec["autoincrement"]:
sql += " ... | Returns SQL fragment to define a field. |
348,683 | def get_content(url, user=None, password=None, proxy=None, data=None,
addheaders=None):
from . import configuration
headers = {
: configuration.UserAgent,
}
if addheaders:
headers.update(addheaders)
method =
kwargs = dict(headers=headers)
if user and pas... | Get URL content and info.
@return: (decoded text content of URL, headers) or
(None, errmsg) on error.
@rtype: tuple (String, dict) or (None, String) |
348,684 | def focusNextPrevChild(self, next_child):
fd = focus_registry.focused_declaration()
if next_child:
child = self.declaration.next_focus_child(fd)
reason = Qt.TabFocusReason
else:
child = self.declaration.previous_focus_child(fd)
reason = Qt... | The default 'focusNextPrevChild' implementation. |
348,685 | def sprite_map(g, **kwargs):
if not Image:
raise SassMissingDependency(, )
sprite_maps = _get_cache()
now_time = time.time()
globs = String(g, quotes=None).value
globs = sorted(g.strip() for g in globs.split())
_k_ = .join(globs)
files = None
rfiles = None
tfiles = ... | Generates a sprite map from the files matching the glob pattern.
Uses the keyword-style arguments passed in to control the placement.
$direction - Sprite map layout. Can be `vertical` (default), `horizontal`, `diagonal` or `smart`.
$position - For `horizontal` and `vertical` directions, the position of th... |
348,686 | def reindex_like_indexers(target, other):
indexers = {k: v for k, v in other.indexes.items() if k in target.dims}
for dim in other.dims:
if dim not in indexers and dim in target.dims:
other_size = other.sizes[dim]
target_size = target.sizes[dim]
if other_size !=... | Extract indexers to align target with other.
Not public API.
Parameters
----------
target : Dataset or DataArray
Object to be aligned.
other : Dataset or DataArray
Object to be aligned with.
Returns
-------
Dict[Any, pandas.Index] providing indexes for reindex keyword ... |
348,687 | def merge_metadata(preprocess_output_dir, transforms_file):
numerical_anlysis_file = os.path.join(preprocess_output_dir,
NUMERICAL_ANALYSIS)
schema_file = os.path.join(preprocess_output_dir, SCHEMA_FILE)
numerical_anlysis = json.loads(
python_portable_string(
... | Merge schema, analysis, and transforms files into one python object.
Args:
preprocess_output_dir: the output folder of preprocessing. Should contain
the schema, and the numerical and categorical
analysis files.
transforms_file: the training transforms file.
Returns:
A dict in the form
... |
348,688 | def block_header_verify( block_data, prev_hash, block_hash ):
serialized_header = block_header_to_hex( block_data, prev_hash )
candidate_hash_bin_reversed = hashing.bin_double_sha256(binascii.unhexlify(serialized_header))
candidate_hash = binascii.hexlify( candidate_hash_bin_reversed[::-1] )
retur... | Verify whether or not bitcoind's block header matches the hash we expect. |
348,689 | def downgrade():
if op._proxy.migration_context.dialect.name == :
op.alter_column(
,
,
type_=sa.dialects.postgresql.JSON,
postgresql_using=
) | Downgrade database. |
348,690 | def _execute_cmd(plugin, args=, run_type=):
s in the directory with salt command specified in run_type
{0}{1} {2}'.format(PLUGINDIR, plugin, args),
python_shell=False)
return data | Execute nagios plugin if it's in the directory with salt command specified in run_type |
348,691 | def peek_openssl_error():
error = libcrypto.ERR_peek_error()
lib = int((error >> 24) & 0xff)
func = int((error >> 12) & 0xfff)
reason = int(error & 0xfff)
return (lib, func, reason) | Peeks into the error stack and pulls out the lib, func and reason
:return:
A three-element tuple of integers (lib, func, reason) |
348,692 | def init_blueprint(self, blueprint, path=):
if self._route is not None:
raise TypeError("route cannot be set when using blueprints!")
blueprint.ask = self
blueprint.add_url_rule("", view_func=self._flask_view_func, methods=[])
... | Initialize a Flask Blueprint, similar to init_app, but without the access
to the application config.
Keyword Arguments:
blueprint {Flask Blueprint} -- Flask Blueprint instance to initialize (Default: {None})
path {str} -- path to templates yaml file, relative to Blueprint (Defau... |
348,693 | def forBurst(self, tag, outputFile = None, dropList = None, lower = True, removeNumbers = True, removeNonWords = True, removeWhitespace = True, stemmer = None):
whiteSpaceRegex = re.compile(r)
if removeNumbers:
if removeNonWords:
otherString = r"[\W\d]"
... | Creates a pandas friendly dictionary with 2 columns one `'year'` and the other `'word'`. Each row is a word that occurred in the field given by _tag_ in a `Record` and the year of the record. Unfortunately getting the month or day with any type of accuracy has proved to be impossible so year is the only option.
... |
348,694 | def validate(self, lsid, check_existing=True):
if not lsid.startswith(self.base_lsid):
return False
if check_existing and lsid in self.registered_modules:
return False
return True | Validates an LSID with the LSID authority.
:param lsid:
:return: boolean - is the LSID valid with this authority? |
348,695 | def move(self, old_path, new_path, raise_if_exists=False):
if raise_if_exists and os.path.exists(new_path):
raise FileAlreadyExists( % new_path)
d = os.path.dirname(new_path)
if d and not os.path.exists(d):
self.mkdir(d)
try:
os.rename(old_pat... | Move file atomically. If source and destination are located
on different filesystems, atomicity is approximated
but cannot be guaranteed. |
348,696 | def _collapse(intervals):
span = None
for start, stop in intervals:
if span is None:
span = _Interval(start, stop)
elif start <= span.stop < stop:
span = _Interval(span.start, stop)
elif start > span.stop:
yield span
span = _Interval(s... | Collapse an iterable of intervals sorted by start coord. |
348,697 | def run_cmd(command, verbose=True, shell=):
process = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT, executable=shell)
output = process.stdout.read().decode().strip().split()
if verbose:
return output
return [line for line in output if line.strip()] | internal helper function to run shell commands and get output |
348,698 | def add_pid(self, qname, sname, value, sym=True):
self.percentage_identity.loc[qname, sname] = value
if sym:
self.percentage_identity.loc[sname, qname] = value | Add a percentage identity value to self.percentage_identity. |
348,699 | def clip(arg, lower=None, upper=None):
if lower is None and upper is None:
raise ValueError("at least one of lower and " "upper must be provided")
op = ops.Clip(arg, lower, upper)
return op.to_expr() | Trim values at input threshold(s).
Parameters
----------
lower : float
upper : float
Returns
-------
clipped : same as type of the input |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.