Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
359,400 | def serialise_to_nrml(self, filename, use_defaults=False):
source_model = self.convert_to_oqhazardlib(
PoissonTOM(1.0), 2.0, 2.0, 10.0, use_defaults=use_defaults)
write_source_model(filename, source_model, name=self.name) | Writes the source model to a nrml source model file given by the
filename
:param str filename:
Path to output file
:param bool use_defaults:
Boolean to indicate whether to use default values (True) or not.
If set to False, ValueErrors will be raised when an ... |
359,401 | def one_step(self, current_state, previous_kernel_results):
with tf.compat.v1.name_scope(
name=mcmc_util.make_name(self.name, , ),
values=[previous_kernel_results]):
transformed_next_state, kernel_results = self._inner_kernel.one_step(
previous_kernel_results.transformed_state,
... | Runs one iteration of the Transformed Kernel.
Args:
current_state: `Tensor` or Python `list` of `Tensor`s
representing the current state(s) of the Markov chain(s),
_after_ application of `bijector.forward`. The first `r`
dimensions index independent chains,
`r = tf.rank(target... |
359,402 | def centre_of_atoms(atoms, mass_weighted=True):
points = [x._vector for x in atoms]
if mass_weighted:
masses = [x.mass for x in atoms]
else:
masses = []
return centre_of_mass(points=points, masses=masses) | Returns centre point of any list of atoms.
Parameters
----------
atoms : list
List of AMPAL atom objects.
mass_weighted : bool, optional
If True returns centre of mass, otherwise just geometric centre of points.
Returns
-------
centre_of_mass : numpy.array
3D coordi... |
359,403 | def _contextualise(self):
deja_vues = []
for rank in reversed(self.taxonomy):
clades = [e for e in self.hierarchy[rank] if e[1]]
uniques = [e for e in clades if len(e[0]) == 1]
uniques = [e... | Determine contextual idents (cidents) |
359,404 | def merge(self, evaluation_context: ) -> None:
self.global_context.merge(evaluation_context.global_context)
self.local_context.merge(evaluation_context.local_context) | Merges the provided evaluation context to the current evaluation context.
:param evaluation_context: Evaluation context to merge. |
359,405 | def parse(self, inputstring, parser, preargs, postargs):
self.reset()
pre_procd = None
with logger.gather_parsing_stats():
try:
pre_procd = self.pre(inputstring, **preargs)
parsed = parse(parser, pre_procd)
out = self.post(pars... | Use the parser to parse the inputstring with appropriate setup and teardown. |
359,406 | def fill_wildcards(self, field=None, value=0):
if field in [None, ] or isinstance(value, Pad):
return
default_value = getattr(Match, field)
if isinstance(default_value, IPAddress):
if field == :
shift = FlowWildCards.OFPFW_NW_DST_SHIFT
... | Update wildcards attribute.
This method update a wildcards considering the attributes of the
current instance.
Args:
field (str): Name of the updated field.
value (GenericType): New value used in the field. |
359,407 | def num2bytes(value, size):
res = []
for _ in range(size):
res.append(value & 0xFF)
value = value >> 8
assert value == 0
return bytes(bytearray(list(reversed(res)))) | Convert an unsigned integer to MSB-first bytes with specified size. |
359,408 | def token(self):
active_ids = []
shard_tokens = []
for root in self.roots:
for shard in root.walk_tree():
shard_tokens.append(shard.token)
shard_tokens[-1].pop("stream_arn")
active_ids.extend((shard.shard_id f... | JSON-serializable representation of the current Stream state.
Use :func:`Engine.stream(YourModel, token) <bloop.engine.Engine.stream>` to create an identical stream,
or :func:`stream.move_to(token) <bloop.stream.Stream.move_to>` to move an existing stream to this position.
:returns: Stream sta... |
359,409 | def pkg_by_name(self, name):
pkgmatches = self.all_pkgs_by_name(name)
if (len(pkgmatches) != 0):
return self.all_pkgs_by_name(name)[-1]
else:
return None | Return a single package that matches name. |
359,410 | def is_method(func):
func0 = _actualfunc(func)
argNames = getargnames(getargspecs(func0))
if len(argNames) > 0:
if argNames[0] == :
if inspect.ismethod(func):
return True
elif sys.version_info.major >= 3:
... | Detects if the given callable is a method. In context of pytypes this
function is more reliable than plain inspect.ismethod, e.g. it automatically
bypasses wrappers from typechecked and override decorators. |
359,411 | def mr(items, targets, **kwargs):
bins = [(target, []) for target in targets]
skip = []
for item in items:
capacities = [target - sum(content) for target, content in bins]
weighted = weight(capacities, **kwargs)
(target, content), capacity, _ = max(zip(bins, capacities, weight... | Max-Rest
Complexity O(n^2) |
359,412 | def make_zip(folder_path, output_filename):
cwd = os.getcwd()
file_lists = []
for root, dirs, files in os.walk(folder_path):
for file in files:
file_1 = os.path.join(root, file).replace(folder_path + , )
if not in file_1:
file_lists.append(file_1)
... | 将目录中除zip之外的文件打包成zip文件(包括子文件夹)
空文件夹不会被打包
example
----------------
make_zip('results','zips//招标信息结果_2017-05-09.zip') |
359,413 | def _hasExplicitOid(store, table):
return any(info[1] == for info
in store.querySchemaSQL(
.format(table))) | Does the given table have an explicit oid column? |
359,414 | def shorrocks_index(A):
r
A = np.asarray(A)
m, n = A.shape
if m != n:
raise ValueError()
diag_sum = np.diag(A).sum()
return (m - diag_sum) / (m - 1) | r"""
Implements Shorrocks mobility index
Parameters
-----------
A : array_like(float)
Square matrix with transition probabilities (mobility matrix) of
dimension m
Returns
--------
Shorrocks index: float
The Shorrocks mobility index calculated as
.. math::
... |
359,415 | def reverse_geocode(self, lat, lng, **kwargs):
return self.geocode(_query_for_reverse_geocoding(lat, lng), **kwargs) | Given a latitude & longitude, return an address for that point from OpenCage's Geocoder.
:param lat: Latitude
:param lng: Longitude
:return: Results from OpenCageData
:rtype: dict
:raises RateLimitExceededError: if you have exceeded the number of queries you can make. Exception ... |
359,416 | def validate_full_name(self, full_name, timeout=-1):
uri = self.URI + + full_name
return self._client.create_with_zero_body(uri=uri, timeout=timeout) | Verifies if a fullName is already in use.
Args:
full_name:
The fullName to be verified.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in
OneView, just stops waiting for its compl... |
359,417 | def getPluginDescriptor(self, dir):
for plugin in glob.glob(os.path.join(dir, )):
return os.path.realpath(plugin)
raise UnrealManagerException() | Detects the .uplugin descriptor file for the Unreal plugin in the specified directory |
359,418 | def _CalculateAttributeStorageTypes(self):
self.attribute_types = {}
for attribute in itervalues(aff4.Attribute.PREDICATES):
self.attribute_types[attribute.predicate] = (
attribute.attribute_type.data_store_type) | Build a mapping between column names and types. |
359,419 | def last(symbols=None, token=, version=):
symbols = _strToList(symbols)
if symbols:
return _getJson( + .join(symbols) + , token, version)
return _getJson(, token, version) | Last provides trade data for executions on IEX. It is a near real time, intraday API that provides IEX last sale price, size and time.
Last is ideal for developers that need a lightweight stock quote.
https://iexcloud.io/docs/api/#last
Args:
symbol (string); Ticker to request
token (string... |
359,420 | def search_registered_query_deleted_for_facet(self, facet, **kwargs):
kwargs[] = True
if kwargs.get():
return self.search_registered_query_deleted_for_facet_with_http_info(facet, **kwargs)
else:
(data) = self.search_registered_query_deleted_for_facet_with_htt... | Lists the values of a specific facet over the customer's deleted derived metric definitions # 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_registered_query_del... |
359,421 | def setup_variables(self):
if self.input_tensor:
if type(self.input_tensor) == int:
x = dim_to_var(self.input_tensor, name="x")
else:
x = self.input_tensor
else:
x = T.matrix()
self.input_variables.append(x)
sel... | Set up variables. |
359,422 | def summary(self, alpha=0.05, start=0, batches=100, chain=None, roundto=3):
statdict = self.stats(
alpha=alpha,
start=start,
batches=batches,
chain=chain)
size = np.size(statdict[])
print_( % self.__name__)
prin... | Generate a pretty-printed summary of the node.
:Parameters:
alpha : float
The alpha level for generating posterior intervals. Defaults to
0.05.
start : int
The starting index from which to summarize (each) chain. Defaults
to zero.
batches : int
... |
359,423 | def dimension_size(x, axis):
s = tf.compat.dimension_value(
tensorshape_util.with_rank_at_least(x.shape, np.abs(axis))[axis])
if s is not None:
return s
return tf.shape(input=x)[axis] | Returns the size of a specific dimension. |
359,424 | def make_variant(cls, converters, re_opts=None, compiled=False, strict=True):
assert converters, "REQUIRE: Non-empty list."
if len(converters) == 1:
return converters[0]
if re_opts is None:
re_opts = cls.default_re_opts
pattern = r")|("... | Creates a type converter for a number of type converter alternatives.
The first matching type converter is used.
REQUIRES: type_converter.pattern attribute
:param converters: List of type converters as alternatives.
:param re_opts: Regular expression options zu use (=default_re_opts).... |
359,425 | def call_each_reversed(funcs: list, *args, **kwargs):
ret = None
for func in reversed(funcs):
ret = func(*args, **kwargs)
return ret | call each func from reversed func list.
return the last func value or None if func list is empty. |
359,426 | def diff_flux_threshold(self, skydir, fn, ts_thresh, min_counts):
sig, bkg, bkg_fit = self.compute_counts(skydir, fn)
norms = irfs.compute_norm(sig, bkg, ts_thresh,
min_counts, sum_axes=[2, 3],
rebin_axes=[10, 1],
... | Compute the differential flux threshold for a point source at
position ``skydir`` with spectral parameterization ``fn``.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
Sky coordinates at which the sensitivity will be evaluated.
fn : `~fermipy.spectru... |
359,427 | def _create_resource(resource, name=None, tags=None, region=None, key=None,
keyid=None, profile=None, **kwargs):
try:
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
create_resource = getattr(conn, + resource)
except Att... | Create a VPC resource. Returns the resource id if created, or False
if not created. |
359,428 | def show_lbaas_member(self, lbaas_member, lbaas_pool, **_params):
return self.get(self.lbaas_member_path % (lbaas_pool, lbaas_member),
params=_params) | Fetches information of a certain lbaas_member. |
359,429 | def py_to_weld_type(self, obj):
if isinstance(obj, np.ndarray):
dtype = str(obj.dtype)
if dtype == :
base = WeldInt16()
elif dtype == :
base = WeldInt()
elif dtype == :
base = WeldLong()
elif dty... | Summary
Args:
obj (TYPE): Description
Returns:
TYPE: Description
Raises:
Exception: Description |
359,430 | def get_context_data(self, **kwargs):
data = super(GaugesView, self).get_context_data(**kwargs)
data.update({: get_r().gauge_slugs()})
return data | Includes the Gauge slugs and data in the context. |
359,431 | def prepare(self, query, custom_payload=None, keyspace=None):
message = PrepareMessage(query=query, keyspace=keyspace)
future = ResponseFuture(self, message, query=None, timeout=self.default_timeout)
try:
future.send_request()
query_id, bind_metadata, pk_indexes,... | Prepares a query string, returning a :class:`~cassandra.query.PreparedStatement`
instance which can be used as follows::
>>> session = cluster.connect("mykeyspace")
>>> query = "INSERT INTO users (id, name, age) VALUES (?, ?, ?)"
>>> prepared = session.prepare(query)
... |
359,432 | def rpc_connect(self):
if self.coin in COINS:
rpc_url = COINS[self.coin]["rpc-url"] + ":"
if self.testnet:
rpc_url += COINS[self.coin]["rpc-port-testnet"]
else:
rpc_url += COINS[self.coin]["rpc-port"]
self.rpc = pyjsonrpc.H... | Connect to a coin daemon's JSON RPC interface.
Returns:
bool: True if successfully connected, False otherwise. |
359,433 | def ctype_class(self):
def vec_factory(elemType):
class Vec(Structure):
_fields_ = [
("ptr", POINTER(elemType.ctype_class)),
("size", c_long),
]
return Vec
if self.elem... | Summary
Returns:
TYPE: Description |
359,434 | async def findArtifactFromTask(self, *args, **kwargs):
return await self._makeApiCall(self.funcinfo["findArtifactFromTask"], *args, **kwargs) | Get Artifact From Indexed Task
Find a task by index path and redirect to the artifact on the most recent
run with the given `name`.
Note that multiple calls to this endpoint may return artifacts from differen tasks
if a new task is inserted into the index between calls. Avoid using thi... |
359,435 | def raise_db_exception(self):
if not self.messages:
raise tds_base.Error("Request failed, server didnmsgno message'] for m in self.messages)
ex = _create_exception_by_message(msg, error_msg)
raise ex | Raises exception from last server message
This function will skip messages: The statement has been terminated |
359,436 | def destroy(self):
return self.get_data(
"domains/%s/records/%s" % (self.domain, self.id),
type=DELETE,
) | Destroy the record |
359,437 | def fragment(self, fragment_size, mask=False):
frames = []
for start in xrange(0, len(self.payload), fragment_size):
payload = self.payload[start:start + fragment_size]
frames.append(Frame(OPCODE_CONTINUATION, payload, mask=mask,
final=Fa... | Fragment the frame into a chain of fragment frames:
- An initial frame with non-zero opcode
- Zero or more frames with opcode = 0 and final = False
- A final frame with opcode = 0 and final = True
The first and last frame may be the same frame, having a non-zero
opcode and final... |
359,438 | def _module_info_from_proto_safe(module_info_def, import_scope=None):
try:
return _module_info_from_proto(module_info_def, import_scope)
except Exception as e:
logging.warning(
"Error encountered when deserializing sonnet ModuleInfo:\n%s", str(e))
return None | Deserializes the `module_info_def` proto without raising exceptions.
Args:
module_info_def: An instance of `module_pb2.SonnetModule`.
import_scope: Optional `string`. Name scope to use.
Returns:
An instance of `ModuleInfo`. |
359,439 | def isSameHVal(a: Value, b: Value) -> bool:
return a is b or (isinstance(a, Value)
and isinstance(b, Value)
and a.val == b.val
and a.vldMask == b.vldMask) | :return: True if two Value instances are same
:note: not just equal |
359,440 | def path(self, which=None):
if which in (,):
return .format(
super(Environment, self).path(which=),
which
)
return super(Environment, self).path(which) | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
smart_class_parameters
/api/environments/:environment_id/smart_class_parameters
Otherwise, call ``super``. |
359,441 | def ec2_credentials_get(user_id=None, name=None, access=None,
profile=None, **connection_args):
***
kstone = auth(profile, **connection_args)
ret = {}
if name:
for user in kstone.users.list():
if user.name == name:
user_id = user.id
... | Return ec2_credentials for a user (keystone ec2-credentials-get)
CLI Examples:
.. code-block:: bash
salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370
salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=72278... |
359,442 | def connect(self, hostname, port=SSH_PORT, username=None, password=None, pkey=None,
key_filename=None, timeout=None, allow_agent=True, look_for_keys=True,
compress=False, sock=None):
if not sock:
for (family, socktype, proto, canonname, sockaddr) in socket.ge... | Connect to an SSH server and authenticate to it. The server's host key
is checked against the system host keys (see `load_system_host_keys`)
and any local host keys (`load_host_keys`). If the server's hostname
is not found in either set of host keys, the missing host key policy
is used... |
359,443 | def write(self, data):
_complain_ifclosed(self.closed)
if self.__encoding:
self.f.write(data.encode(self.__encoding, self.__errors))
return len(data)
else:
return self.f.write(data) | Write ``data`` to the file.
:type data: bytes
:param data: the data to be written to the file
:rtype: int
:return: the number of bytes written |
359,444 | def teardown(self):
for proxy in self._proxies.values():
proxy.restore_original_object()
for patch in self._patches.values():
patch.restore_original_object() | Restores all doubled objects to their original state. |
359,445 | def _call_parallel_target(self, name, cdata, low):
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata[]](*cdata[],
**cdata[])
except Exception as exc:
... | The target function to call that will create the parallel thread/process |
359,446 | def _readXputMaps(self, mapCards, directory, session, spatial=False, spatialReferenceID=4236, replaceParamFile=None):
if self.mapType in self.MAP_TYPES_SUPPORTED:
for card in self.projectCards:
if (card.name in mapCards) and self._noneOrNumValue(card.value):
... | GSSHA Project Read Map Files from File Method |
359,447 | def version_diff(version1, version2):
if version1 is None or version2 is None:
return
if version1 == version2:
return
for v in (, , ):
if getattr(version1, v) != getattr(version2, v):
return v
return | Return string representing the diff between package versions.
We're interested in whether this is a major, minor, patch or 'other'
update. This method will compare the two versions and return None if
they are the same, else it will return a string value indicating the
type of diff - 'major', 'minor', '... |
359,448 | def doTransaction(conn, start=True, startSQL=):
START TRANSACTIONSTART TRANSACTION
try:
if start:
executeSQL(conn, startSQL)
yield conn
except:
if conn is not None:
conn.rollback()
raise
else:
conn.commit() | wrap a connection in a transaction. starts a transaction, yields the conn, and then if an exception occurs, calls rollback(). otherwise calls commit().
start: if True, executes 'START TRANSACTION' sql before yielding conn. Useful for connections that are autocommit by default.
startSQL: override if 'START TR... |
359,449 | def _initializes_minimum_needs_fields():
needs_profile = NeedsProfile()
needs_profile.load()
fields = []
needs_parameters = needs_profile.get_needs_parameters()
for need_parameter in needs_parameters:
if isinstance(need_parameter, ResourceParameter):
format_args = {
... | Initialize minimum needs fields.
Minimum needs definitions are taken from currently used profile. |
359,450 | def verify_type_product(self, satellite):
if satellite == :
id_satellite =
stations = [, , , , , , , , , , , ]
elif satellite == :
id_satellite =
stations = [, , , , ]
elif satellite == :
id_satellite =
stations ... | Gets satellite id |
359,451 | def from_master_secret(cls, seed, network="bitcoin_testnet"):
network = Wallet.get_network(network)
seed = ensure_bytes(seed)
I = hmac.new(b"Bitcoin seed", msg=seed, digestmod=sha512).digest()
I_L, I_R = I[:32], I[32:]
return cls(priva... | Generate a new PrivateKey from a secret key.
:param seed: The key to use to generate this wallet. It may be a long
string. Do not use a phrase from a book or song, as that will
be guessed and is not secure. My advice is to not supply this
argument and let me generate a new r... |
359,452 | def cumulant(self, n, k, error=False):
r
corr_nk = self.correlation(n, k, error=error)
if k == 2:
return corr_nk
elif k == 4:
corr_n2 = self.correlation(n, 2)
return corr_nk - 2*corr_n2*corr_n2 | r"""
Calculate `c_n\{k\}`,
the `k`-particle cumulant for `n`\ th-order anisotropy.
:param int n: Anisotropy order.
:param int k: Correlation order.
:param bool error:
Whether to calculate statistical error (for `c_n\{2\}` only).
If true, return a tuple `... |
359,453 | def get_brokers(self):
return [.format(parsedUrl.hostname, parsedUrl.port) for parsedUrl in
[urlparse(url) for url in self.kafka_url.split()]] | Parses the KAKFA_URL and returns a list of hostname:port pairs in the format
that kafka-python expects. |
359,454 | def get_by_provider_display_name(self, provider_display_name):
san_managers = self._client.get_all()
result = [x for x in san_managers if x[] == provider_display_name]
return result[0] if result else None | Gets a SAN Manager by provider display name.
Args:
provider_display_name: Name of the Provider Display Name
Returns:
dict: SAN Manager. |
359,455 | def extract(self, progress = True, recurse = True, tex_only = False,
extract_manifest = False, path = None, **kwargs):
if path is None:
path = self.folder_out
if tex_only:
kwargs[] = False
utils.mkdir_silent(path)
utime(path, (self.time, self.time))
... | to_extract = (f for f in self.tree.all_files if not(tex_only and not isinstance(f, ImageFile) and not isinstance(f, ImageCanvas)))
p = Pool()
args = zip(to_extract, itertools.cycle((path,)), itertools.cycle((kwargs,)))
to_recurse = []
for f in tqdm(p.imap_unordered(_extract, args)):
... |
359,456 | def multilabel_accuracy_matchk(predictions,
labels,
k,
weights_fn=common_layers.weights_nonzero):
predictions = tf.to_int32(tf.argmax(predictions, axis=-1))
scores = tf.to_float(tf.equal(predictions, labels))
weight... | Used to evaluate the VQA accuracy.
Let n be the times that predictions appear in labels, then final score
is min(n/k, 1).
Refer to https://arxiv.org/pdf/1505.00468.pdf.
Args:
predictions: A tensor with shape [batch_size, 1, 1, 1, vocab_size].
labels: A tensor with shape [batch_size, length, 1, 1].
... |
359,457 | def load_texture(self, file_path):
self.image = pygame.image.load(file_path)
self.apply_texture(self.image) | Generate our sprite's surface by loading the specified image from disk.
Note that this automatically centers the origin. |
359,458 | def src_new(converter_type, channels):
error = ffi.new()
state = _lib.src_new(converter_type, channels, error)
return state, error[0] | Initialise a new sample rate converter.
Parameters
----------
converter_type : int
Converter to be used.
channels : int
Number of channels.
Returns
-------
state
An anonymous pointer to the internal state of the converter.
error : int
Error code. |
359,459 | def set_perspective(self, fov, aspect, near, far):
self.matrix = transforms.perspective(fov, aspect, near, far) | Set the perspective
Parameters
----------
fov : float
Field of view.
aspect : float
Aspect ratio.
near : float
Near location.
far : float
Far location. |
359,460 | def parse_args(kwargs, defaults=None):
try:
import fire
except ImportError:
raise ImportError("Using skorch cli helpers requires the fire library,"
" you can install it with pip: pip install fire.")
try:
import numpydoc.docscrape
except ImportError:... | Apply command line arguments or show help.
Use this in conjunction with the fire library to quickly build
command line interfaces for your scripts.
This function returns another function that must be called with
the estimator (e.g. ``NeuralNet``) to apply the parsed command
line arguments. If the ... |
359,461 | def __marshal_matches(matched):
json_matches = []
for m in matched:
identities = [i.uuid for i in m]
if len(identities) == 1:
continue
json_match = {
: identities,
: False
}
json_matche... | Convert matches to JSON format.
:param matched: a list of matched identities
:returns json_matches: a list of matches in JSON format |
359,462 | def add_resource_url(self, url, mimetype, placement=None):
if not placement:
placement = self._default_placement(mimetype)
self._resources.append(FragmentResource(, url, mimetype, placement)) | Add a resource by URL needed by this Fragment.
Other helpers, such as :func:`add_css_url` or
:func:`add_javascript_url` are more convenent for those common types of
resource.
`url`: the URL to the resource.
Other parameters are as defined for :func:`add_resource`. |
359,463 | def _get_credentials(username=None, password=None, dbhost=None):
system_config = dbhost.objectmodels[].find_one({
: True
})
try:
salt = system_config.salt.encode()
except (KeyError, AttributeError):
log(
)
sys.exit(3)
if username ... | Obtain user credentials by arguments or asking the user |
359,464 | def publish(self, **kwargs):
if self._dxid is not None:
return dxpy.api.global_workflow_publish(self._dxid, **kwargs)
else:
return dxpy.api.global_workflow_publish( + self._name, alias=self._alias, **kwargs) | Publishes the global workflow, so all users can find it and use it on the platform.
The current user must be a developer of the workflow. |
359,465 | def getPartitionId(self, i):
if (i < 0) or (i >= self._numPatterns):
raise RuntimeError("index out of bounds")
partitionId = self._partitionIdList[i]
if partitionId == numpy.inf:
return None
else:
return partitionId | Gets the partition id given an index.
:param i: index of partition
:returns: the partition id associated with pattern i. Returns None if no id
is associated with it. |
359,466 | def _convert_to_style(cls, style_dict, num_format_str=None):
import xlwt
if style_dict:
xlwt_stylestr = cls._style_to_xlwt(style_dict)
style = xlwt.easyxf(xlwt_stylestr, field_sep=, line_sep=)
else:
style = xlwt.XFStyle()
if num_format_str is... | converts a style_dict to an xlwt style object
Parameters
----------
style_dict : style dictionary to convert
num_format_str : optional number format string |
359,467 | def _find_matching_instance(cache_key):
infos = get_all()
candidates = [info for info in infos if info.cache_key == cache_key]
for candidate in sorted(candidates, key=lambda x: x.port):
return candidate
return None | Find a running TensorBoard instance compatible with the cache key.
Returns:
A `TensorBoardInfo` object, or `None` if none matches the cache key. |
359,468 | def get_attrtext(value):
m = _non_attribute_end_matcher(value)
if not m:
raise errors.HeaderParseError(
"expected attrtext but found {!r}".format(value))
attrtext = m.group()
value = value[len(attrtext):]
attrtext = ValueTerminal(attrtext, )
_validate_xtext(attrtext)
... | attrtext = 1*(any non-ATTRIBUTE_ENDS character)
We allow any non-ATTRIBUTE_ENDS in attrtext, but add defects to the
token's defects list if we find non-attrtext characters. We also register
defects for *any* non-printables even though the RFC doesn't exclude all of
them, because we follow the spirit o... |
359,469 | def processSquarePayment(request):
logger.info()
nonce_id = request.POST.get()
invoice_id = request.POST.get()
tr_id = request.POST.get()
amount = request.POST.get()
submissionUserId = request.POST.get()
transactionType = request.POST.get()
taxable = request.POST.get(, False)
s... | This view handles the charging of approved Square Checkout payments.
All Checkout payments must either be associated with a pre-existing Invoice
or a registration, or they must have an amount and type passed in the post data
(such as gift certificate payment requests). |
359,470 | def _set_cached_value(self, xblock, value):
if not hasattr(xblock, ):
xblock._field_data_cache = {}
xblock._field_data_cache[self.name] = value | Store a value in the xblock's cache, creating the cache if necessary. |
359,471 | def get_data(self, datasource, callback):
task = self.__app.worker.current_task
media_metadata = datasource.connector_type_preset[][]
result_data = task[]
tmp_file = NamedTemporaryFile(delete=False, suffix=SOURCE_FORMAT_EXTENSION.get(media_metadata[]))
self.__app.log.inf... | Сохранение медиафайла
:param task:
:param media_metadata:
:param file_suffix:
:param callback:
:return: |
359,472 | def get_area_slices(data_area, area_to_cover):
if data_area.proj_dict[] != :
raise NotImplementedError()
if area_to_cover.proj_dict[] == data_area.proj_dict[]:
LOGGER.debug(
.format(area_to_cover.proj_dict[]))
llx, lly, urx, ury = area_to_cover.a... | Compute the slice to read from an *area* based on an *area_to_cover*. |
359,473 | def add_pooling_with_padding_types(builder, name, height, width, stride_height, stride_width,
layer_type, padding_type, input_name, output_name,
padding_top = 0, padding_bottom = 0, padding_left = 0, padding_right = 0,
same_padding_asymmetry_mode = ,
exclude_pad_area = True, is_globa... | Add a pooling layer to the model.
This is our own implementation of add_pooling since current CoreML's version (0.5.0) of builder
doesn't provide support for padding types apart from valid. This support will be added in the
next release of coremltools. When that happens, this can be removed.
Par... |
359,474 | def DiffArrayObjects(self, oldObj, newObj, isElementLinks=False):
if oldObj == newObj:
return True
if not oldObj or not newObj:
return False
if len(oldObj) != len(newObj):
__Log__.debug(
% (len(oldObj), len(newObj)))
return False
firstObj = ... | Method which deligates the diffing of arrays based on the type |
359,475 | def sandbox_status(self, vm_name=None):
vagrant_sandbox_output = self._run_sandbox_command([, vm_name])
return self._parse_vagrant_sandbox_status(vagrant_sandbox_output) | Returns the status of the sandbox mode.
Possible values are:
- on
- off
- unknown
- not installed |
359,476 | def get_actor(self, aid, check_monitor=True):
aid = actor_identity(aid)
return self._concurrency.get_actor(self, aid,
check_monitor=check_monitor) | Given an actor unique id return the actor proxy. |
359,477 | def _copy_static_assets(self, output_dir):
base_directory = .format(self._report_name)
for asset in resource_listdir(self._package_name, base_directory):
filename = resource_filename(
self._package_name, .format(base_directory, asset))
shutil.copy2(filena... | Copy assets for the report to `output_dir`.
:param output_dir: directory to output assets to
:type output_dir: `str` |
359,478 | def parse_response(cls, response, **kwargs):
if response.tag != cls.command_name:
raise ResponseParseError(
"Received response of type {}, PutCommand can only parse responses of type {}".format(response.tag,
... | Parse the server response for this put file command
This will parse xml of the following form::
<put_file />
or with an error::
<put_file>
<error ... />
</put_file>
:param response: The XML root of the response for a put file command
... |
359,479 | def make_redirect_url(self, path_info, query_args=None, domain_part=None):
suffix = ""
if query_args:
suffix = "?" + self.encode_query_args(query_args)
return str(
"%s://%s/%s%s"
% (
self.url_scheme or "http",
self.get_... | Creates a redirect URL.
:internal: |
359,480 | def delete_service_settings_on_service_delete(sender, instance, **kwargs):
service = instance
try:
service_settings = service.settings
except ServiceSettings.DoesNotExist:
return
if not service_settings.shared:
service.settings.delete() | Delete not shared service settings without services |
359,481 | def run(align_bams, items, ref_file, assoc_files, region=None, out_file=None):
paired = vcfutils.get_paired_bams(align_bams, items)
assert paired and not paired.normal_bam, ("Pisces supports tumor-only variant calling: %s" %
(",".join([dd.get_sample_name(d) for... | Run tumor only pisces calling
Handles bgzipping output file and fixing VCF sample naming to match BAM sample. |
359,482 | def indicators_from_tag(self, indicator, tag_name, filters=None, params=None):
params = params or {}
for t in self.pivot_from_tag(indicator, tag_name, filters=filters, params=params):
yield t | Args:
indicator:
tag_name:
filters:
params:
Return: |
359,483 | def read(self, entity=None, attrs=None, ignore=None, params=None):
if attrs is None:
attrs = self.read_json()
attrs[] = attrs.pop()
attrs[] = attrs.pop()
attrs[] = attrs.pop()
if ignore is None:
ignore = set()
ignore.update([, , ])
... | Fetch as many attributes as possible for this entity.
Do not read the ``facts``, ``organization`` or ``type`` attributes.
For more information, see `Bugzilla #1202917
<https://bugzilla.redhat.com/show_bug.cgi?id=1202917>`_. |
359,484 | def event_text(self, event):
logger.debug("error text for %s" % hex(event.EvtCode))
len_ = 1024
text_type = ctypes.c_char * len_
text = text_type()
error = self.library.Srv_EventText(ctypes.byref(event),
ctypes.byref(text), len_... | Returns a textual explanation of a given event object
:param event: an PSrvEvent struct object
:returns: the error string |
359,485 | def join(self, network):
args = {: network}
self._network_chk.check(args)
response = self._client.raw(, args)
result = response.get()
if result.state != :
raise RuntimeError(, result.stderr) | Join a zerotier network
:param network: network id to join
:return: |
359,486 | def phase_identification_parameter(V, dP_dT, dP_dV, d2P_dV2, d2P_dVdT):
r
return V*(d2P_dVdT/dP_dT - d2P_dV2/dP_dV) | r'''Calculate the Phase Identification Parameter developed in [1]_ for
the accurate and efficient determination of whether a fluid is a liquid or
a gas based on the results of an equation of state. For supercritical
conditions, this provides a good method for choosing which property
correlations to us... |
359,487 | def replace(self, key, initial_value, new_value):
base64_key = _encode(key)
base64_initial_value = _encode(initial_value)
base64_new_value = _encode(new_value)
txn = {
: [{
: base64_key,
: ,
: ,
: base64... | Atomically replace the value of a key with a new value.
This compares the current value of a key, then replaces it with a new
value if it is equal to a specified value. This operation takes place
in a transaction.
:param key: key in etcd to replace
:param initial_value: old val... |
359,488 | def make_features(context, frmat=, str_maximal=False):
config = Config.create(context=context, format=frmat, str_maximal=str_maximal)
return FeatureSystem(config) | Return a new feature system from context string in the given format.
Args:
context (str): Formal context table as plain-text string.
frmat: Format of the context string (``'table'``, ``'cxt'``, ``'csv'``).
str_maximal (bool):
Example:
>>> make_features('''
... |+ma... |
359,489 | def lifecycle_lock(self):
safe_mkdir(self._metadata_base_dir)
return OwnerPrintingInterProcessFileLock(
) | An identity-keyed inter-process lock for safeguarding lifecycle and other operations. |
359,490 | def _get_hold(line, pattern=__HOLD_PATTERN, full=True):
if full:
if _yum() == :
lock_re = r.format(pattern)
else:
lock_re = r.format(pattern)
else:
if _yum() == :
lock_re = r.format(pattern)
else:
lock_re = r.format(pattern)
... | Resolve a package name from a line containing the hold expression. If the
regex is not matched, None is returned.
yum ==> 2:vim-enhanced-7.4.629-5.el6.*
dnf ==> vim-enhanced-2:7.4.827-1.fc22.* |
359,491 | def post(self):
if not request.is_json:
return self.response_400(message="Request is not JSON")
try:
item = self.add_model_schema.load(request.json)
except ValidationError as err:
return self.response_422(message=err.messages)
if isin... | POST item to Model
---
post:
requestBody:
description: Model schema
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/{{self.__class__.__name__}}.post'
responses:
... |
359,492 | def receive_request(self, transaction):
transaction.cached_element = self.cache.search_response(transaction.request)
if transaction.cached_element is None:
transaction.cacheHit = False
else:
transaction.response = transaction.cached_element.cached_response
... | checks the cache for a response to the request
:param transaction:
:return: |
359,493 | def aggregate_raw_batches(self, pipeline, **kwargs):
cursor_class = create_class_with_framework(
AgnosticLatentCommandCursor, self._framework, self.__module__)
return cursor_class(self, self._async_aggregate_raw_batches, pipeline,
**unwrap_kwarg... | Perform an aggregation and retrieve batches of raw BSON.
Similar to the :meth:`aggregate` method but returns each batch as bytes.
This example demonstrates how to work with raw batches, but in practice
raw batches should be passed to an external library that can decode
BSON into anothe... |
359,494 | def step(self, observation, **extra_feed):
a, v, state, neglogp = self._evaluate([self.action, self.vf, self.state, self.neglogp], observation, **extra_feed)
if state.size == 0:
state = None
return a, v, state, neglogp | Compute next action(s) given the observation(s)
Parameters:
----------
observation observation data (either single or a batch)
**extra_feed additional data such as state or mask (names of the arguments should match the ones in constructor, see __init__)
Returns:
... |
359,495 | def update(self, **kwargs):
if in kwargs and kwargs[] == :
if not in kwargs:
error =
raise MissingUpdateParameter(error)
if hasattr(self, ):
if getattr(self, ) == and not in self.__dict__:
error =
rais... | When setting useProxyServer to enable we need to supply
proxyServerPool value as well |
359,496 | def request(self, method, path, contents, headers, decode_json=False,
stream=False, query=None, cdn=False):
if query:
path += + .join(
( % (quote(k), quote(v)) if v else quote(k))
for k, v in sorted(six.iteritems(query)))
reset_func =... | See :py:func:`swiftly.client.client.Client.request` |
359,497 | def unique_string(length=UUID_LENGTH):
string = str(uuid4()) * int(math.ceil(length / float(UUID_LENGTH)))
return string[:length] if length else string | Generate a unique string |
359,498 | def add_entity_errors(
self,
property_name,
direct_errors=None,
schema_errors=None
):
if direct_errors is None and schema_errors is None:
return self
if direct_errors is not None:
if property_name not in self.errors:
... | Attach nested entity errors
Accepts a list errors coming from validators attached directly,
or a dict of errors produced by a nested schema.
:param property_name: str, property name
:param direct_errors: list, errors from validators attached directly
:param schema_errors: dict, ... |
359,499 | def parameters(self):
if self._coord_type == :
return collections.OrderedDict(((, self.l), (, self.b)))
else:
return collections.OrderedDict(((, self.ra), (, self.dec))) | Get the dictionary of parameters (either ra,dec or l,b)
:return: dictionary of parameters |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.