Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
10,300 | def cancel_inquiry (self):
self.names_to_find = {}
if self.is_inquiring:
try:
_bt.hci_send_cmd (self.sock, _bt.OGF_LINK_CTL, \
_bt.OCF_INQUIRY_CANCEL)
except _bt.error as e:
self.sock.close ()
self.... | Call this method to cancel an inquiry in process. inquiry_complete
will still be called. |
10,301 | def all_my_hosts_and_services(self):
for what in (self.hosts, self.services):
for item in what:
yield item | Create an iterator for all my known hosts and services
:return: None |
10,302 | def _get_objects_with_same_attribute(self,
objects: Set[Object],
attribute_function: Callable[[Object], str]) -> Set[Object]:
objects_of_attribute: Dict[str, Set[Object]] = defaultdict(set)
for entity in objects:
... | Returns the set of objects for which the attribute function returns an attribute value that
is most frequent in the initial set, if the frequency is greater than 1. If not, all
objects have different attribute values, and this method returns an empty set. |
10,303 | async def parse_update(self, bot):
data = await self.request.json()
update = types.Update(**data)
return update | Read update from stream and deserialize it.
:param bot: bot instance. You an get it from Dispatcher
:return: :class:`aiogram.types.Update` |
10,304 | def _apply_to_array(self, yd, y, weights, off_slices, ref_slice, dim):
ndims = len(y.shape)
all = slice(None, None, 1)
ref_multi_slice = [all] * ndims
ref_multi_slice[dim] = ref_slice
for w, s in zip(weights, off_slices):
off_multi_slice = [all] * ndims
... | Applies the finite differences only to slices along a given axis |
10,305 | def _get_dvs_capability(dvs_name, dvs_capability):
log.trace(%s\, dvs_name)
return {: dvs_capability.dvsOperationSupported,
:
dvs_capability.dvPortGroupOperationSupported,
: dvs_capability.dvPortOperationSupported} | Returns the dict representation of the DVS product_info
dvs_name
The name of the DVS
dvs_capability
The DVS capability |
10,306 | def _create_identifier(rdtype, name, content):
sha256 = hashlib.sha256()
sha256.update((rdtype + ).encode())
sha256.update((name + ).encode())
sha256.update(content.encode())
return sha256.hexdigest()[0:7] | Creates hashed identifier based on full qualified record type, name & content
and returns hash. |
10,307 | def dependencies(self, task, params={}, **options):
path = "/tasks/%s/dependencies" % (task)
return self.client.get(path, params, **options) | Returns the compact representations of all of the dependencies of a task.
Parameters
----------
task : {Id} The task to get dependencies on.
[params] : {Object} Parameters for the request |
10,308 | def get_rupdict(self):
assert len(self.rup_array) == 1,
dic = {: self.trt, : self.samples}
with datastore.read(self.filename) as dstore:
rupgeoms = dstore[]
source_ids = dstore[][]
rec = self.rup_array[0]
geom = rupgeoms[rec[]:rec[]].resh... | :returns: a dictionary with the parameters of the rupture |
10,309 | def _set_vcs(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u: {: 1}, u: {: 2}},), is_leaf=Tr... | Setter method for vcs, mapped from YANG variable /event_handler/event_handler_list/trigger/vcs (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_vcs is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj... |
10,310 | def _learnFeatureLocationPair(self, newLocation, featureLocationInput,
featureLocationGrowthCandidates):
potentialOverlaps = self.featureLocationConnections.computeActivity(
featureLocationInput)
matchingSegments = np.where(potentialOverlaps > self.learningThreshold)[... | Grow / reinforce synapses between the location layer's dendrites and the
input layer's active cells. |
10,311 | def _check_for_pi_nodes(self, list, inheader):
list = list[:]
while list:
elt = list.pop()
t = elt.nodeType
if t == _Node.PROCESSING_INSTRUCTION_NODE:
raise ParseException( + \
elt.nodeName + ,
i... | Raise an exception if any of the list descendants are PI nodes. |
10,312 | def _validate_query(query):
query = deepcopy(query)
if query["q"] == BLANK_QUERY["q"]:
raise ValueError("No query specified.")
query["q"] = _clean_query_string(query["q"])
if query["limit"] is None:
query["limit"] = SEARCH_LIMIT if query["advanced"] else NONADVANCED_LIMI... | Validate and clean up a query to be sent to Search.
Cleans the query string, removes unneeded parameters, and validates for correctness.
Does not modify the original argument.
Raises an Exception on invalid input.
Arguments:
query (dict): The query to validate.
Returns:
dict: The v... |
10,313 | def convert_entrez_to_uniprot(self, entrez):
server = "http://www.uniprot.org/uniprot/?query=%22GENEID+{0}%22&format=xml".format(entrez)
r = requests.get(server, headers={"Content-Type": "text/xml"})
if not r.ok:
r.raise_for_status()
sys.exit()
response =... | Convert Entrez Id to Uniprot Id |
10,314 | def getPDF(self):
if hasattr(self, ):
return self._qplot, self._hplot, self._tplot
else:
raise ValueError() | Function that gets vectors of the pdf and target at the last design
evaluated.
:return: tuple of q values, pdf values, target values |
10,315 | def read_config(cls, configparser):
config = dict()
section = cls.__name__
option = "warningregex"
if configparser.has_option(section, option):
value = configparser.get(section, option)
else:
value = None
config[option] = value
ret... | Read configuration file options. |
10,316 | def job_step_error(self, job_request_payload, message):
payload = JobStepErrorPayload(job_request_payload, message)
self.send(job_request_payload.error_command, payload) | Send message that the job step failed using payload data.
:param job_request_payload: StageJobPayload|RunJobPayload|StoreJobOutputPayload payload from job with error
:param message: description of the error |
10,317 | def new_socket():
new_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
new_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
reuseport = socket.SO_REUSEPORT
except AttributeError:
pass
else:
try:
new_sock.setsockopt(socket.SOL_... | Create a new socket with OS-specific parameters
Try to set SO_REUSEPORT for BSD-flavored systems if it's an option.
Catches errors if not. |
10,318 | def validate_replicas(self, data):
environment = data.get()
if environment and environment.replicas:
validate_replicas(data.get(), environment.replicas) | Validate distributed experiment |
10,319 | def _call(self, endpoint, data=None):
data = {} if data is None else data
try:
data[] = self.access_token()
return self._request(endpoint, data)
except AccessTokenExpired:
self._cached_access_token = None
data[] = self.access_token()
... | Make an authorized API call to specified endpoint.
:param str endpoint: API endpoint's relative URL, eg. `/account`.
:param dict data: POST request data.
:return: A dictionary or a string with response data. |
10,320 | def run(self):
print()
_build.run(self)
print()
docdir = os.path.join(self.build_lib, , )
self.mkpath(docdir)
doc_builder = os.path.join(self.build_lib, , )
doc_source =
check_call([sys.executable, doc_builder, doc_source, self.build_li... | Build the Fortran library, all python extensions and the docs. |
10,321 | def _read_data(path):
data = {}
with open(path, "r") as f_obj:
var = ""
for line in f_obj:
if "<-" in line:
if len(var):
key, var = _process_data_var(var)
data[key] = var
var = ""
var += " " + li... | Read Rdump output and transform to Python dictionary.
Parameters
----------
path : str
Returns
-------
Dict
key, values pairs from Rdump formatted data. |
10,322 | def is_handler_subclass(cls, classnames=("ViewHandler", "APIHandler")):
if isinstance(cls, list):
return any(is_handler_subclass(c) for c in cls)
elif isinstance(cls, type):
return any(c.__name__ in classnames for c in inspect.getmro(cls))
else:
raise TypeError(
"Une... | Determines if ``cls`` is indeed a subclass of ``classnames`` |
10,323 | def analyze_cluster_size_per_scan_parameter(input_file_hits, output_file_cluster_size, parameter=, max_chunk_size=10000000, overwrite_output_files=False, output_pdf=None):
logging.info( + parameter + + input_file_hits)
if os.path.isfile(output_file_cluster_size) and not overwrite_output_files:
l... | This method takes multiple hit files and determines the cluster size for different scan parameter values of
Parameters
----------
input_files_hits: string
output_file_cluster_size: string
The data file with the results
parameter: string
The name of the parameter to separate the dat... |
10,324 | def trace_line_numbers(filename, reload_on_change=False):
fullname = cache_file(filename, reload_on_change)
if not fullname: return None
e = file_cache[filename]
if not e.line_numbers:
if hasattr(coverage.coverage, ):
e.line_numbers = coverage.the_coverage.analyze_morf(fullname)... | Return an Array of breakpoints in filename.
The list will contain an entry for each distinct line event call
so it is possible (and possibly useful) for a line number appear more
than once. |
10,325 | def combine_hex(data):
output = 0x00
for i, value in enumerate(reversed(data)):
output |= (value << i * 8)
return output | Combine list of integer values to one big integer |
10,326 | def dist_to_deg(self, distance, latitude):
lat = latitude if latitude >= 0 else -1 * latitude
rad2deg = 180 / pi
earthRadius = 6378160.0
latitudeCorrection = 0.5 * (1 + cos(lat * pi / 180))
return (distance / (earthRadius * latitudeCorrection) * rad2deg... | distance = distance in meters
latitude = latitude in degrees
at the equator, the distance of one degree is equal in latitude and longitude.
at higher latitudes, a degree longitude is shorter in length, proportional to cos(latitude)
http://en.wikipedia.org/wiki/Decimal_degrees
T... |
10,327 | def avg_receive_rate(self):
if not self._has_data or not in self.result[]:
return None
bps = self.result[][][]
return bps / 8 / 1024 / 1024 | Average receiving rate in MB/s over the entire run. This data may
not exist if iperf was interrupted.
If the result is not from a success run, this property is None. |
10,328 | def _prepare_for_submission(self,tempfolder, inputdict):
try:
code = inputdict.pop(self.get_linkname())
except KeyError:
raise InputValidationError("No code specified for this "
"calculation")
try:
param... | This is the routine to be called when you want to create
the input files and related stuff with a plugin.
:param tempfolder: a aiida.common.folders.Folder subclass where
the plugin should put all its files.
:param inputdict: a dictionary with the input nodes, ... |
10,329 | def load_average(self):
with io.open(self.load_average_file, ) as f:
file_columns = f.readline().strip().split()
return float(file_columns[self._load_average_file_column]) | Returns the current load average. |
10,330 | def _create_package_hierarchy(prefix=settings.TEMP_DIR, book_id=None):
root_dir = _get_package_name(book_id=book_id, prefix=prefix)
if os.path.exists(root_dir):
shutil.rmtree(root_dir)
os.mkdir(root_dir)
original_dir = os.path.join(root_dir, "original")
metadata_dir = os.path.join(ro... | Create hierarchy of directories, at it is required in specification.
`root_dir` is root of the package generated using :attr:`settings.TEMP_DIR`
and :func:`_get_package_name`.
`orig_dir` is path to the directory, where the data files are stored.
`metadata_dir` is path to the directory with MODS metad... |
10,331 | def all(self, query=None, **kwargs):
return super(OrganizationsProxy, self).all(query=query) | Gets all organizations. |
10,332 | def SetPercentageView(self, percentageView):
self.percentageView = percentageView
self.percentageMenuItem.Check(self.percentageView)
self.percentageViewTool.SetValue(self.percentageView)
total = self.adapter.value( self.loader.get_root( self.viewType ) )
for control in s... | Set whether to display percentage or absolute values |
10,333 | def get(self,
variable_path: str,
default: t.Optional[t.Any] = None,
coerce_type: t.Optional[t.Type] = None,
coercer: t.Optional[t.Callable] = None,
required: bool = False,
**kwargs):
for p in self.parsers:
try:
... | Tries to read a ``variable_path`` from each of the passed parsers.
It stops if read was successful and returns a retrieved value.
If none of the parsers contain a value for the specified path it returns ``default``.
:param variable_path: a path to variable in config
:param default: a de... |
10,334 | def pre_build(local_root, versions):
log = logging.getLogger(__name__)
exported_root = TempDir(True).name
for sha in {r[] for r in versions.remotes}:
target = os.path.join(exported_root, sha)
log.debug(, sha)
export(local_root, sha, target)
remote = versions[Conf... | Build docs for all versions to determine root directory and master_doc names.
Need to build docs to (a) avoid filename collision with files from root_ref and branch/tag names and (b) determine
master_doc config values for all versions (in case master_doc changes from e.g. contents.rst to index.rst between
... |
10,335 | def validate_json_schema(data, schema, name="task"):
try:
jsonschema.validate(data, schema)
except jsonschema.exceptions.ValidationError as exc:
raise ScriptWorkerTaskException(
"Canmalformed-payload']
) | Given data and a jsonschema, let's validate it.
This happens for tasks and chain of trust artifacts.
Args:
data (dict): the json to validate.
schema (dict): the jsonschema to validate against.
name (str, optional): the name of the json, for exception messages.
Defaults to "... |
10,336 | def compress_flood_fill_regions(targets):
t = RegionCoreTree()
for (x, y), cores in iteritems(targets):
for p in cores:
t.add_core(x, y, p)
return sorted(t.get_regions_and_coremasks()) | Generate a reduced set of flood fill parameters.
Parameters
----------
targets : {(x, y) : set([c, ...]), ...}
For each used chip a set of core numbers onto which an application
should be loaded. E.g., the output of
:py:func:`~rig.place_and_route.util.build_application_map` when in... |
10,337 | def getTypeStr(_type):
r
if isinstance(_type, CustomType):
return str(_type)
if hasattr(_type, ):
return _type.__name__
return | r"""Gets the string representation of the given type. |
10,338 | def set_state_view(self, request):
if not request.user.has_perm():
return HttpResponseForbidden()
try:
state = int(request.POST.get("state", ""))
except ValueError:
return HttpResponseBadRequest()
try:
experiment = Experiment.obj... | Changes the experiment state |
10,339 | def make_dataset(self, dataset, raise_if_exists=False, body=None):
if body is None:
body = {}
try:
body[] = {
: dataset.project_id,
: dataset.dataset_id
}
if dataset.location is not None:... | Creates a new dataset with the default permissions.
:param dataset:
:type dataset: BQDataset
:param raise_if_exists: whether to raise an exception if the dataset already exists.
:raises luigi.target.FileAlreadyExists: if raise_if_exists=True and the dataset exists |
10,340 | def setup_statemachine(self):
machine = QtCore.QStateMachine()
group = util.QState("group", QtCore.QState.ParallelStates, machine)
visibility = util.QState("visibility", group)... | Setup and start state machine |
10,341 | def reduce_claims(query_claims):
claims = collections.defaultdict(list)
for claim, entities in query_claims.items():
for ent in entities:
try:
snak = ent.get()
snaktype = snak.get()
value = snak.get().get()
except AttributeE... | returns claims as reduced dict {P: [Q's or values]}
P = property
Q = item |
10,342 | def parse_bool(value):
boolean = parse_str(value).capitalize()
if boolean in ("True", "Yes", "On", "1"):
return True
elif boolean in ("False", "No", "Off", "0"):
return False
else:
raise ValueError(.format(value)) | Parse string to bool.
:param str value: String value to parse as bool
:return bool: |
10,343 | def render(self, message=None, css_class=, form_contents=None,
status=200, title="Python OpenID Consumer Example",
sreg_data=None, pape_data=None):
self.send_response(status)
self.pageHeader(title)
if message:
self.wfile.write("<div class=>" % (... | Render a page. |
10,344 | def covertype():
import sklearn.datasets
data = sklearn.datasets.covtype.fetch_covtype()
features = data.data
labels = data.target
features -= features.mean(0)
features /= features.std(0)
features = np.hstack([features, np.ones([features.shape[0], 1])])
features = tf.cast(features, dtype=tf.flo... | Builds the Covertype data set. |
10,345 | def t_fold_end(self, t):
r
column = find_column(t)
indent = self.indent_stack[-1]
if column < indent:
rollback_lexpos(t)
if column <= indent:
t.lexer.pop_state()
t.type =
if column > indent:
t.type =
return t | r'\n+\ * |
10,346 | def targets(tgt, tgt_type=, **kwargs):
roster_dir = __opts__.get(, )
raw = dict.fromkeys(os.listdir(roster_dir), )
log.debug(, len(raw), roster_dir)
matched_raw = __utils__[](raw, tgt, tgt_type, )
rendered = {minion_id: _render(os.path.join(roster_dir, minion_id), **kwargs)
... | Return the targets from the directory of flat yaml files,
checks opts for location. |
10,347 | def decode_body(headers: MutableMapping, body: bytes) -> dict:
type_, encoding = parse_content_type(headers)
decoded_body = body.decode(encoding)
if type_ == "application/json":
payload = json.loads(decoded_body)
else:
if decoded_body == "ok":
payload = {"ok": Tru... | Decode the response body
For 'application/json' content-type load the body as a dictionary
Args:
headers: Response headers
body: Response body
Returns:
decoded body |
10,348 | def getNextRecord(self, useCache=True):
assert self._file is not None
assert self._mode == self._FILE_READ_MODE
try:
line = self._reader.next()
except StopIteration:
if self.rewindAtEOF:
if self._recordCount == 0:
raise Exception("The source configured to reset ... | Returns next available data record from the file.
:returns: a data row (a list or tuple) if available; None, if no more
records in the table (End of Stream - EOS); empty sequence (list
or tuple) when timing out while waiting for the next record. |
10,349 | def download_file(pk):
release_file = models.ReleaseFile.objects.get(pk=pk)
logging.info("Downloading %s", release_file.url)
proxies = None
if settings.LOCALSHOP_HTTP_PROXY:
proxies = settings.LOCALSHOP_HTTP_PROXY
response = requests.get(release_file.url, stream=True, proxies=proxies)
... | Download the file reference in `models.ReleaseFile` with the given pk. |
10,350 | def get_file_search(self, query):
api_name =
(all_responses, query) = self._bulk_cache_lookup(api_name, query)
response_chunks = self._request_reports("query", query, )
self._extract_response_chunks(all_responses, response_chunks, api_name)
return all_responses | Performs advanced search on samples, matching certain binary/
metadata/detection criteria.
Possible queries: file size, file type, first or last submission to
VT, number of positives, bynary content, etc.
Args:
query: dictionary with search arguments
Ex... |
10,351 | def geo(self):
out = dict(zip([, , , , , ],
self.raster.GetGeoTransform()))
out[] = out[] + out[] * self.cols
out[] = out[] + out[] * self.rows
return out | General image geo information.
Returns
-------
dict
a dictionary with keys `xmin`, `xmax`, `xres`, `rotation_x`, `ymin`, `ymax`, `yres`, `rotation_y` |
10,352 | def set_mapper_index(self, index, mapper):
parent = index.parent()
mapper.setRootIndex(parent)
mapper.setCurrentModelIndex(index) | Set the mapper to the given index
:param index: the index to set
:type index: QtCore.QModelIndex
:param mapper: the mapper to set
:type mapper: QtGui.QDataWidgetMapper
:returns: None
:rtype: None
:raises: None |
10,353 | def read_config(config):
for line in config.splitlines():
line = line.lstrip()
if line and not line.startswith("
return line
return "" | Read config file and return uncomment line |
10,354 | def rename(self, path, raise_if_exists=False):
if isinstance(path, HdfsTarget):
path = path.path
if raise_if_exists and self.fs.exists(path):
raise RuntimeError( % path)
self.fs.rename(self.path, path) | Does not change self.path.
Unlike ``move_dir()``, ``rename()`` might cause nested directories.
See spotify/luigi#522 |
10,355 | def html_abstract(self):
return self.format_abstract(format=, deparagraph=False,
mathjax=False, smart=True) | HTML5-formatted document abstract (`str`). |
10,356 | def get_version():
proc = tmux_cmd()
if proc.stderr:
if proc.stderr[0] == :
if sys.platform.startswith("openbsd"):
return LooseVersion( % TMUX_MAX_VERSION)
raise exc.LibTmuxException(
% TMUX_MIN_VERSION
)
... | Return tmux version.
If tmux is built from git master, the version returned will be the latest
version appended with -master, e.g. ``2.4-master``.
If using OpenBSD's base system tmux, the version will have ``-openbsd``
appended to the latest version, e.g. ``2.4-openbsd``.
Returns
-------
... |
10,357 | def emitError(self, level):
if level in [ABORT,
ERROR,
WARNING,
VERBOSE,
VERBOSE1,
VERBOSE2,
VERBOSE3,
DEBUG]:
return True
return False | determine if a level should print to
stderr, includes all levels but INFO and QUIET |
10,358 | def intersect(self, range_):
self.solver.intersection_broad_tests_count += 1
if range_.is_any():
return self
if self.solver.optimised:
if range_ in self.been_intersected_with:
return self
if self.pr:
self.pr.passive("interse... | Remove variants whose version fall outside of the given range. |
10,359 | def handle_annotations_url(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
keyword = tokens[]
self.raise_for_redefined_annotation(line, position, keyword)
url = tokens[]
self.annotation_url_dict[keyword] = url
if self.skip_validation:
... | Handle statements like ``DEFINE ANNOTATION X AS URL "Y"``.
:raises: RedefinedAnnotationError |
10,360 | def Suratman(L, rho, mu, sigma):
r
return rho*sigma*L/(mu*mu) | r'''Calculates Suratman number, `Su`, for a fluid with the given
characteristic length, density, viscosity, and surface tension.
.. math::
\text{Su} = \frac{\rho\sigma L}{\mu^2}
Parameters
----------
L : float
Characteristic length [m]
rho : float
Density of fluid, [kg/... |
10,361 | def get_all_metadata(
self,
bucket: str,
key: str
) -> dict:
try:
return self.s3_client.head_object(
Bucket=bucket,
Key=key
)
except botocore.exceptions.ClientError as ex:
if str(ex.respo... | Retrieves all the metadata for a given object in a given bucket.
:param bucket: the bucket the object resides in.
:param key: the key of the object for which metadata is being retrieved.
:return: the metadata |
10,362 | def _get_future_tasks(self):
self.alerts = {}
now = std_now()
for task in objectmodels[].find({: {: now}}):
self.alerts[task.alert_time] = task
self.log(, len(self.alerts), ) | Assemble a list of future alerts |
10,363 | def has_next_assessment_part(self, assessment_part_id):
if not self.supports_child_ordering or not self.supports_simple_child_sequencing:
raise AttributeError()
if in self._my_map and str(assessment_part_id) in self._my_map[]:
if self._my_map[][-1] != str(assessment_p... | This supports the basic simple sequence case. Can be overriden in a record for other cases |
10,364 | def output_filename(output_dir, key_handle, public_id):
parts = [output_dir, key_handle] + pyhsm.util.group(public_id, 2)
path = os.path.join(*parts)
if not os.path.isdir(path):
os.makedirs(path)
return os.path.join(path, public_id) | Return an output filename for a generated AEAD. Creates a hashed directory structure
using the last three bytes of the public id to get equal usage. |
10,365 | def deprecate(message):
warnings.simplefilter()
warnings.warn(message, category=DeprecationWarning)
warnings.resetwarnings() | Loudly prints warning. |
10,366 | def _extract_apis_from_function(logical_id, function_resource, collector):
resource_properties = function_resource.get("Properties", {})
serverless_function_events = resource_properties.get(SamApiProvider._FUNCTION_EVENT, {})
SamApiProvider._extract_apis_from_events(logical_id, serverl... | Fetches a list of APIs configured for this SAM Function resource.
Parameters
----------
logical_id : str
Logical ID of the resource
function_resource : dict
Contents of the function resource including its properties
collector : ApiCollector
... |
10,367 | def getExtn(fimg, extn=None):
if extn is None:
_extn = fimg[0]
for _e in fimg:
if _e.data is not None:
_extn = _e
break
else:
if repr(extn).find() > 1:
if isinstance(extn, tuple):
... | Returns the PyFITS extension corresponding to extension specified in
filename.
Defaults to returning the first extension with data or the primary
extension, if none have data. If a non-existent extension has been
specified, it raises a `KeyError` exception. |
10,368 | def crosscov(x, y, axis=-1, all_lags=False, debias=True, normalize=True):
if x.shape[axis] != y.shape[axis]:
raise ValueError(
)
if debias:
x = remove_bias(x, axis)
y = remove_bias(y, axis)
slicing = [slice(d) for d in x.shape]
slicing[axis] = slice(... | Returns the crosscovariance sequence between two ndarrays.
This is performed by calling fftconvolve on x, y[::-1]
Parameters
----------
x : ndarray
y : ndarray
axis : time axis
all_lags : {True/False}
whether to return all nonzero lags, or to clip the length of s_xy
to be the... |
10,369 | def parse(cls, gvid, exception=True):
if gvid == :
return cls.get_class()(0)
if not bool(gvid):
return None
if not isinstance(gvid, six.string_types):
raise TypeError("Can{}{}null{}{}null{}{}sl']
except KeyError:
pass
r... | Parse a string value into the geoid of this class.
:param gvid: String value to parse.
:param exception: If true ( default) raise an eception on parse erorrs. If False, return a
'null' geoid.
:return: |
10,370 | def pull_requests(self):
pr_numbers = re.findall(r"[pP][rR]\s?[0-9]+", self.description)
pr_numbers += re.findall(re.compile("pull\s?request\s?[0-9]+", re.IGNORECASE), self.description)
pr_numbers = [re.sub(,, p) for p in pr_numbers]
return pr_numbers | Looks for any of the following pull request formats in the description field:
pr12345, pr 2345, PR2345, PR 2345 |
10,371 | def get_nexusvm_bindings(vlan_id, instance_id):
LOG.debug("get_nexusvm_bindings() called")
return _lookup_all_nexus_bindings(instance_id=instance_id,
vlan_id=vlan_id) | Lists nexusvm bindings. |
10,372 | def path(self, value):
prepval = value.replace(, )
self._path = posixpath.normpath(prepval) | Set path
:param value: The value for path
:type value: str
:raises: None |
10,373 | def subcorpus(self, selector):
subcorpus = self.__class__(self[selector],
index_by=self.index_by,
index_fields=self.indices.keys(),
index_features=self.features.keys())
return subcorpus | Generates a new :class:`.Corpus` using the criteria in ``selector``.
Accepts selector arguments just like :meth:`.Corpus.select`\.
.. code-block:: python
>>> corpus = Corpus(papers)
>>> subcorpus = corpus.subcorpus(('date', 1995))
>>> subcorpus
<tethne.cla... |
10,374 | def visibility_changed(self, enable):
super(SpyderPluginWidget, self).visibility_changed(enable)
if enable and not self.pydocbrowser.is_server_running():
self.pydocbrowser.initialize() | DockWidget visibility has changed |
10,375 | def _create_spec_config(self, table_name, spec_documents):
_spec_table = self._resource.Table(table_name + )
for doc in spec_documents:
_spec_table.put_item(Item=doc) | Dynamo implementation of spec config creation
Called by `create_archive_table()` in
:py:class:`manager.BaseDataManager` Simply adds two rows to the spec
table
Parameters
----------
table_name :
base table name (not including .spec suffix)
spec_doc... |
10,376 | def _message_hostgroup_parse(self, message):
splitter_count = message.count(WHostgroupBeaconMessenger.__message_groups_splitter__)
if splitter_count == 0:
return [], WBeaconGouverneurMessenger._message_address_parse(self, message)
elif splitter_count == 1:
splitter_pos = message.find(WHostgroupBeaconMess... | Parse given message and return list of group names and socket information. Socket information
is parsed in :meth:`.WBeaconGouverneurMessenger._message_address_parse` method
:param message: bytes
:return: tuple of list of group names and WIPV4SocketInfo |
10,377 | def _cmd_line_parser():
parser = argparse.ArgumentParser()
parser.add_argument(,
help=(
))
parser.add_argument(,
action=,
help=)
parser.add_argument(,
default=,
... | return a command line parser. It is used when generating the documentation |
10,378 | def init_environment():
os.environ[] =
pluginpath = os.pathsep.join((os.environ.get(, ), constants.BUILTIN_PLUGIN_PATH))
os.environ[] = pluginpath | Set environment variables that are important for the pipeline.
:returns: None
:rtype: None
:raises: None |
10,379 | def send_message(self, app_mxit_id, target_user_ids, message=, contains_markup=True,
spool=None, spool_timeout=None, links=None, scope=):
data = {
: app_mxit_id,
: ",".join(target_user_ids),
: message,
: contains_markup
}
... | Send a message (from a Mxit app) to a list of Mxit users |
10,380 | def parentLayer(self):
if self._parentLayer is None:
from ..agol.services import FeatureService
self.__init()
url = os.path.dirname(self._url)
self._parentLayer = FeatureService(url=url,
securityHandler=self.... | returns information about the parent |
10,381 | def run(main=None, argv=None):
flags_obj = flags.FLAGS
absl_flags_obj = absl_flags.FLAGS
args = argv[1:] if argv else None
flags_passthrough = flags_obj._parse_flags(args=args)
if absl_flags_obj["verbosity"].using_default_value:
absl_flags_obj.verbo... | Runs the program with an optional 'main' function and 'argv' list. |
10,382 | def get_events(self):
result = []
while self._wait(0):
event = self._read()
if event:
result.append(event)
return result | Returns a list of all joystick events that have occurred since the last
call to `get_events`. The list contains events in the order that they
occurred. If no events have occurred in the intervening time, the
result is an empty list. |
10,383 | def _lei16(ins):
output = _16bit_oper(ins.quad[2], ins.quad[3])
output.append()
output.append()
REQUIRES.add()
return output | Compares & pops top 2 operands out of the stack, and checks
if the 1st operand <= 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
16 bit signed version |
10,384 | def fetch(self, key: object, default=None):
return self._user_data.get(key, default) | Retrieves the related value from the stored user data. |
10,385 | def generate(str, alg):
img = Image.new(IMAGE_MODE, IMAGE_SIZE, BACKGROUND_COLOR)
hashcode = hash_input(str, alg)
pixelmap = setup_pixelmap(hashcode)
draw_image(pixelmap, img)
return img | Generates an PIL image avatar based on the given
input String. Acts as the main accessor to pagan. |
10,386 | def _get_user_data(self):
url = self.session.host + + str(self.session.id) + + str(self.id) +
r = requests.get(url)
if r.status_code == 200:
content = r.json()
else:
raise Exception()
return content | Base method for retrieving user data from a viz. |
10,387 | def open(self, filename, mode=, **kwargs):
if in mode and not self.backend.exists(filename):
raise FileNotFound(filename)
return self.backend.open(filename, mode, **kwargs) | Open the file and return a file-like object.
:param str filename: The storage root-relative filename
:param str mode: The open mode (``(r|w)b?``)
:raises FileNotFound: If trying to read a file that does not exists |
10,388 | def position(self):
line, col = self._position(self.chunkOffset)
return (line + 1, col) | Returns (line, col) of the current position in the stream. |
10,389 | def parseReaderConfig(self, confdict):
logger.debug(, confdict)
conf = {}
for k, v in confdict.items():
if not k.startswith():
continue
ty = v[]
data = v[]
vendor = None
subtype = None
try:
... | Parse a reader configuration dictionary.
Examples:
{
Type: 23,
Data: b'\x00'
}
{
Type: 1023,
Vendor: 25882,
Subtype: 21,
Data: b'\x00'
} |
10,390 | def count_sources(edge_iter: EdgeIterator) -> Counter:
return Counter(u for u, _, _ in edge_iter) | Count the source nodes in an edge iterator with keys and data.
:return: A counter of source nodes in the iterable |
10,391 | def ordered_expected_layers(self):
registry = QgsProject.instance()
layers = []
count = self.list_layers_in_map_report.count()
for i in range(count):
layer = self.list_layers_in_map_report.item(i)
origin = layer.data(LAYER_ORIGIN_ROLE)
if orig... | Get an ordered list of layers according to users input.
From top to bottom in the legend:
[
('FromCanvas', layer name, full layer URI, QML),
('FromAnalysis', layer purpose, layer group, None),
...
]
The full layer URI is coming from our helper.
... |
10,392 | def batch_predict_async(training_dir, prediction_input_file, output_dir,
mode, batch_size=16, shard_files=True, output_format=, cloud=False):
import google.datalab.utils as du
with warnings.catch_warnings():
warnings.simplefilter("ignore")
if cloud:
runner_results = cloud_ba... | Local and cloud batch prediction.
Args:
training_dir: The output folder of training.
prediction_input_file: csv file pattern to a file. File must be on GCS if
running cloud prediction
output_dir: output location to save the results. Must be a GSC path if
running cloud prediction.
mode... |
10,393 | def toc(self, depth=6, lowest_level=6):
depth = min(max(depth, 0), 6)
depth = 6 if depth == 0 else depth
lowest_level = min(max(lowest_level, 1), 6)
toc = self._root.to_dict()[]
def traverse(curr_toc, dep, lowest_lvl, curr_depth=1):
if curr_depth > dep:
... | Get table of content of currently fed HTML string.
:param depth: the depth of TOC
:param lowest_level: the allowed lowest level of header tag
:return: a list representing the TOC |
10,394 | def initialize(name=, pool_size=10, host=, password=, port=5432, user=):
global pool
instance = Pool(name=name, pool_size=pool_size, host=host, password=password, port=port, user=user)
pool = instance
return instance | Initialize a new database connection and return the pool object.
Saves a reference to that instance in a module-level variable, so applications with only one database
can just call this function and not worry about pool objects. |
10,395 | def _invoke_callbacks(self, *args, **kwargs):
for callback in self._done_callbacks:
_helpers.safe_invoke_callback(callback, *args, **kwargs) | Invoke all done callbacks. |
10,396 | def create_table(
data,
meta=None,
fields=None,
skip_header=True,
import_fields=None,
samples=None,
force_types=None,
max_rows=None,
*args,
**kwargs
):
table_rows = iter(data)
force_types = force_types or {}
if import_fields is not None:
import_fields = ... | Create a rows.Table object based on data rows and some configurations
- `skip_header` is only used if `fields` is set
- `samples` is only used if `fields` is `None`. If samples=None, all data
is filled in memory - use with caution.
- `force_types` is only used if `fields` is `None`
- `import_fiel... |
10,397 | def file_renamed_in_data_in_editorstack(self, editorstack_id_str,
original_filename, filename):
for editorstack in self.editorstacks:
if str(id(editorstack)) != editorstack_id_str:
editorstack.rename_in_data(original_filename,... | A file was renamed in data in editorstack, this notifies others |
10,398 | def pkcs7_pad(buf):
padder = cryptography.hazmat.primitives.padding.PKCS7(
cryptography.hazmat.primitives.ciphers.
algorithms.AES.block_size).padder()
return padder.update(buf) + padder.finalize() | Appends PKCS7 padding to an input buffer
:param bytes buf: buffer to add padding
:rtype: bytes
:return: buffer with PKCS7_PADDING |
10,399 | def _make_names_unique(animations):
counts = {}
for a in animations:
c = counts.get(a[], 0) + 1
counts[a[]] = c
if c > 1:
a[] += + str(c - 1)
dupes = set(k for k, v in counts.items() if v > 1)
for a in animations:
if a[] in dupes:
a[] += | Given a list of animations, some of which might have duplicate names, rename
the first one to be <duplicate>_0, the second <duplicate>_1,
<duplicate>_2, etc. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.