Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
360,600 | def _init_multicast_socket(self):
self.debug("()")
self._multicast_socket = socket.socket(
socket.AF_INET,
socket.SOCK_DGRAM
)
self._multicast_socket.setsockopt(
socket.SOL_SOCKET,
socket.SO_REUSEADDR,
... | Init multicast socket
:rtype: None |
360,601 | async def fastStreamedQuery(self, url, *, headers=None, verify=True):
response = await self.session.get(url,
headers=self._buildHeaders(headers),
timeout=HTTP_SHORT_TIMEOUT,
ssl=verify)
respon... | Send a GET request with short timeout, do not retry, and return streamed response. |
360,602 | def _getOutputElegant(self, **kws):
datascript = "sddsprintdata.sh"
datapath = self.sim_path
trajparam_list = kws[]
sddsfile = os.path.expanduser(os.path.join(self.sim_path, kws[]))
dh = datautils.DataExtracter(sddsfile, *trajparam_list)
dh.setDataScript(datascri... | get results from elegant output according to the given keywords,
input parameter format: key = sdds field name tuple, e.g.:
available keywords are:
- 'file': sdds fielname, file = test.sig
- 'data': data array, data = ('s','Sx')
- 'dump': h5file name, if... |
360,603 | def add_ngram(sequences, token_indice, ngram_range=2):
new_sequences = []
for input_list in sequences:
new_list = input_list[:]
for i in range(len(new_list) - ngram_range + 1):
for ngram_value in range(2, ngram_range + 1):
ngram = tuple(new_list[i:i + ngram_value... | Augment the input list of list (sequences) by appending n-grams values.
Example: adding bi-gram
>>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]]
>>> token_indice = {(1, 3): 1337, (9, 2): 42, (4, 5): 2017}
>>> add_ngram(sequences, token_indice, ngram_range=2)
[[1, 3, 4, 5, 1337, 2017], [1, 3, 7, 9, 2,... |
360,604 | def run(hostname=None, port=None, path=None, loop=None):
if path:
log.debug("Starting Opentrons server application on {}".format(
path))
hostname, port = None, None
else:
log.debug("Starting Opentrons server application on {}:{}".format(
hostname, port))
... | The arguments are not all optional. Either a path or hostname+port should
be specified; you have to specify one. |
360,605 | def search_my_notes(self, loan_id=None, order_id=None, grade=None, portfolio_name=None, status=None, term=None):
assert grade is None or type(grade) is str,
assert portfolio_name is None or type(portfolio_name) is str,
index = 0
found = []
sort_by = if order_id is no... | Search for notes you are invested in. Use the parameters to define how to search.
Passing no parameters is the same as calling `my_notes(get_all=True)`
Parameters
----------
loan_id : int, optional
Search for notes for a specific loan. Since a loan is broken up into a pool o... |
360,606 | def is_pyclustering_instance(model):
return any(isinstance(model, i) for i in [xmeans, clarans, rock, optics]) | Checks if the clustering.rst algorithm belongs to pyclustering
:param model: the clustering.rst algorithm model
:return: the truth value (Boolean) |
360,607 | def _execute_network_run(self, traj, network, network_dict, component_list,
analyser_list, pre_run=False):
subrun_list = self._extract_subruns(traj, pre_run=pre_run)
subrun_number = 0
while len(subrun_list) > 0:
... | Generic `execute_network_run` function, handles experimental runs as well as pre-runs.
See also :func:`~pypet.brian2.network.NetworkRunner.execute_network_run` and
:func:`~pypet.brian2.network.NetworkRunner.execute_network_pre_run`. |
360,608 | def _before_after(n_samples):
if not isinstance(n_samples, (tuple, list)):
before = n_samples // 2
after = n_samples - before
else:
assert len(n_samples) == 2
before, after = n_samples
n_samples = before + after
assert before >= 0
assert after >= 0
assert... | Get the number of samples before and after. |
360,609 | def get_delete_url_link(self, text=None, cls=None, icon_class=None,
**attrs):
if text is None:
text =
return build_link(href=self.get_delete_url(),
text=text,
cls=cls,
icon_cl... | Gets the html delete link for the object. |
360,610 | def get(self, time, interpolate=):
try:
getter = self.getter_functions[interpolate]
except KeyError:
msg = (
"unknown value for interpolate, "
"valid values are in [{}]"
).format(interpolate, .join(self.getter_functions))
... | Get the value of the time series, even in-between measured values. |
360,611 | def spectrogram_image(mediafile, dpi=72, outdir=None, outfile=None):
import matplotlib
matplotlib.use()
import matplotlib.pyplot as plt
import scipy.io.wavfile
import numpy as np
import pylab
outfile = outfile or ""
if outdir and outfile and os.sep in outfile:
ra... | Create spectrogram image from audio data.
Return path to created image file. |
360,612 | def is_too_early_to_signup(self, now=None):
if now is None:
now = datetime.datetime.now()
activity_date = (datetime.datetime.combine(self.block.date, datetime.time(0, 0, 0)))
presign_period = datetime.timedelta(days=2)
return (now < (activity_date - presig... | Return whether it is too early to sign up for the activity if it is a presign (48 hour
logic is here). |
360,613 | def _getArgNames(spec):
return set(
spec.args
+ spec.kwonlyargs
+ ((,) if spec.varargs else ())
+ ((,) if spec.varkw else ())
+ spec.annotations
) | Get the name of all arguments defined in a function signature.
The name of * and ** arguments is normalized to "*args" and "**kwargs".
:param ArgSpec spec: A function to interrogate for a signature.
:return: The set of all argument names in `func`s signature.
:rtype: Set[str] |
360,614 | def file_mode(self):
fms = self.attributes[]
eax = set()
if isinstance(fms, six.string_types):
fms = shlex.split(fms)
for fm in fms:
if fm == :
eax.add()
eax.add()
elif fm in [, ]:
eax.add(fm)
... | onefile, fpp, or both |
360,615 | def _get_scale_and_shape_sim(self, transformed_lvs):
if self.scale is True:
if self.shape is True:
model_shape = self.latent_variables.z_list[-1].prior.transform(transformed_lvs[-1, :])
model_scale = self.latent_variables.z_list[-2].prior.transform(transfor... | Obtains model scale, shape, skewness latent variables for
a 2d array of simulations.
Parameters
----------
transformed_lvs : np.array
Transformed latent variable vector (2d - with draws of each variable)
Returns
----------
- Tuple of np.arrays (each ... |
360,616 | def add_mea(mea_yaml_path):
path = os.path.abspath(mea_yaml_path)
if path.endswith() or path.endswith() and os.path.isfile(path):
with open(path, ) as meafile:
if use_loader:
elinfo = yaml.load(meafile, Loader=yaml.FullLoader)
else:
elinfo = ... | Adds the mea design defined by the yaml file in the install folder
Parameters
----------
mea_yaml_file
Returns
------- |
360,617 | def matchremove_noun_endings(word):
was_stemmed = False
noun_endings = [, , , , , , , , , , , ]
for ending in noun_endings:
if word in exceptions:
word = word
was_stemmed = True
break
if word == ending:
word = word
... | Remove the noun and adverb word endings |
360,618 | def jsonify_error(message_or_exception, status_code=400):
if isinstance(message_or_exception, Exception):
message = % (
message_or_exception.__class__.__name__, message_or_exception)
else:
message = message_or_exception
logging.debug(,
status_code, messag... | Returns a JSON payload that indicates the request had an error. |
360,619 | def interleaveblastresults(query, subject):
matchstring =
blaststring =
for i, bp in enumerate(query):
if bp == subject[i]:
matchstring +=
else:
matchstring +=
prev =... | Creates an interleaved string that resembles BLAST sequence comparisons
:param query: Query sequence
:param subject: Subject sequence
:return: Properly formatted BLAST-like sequence comparison |
360,620 | def pass_to_client(self, event, data, *args):
self.q.put((event, data, *args)) | Passes data up to the client via a Queue().
:param event:
:param data:
:param args:
:return: |
360,621 | def get_klass(self):
klass_name = self.kwargs.get(, None)
klass = self.registry.get(klass_name, None)
if not klass:
raise Http404("Unknown autocomplete class `{}`".format(klass_name))
return klass | Return the agnocomplete class to be used with the eventual query. |
360,622 | def v_reference_leaf_leafref(ctx, stmt):
if (hasattr(stmt, ) and
stmt.i_leafref is not None and
stmt.i_leafref_expanded is False):
path_type_spec = stmt.i_leafref
not_req_inst = not(path_type_spec.require_instance)
x = validate_leafref_path(ctx, stmt,
... | Verify that all leafrefs in a leaf or leaf-list have correct path |
360,623 | def join(self):
self.tasks.join()
for worker in self.workers:
self.tasks.put(None)
for worker in self.workers:
worker.join()
worker.s3 = None | Utility function to wait all tasks to complete |
360,624 | def fundfeepool(ctx, symbol, amount, account):
print_tx(ctx.bitshares.fund_fee_pool(symbol, amount, account=account)) | Fund the fee pool of an asset |
360,625 | def fetch_file(
download_url,
filename=None,
decompress=False,
subdir=None,
force=False,
timeout=None,
use_wget_if_available=False):
filename = build_local_filename(download_url, filename, decompress)
full_path = build_path(filename, subdir)
if no... | Download a remote file and store it locally in a cache directory. Don't
download it again if it's already present (unless `force` is True.)
Parameters
----------
download_url : str
Remote URL of file to download.
filename : str, optional
Local filename, used as cache key. If omitte... |
360,626 | def get_previous_price_list(self, currency, start_date, end_date):
start = start_date.strftime()
end = end_date.strftime()
url = (
.format(
start, end, currency
)
)
response = requests.get(url)
if respons... | Get List of prices between two dates |
360,627 | def Kdiag(self, X):
K_ff = np.ones(X.shape[0])
for i,x in enumerate(X):
for il,l in enumerate(self.lengthscale):
idx = il*2
K_ff[i] *= self.k_ff(x[idx],x[idx],l)
return K_ff * self.variances[0] | I've used the fact that we call this method for K_ff when finding the covariance as a hack so
I know if I should return K_ff or K_xx. In this case we're returning K_ff!!
$K_{ff}^{post} = K_{ff} - K_{fx} K_{xx}^{-1} K_{xf}$ |
360,628 | def generate_pair(algorithm, bit_size=None, curve=None):
if algorithm not in set([, , ]):
raise ValueError(pretty_message(
,
repr(algorithm)
))
if algorithm == :
if bit_size not in set([1024, 2048, 3072, 4096]):
raise ValueError(pretty_message(
... | Generates a public/private key pair
:param algorithm:
The key algorithm - "rsa", "dsa" or "ec"
:param bit_size:
An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024,
2048, 3072 or 4096. For "dsa" the value may be 1024, plus 2048 or 3072
if OpenSSL 1.0.0 or ne... |
360,629 | def power_law_anisotropy(self, r, kwargs_profile, kwargs_anisotropy, kwargs_light):
theta_E = kwargs_profile[]
gamma = kwargs_profile[]
r_ani = kwargs_anisotropy[]
a = 0.551 * kwargs_light[]
rho0_r0_gamma = self._rho0_r0_gamma(theta_E, gamma)
prefac1 = 4... | equation (19) in Suyu+ 2010
:param r:
:return: |
360,630 | def set_attribute(library, session, attribute, attribute_state):
return library.viSetAttribute(session, attribute, attribute_state) | Sets the state of an attribute.
Corresponds to viSetAttribute function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param attribute: Attribute for which the state is to be modified. (Attributes.*)
:param attribute... |
360,631 | def dict_encode(in_dict):
if _IS_PY2:
out_dict = {}
for k, v in list(in_dict.items()):
if isinstance(v, unicode):
v = v.encode()
elif isinstance(v, str):
v.decode()
out_dict[k] = v
return out_dict
e... | returns a new dictionary with encoded values useful for encoding http queries (python < 3) |
360,632 | def get_avatar_upload_to(self, filename):
dummy, ext = os.path.splitext(filename)
return os.path.join(
machina_settings.PROFILE_AVATAR_UPLOAD_TO,
.format(id=str(uuid.uuid4()).replace(, ), ext=ext),
) | Returns the path to upload the associated avatar to. |
360,633 | def get_data_mask_functions(is_micro):
def fn0(i, j):
return (i + j) & 0x1 == 0
def fn1(i, j):
return i & 0x1 == 0
def fn2(i, j):
return j % 3 == 0
def fn3(i, j):
return (i + j) % 3 == 0
def fn4(i, j):
return (i // 2 + j // 3) & 0x1 == 0
def... | Returns the data mask functions.
ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50)
Table 10 — Data mask pattern generation conditions (page 50)
=============== ===================== =====================================
QR Code Pattern Micro QR Code Pattern Condition
========... |
360,634 | def update_by_external_id(self, api_objects):
if not isinstance(api_objects, collections.Iterable):
api_objects = [api_objects]
return CRUDRequest(self).put(api_objects, update_many_external=True) | Update (PUT) one or more API objects by external_id.
:param api_objects: |
360,635 | def remove_section(file_name, section, separator=):
targetini.remove_section*
inifile = _Ini.get_ini_file(file_name, separator=separator)
if section in inifile:
section = inifile.pop(section)
inifile.flush()
ret = {}
for key, value in six.iteritems(section):
if ke... | Remove a section in an ini file. Returns the removed section as dictionary,
or ``None`` if nothing was removed.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.remove_section',
[path_to_ini_file, section_name... |
360,636 | def merge_two_dictionaries(a, b, merge_lists=False):
key = None
try:
if a is None or isinstance(a, (six.string_types, six.text_type, six.integer_types, float)):
a = b
elif isinstance(a, list):
if isinstance(b, list):
... | Merges b into a and returns merged result
NOTE: tuples and arbitrary objects are not handled as it is totally ambiguous what should happen
Args:
a (DictUpperBound): dictionary to merge into
b (DictUpperBound): dictionary to merge from
merge_lists (bool): Whether to merge lists (True) o... |
360,637 | def get_python_path(venv_path):
bin_path = get_bin_path(venv_path)
program_path = os.path.join(bin_path, )
if sys.platform.startswith():
program_path = program_path +
return program_path | Get given virtual environment's `python` program path.
:param venv_path: Virtual environment directory path.
:return: `python` program path. |
360,638 | def _obj_display(obj, display=):
result =
if not display:
result = str(obj)
else:
template = Template(display)
context = Context({:obj})
result = template.render(context)
return result | Returns string representation of an object, either the default or based
on the display template passed in. |
360,639 | def send_message(self, user=None, message=None,channel=None):
self.transport.send_message(user=user, message=message, channel=channel) | Todo connect |
360,640 | def _gh(self, x):
Pgen = x[self._Pg.i1:self._Pg.iN + 1]
Qgen = x[self._Qg.i1:self._Qg.iN + 1]
for i, gen in enumerate(self._gn):
gen.p = Pgen[i] * self._base_mva
gen.q = Qgen[i] * self._base_mva
Sbus = self.om.case.getSbus(self._bs)
... | Evaluates the constraint function values. |
360,641 | def _get_proper_filename(file, kind, extension,
date=None, possible_names=None):
if isinstance(file, pathlib.Path):
file = str(file.absolute())
if file is not None and not isinstance(file, str):
return file
if file is N... | Gets a proper filename for 'file', if this is a path.
'kind' should be the kind of the output file (photo, document...)
'extension' should be the extension to be added to the file if
the filename doesn't have any yet
'date' should be when this file was originally... |
360,642 | def extract_nodes(soup, nodename, attr = None, value = None):
tags = soup.find_all(nodename)
if attr != None and value != None:
return list(filter(lambda tag: tag.get(attr) == value, tags))
return list(tags) | Returns a list of tags (nodes) from the given soup matching the given nodename.
If an optional attribute and value are given, these are used to filter the results
further. |
360,643 | def register_factory(self, specification, factory, scope=None):
self.register_provider(
specification,
FactoryProvider(factory, scope=scope)
) | Shortcut for creating and registering
a :py:class:`wiring.providers.FactoryProvider`. |
360,644 | def set_siren_volume(self, volume):
values = {
"desired_state": {
"siren_volume": volume
}
}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(response) | :param volume: one of [low, medium, high] |
360,645 | def create_schema(self):
cursor = self.cursor
execute = cursor.execute
execute()
tables = {table for table, in cursor}
if not in tables:
execute()
if not in tables:
execute()
if not in tables:
execute()
if n... | Create all necessary tables |
360,646 | def sync(args):
import operator
session = c.Session(args)
if "all" in args["names"]:
targetfeeds = session.list_feeds()
else:
targetfeeds = []
for name in args["names"]:
if name not in session.feeds:
print("You don'.join(["I cannot sync ", feed,
... | Implement the 'greg sync' command |
360,647 | def spline_interpolate(x_axis, y_axis, x_new_axis):
f = interp1d(x_axis, y_axis, kind="cubic")
return f(x_new_axis) | Interpolate a y = f(x) function using Spline interpolation algorithm,
x_new_axis has to be in range of x_axis.
`Spline interpolation <https://en.wikipedia.org/wiki/Spline_interpolation>`_
is a popular interpolation method. Way more accurate than linear interpolate
in average |
360,648 | def read(self, size=None):
if size is not None:
read_size = min(size, self.__remaining_bytes)
else:
read_size = self.__remaining_bytes
data = self.__stream.read(read_size)
if read_size > 0 and not data:
raise exceptions.StreamExhausted(
... | Read at most size bytes from this slice.
Compared to other streams, there is one case where we may
unexpectedly raise an exception on read: if the underlying stream
is exhausted (i.e. returns no bytes on read), and the size of this
slice indicates we should still be able to read more by... |
360,649 | def pred_from_structures(self, target_species, structures_list,
remove_duplicates=True, remove_existing=False):
target_species = get_el_sp(target_species)
result = []
transmuter = StandardTransmuter([])
if len(list(set(target_species) & set(self.get_... | performs a structure prediction targeting compounds containing all of
the target_species, based on a list of structure (those structures
can for instance come from a database like the ICSD). It will return
all the structures formed by ionic substitutions with a probability
higher than th... |
360,650 | def stepBy(self, steps):
oldValue = self.value()
if oldValue == 0:
newValue = steps
elif steps == 1:
newValue = self.value() * self.smallStepFactor
elif steps == -1:
newValue = self.value() / self.smallStepFactor
elif steps == 10:
... | Function that is called whenever the user triggers a step. The steps parameter
indicates how many steps were taken, e.g. Pressing Qt::Key_Down will trigger a call to
stepBy(-1), whereas pressing Qt::Key_Prior will trigger a call to stepBy(10). |
360,651 | def combine_slices(slice_datasets, rescale=None):
s coordinate system.
Returns a two-tuple containing the 3D-ndarray and the affine matrix.
If `rescale` is set to `None` (the default), then the image array dtype
will be preserved, unless any of the DICOM images contain either the
`Rescale Slope
... | Given a list of pydicom datasets for an image series, stitch them together into a
three-dimensional numpy array. Also calculate a 4x4 affine transformation
matrix that converts the ijk-pixel-indices into the xyz-coordinates in the
DICOM patient's coordinate system.
Returns a two-tuple containing the 3... |
360,652 | def update_feature_value(host_name, client_name, client_pass, user_twitter_id, feature_name, feature_score):
username = str(user_twitter_id)
feature_value = "{0:.2f}".format(feature_score)
joined_ftr_value = "ftr_" + feature_name + "=" + str(feature_value)
values = "usr=%s&%s" % (username, joined_f... | Updates a single topic score, for a single user.
Inputs: - host_name: A string containing the address of the machine where the PServer instance is hosted.
- client_name: The PServer client name.
- client_pass: The PServer client's password.
- user_twitter_id: A Twitter user iden... |
360,653 | def seek(self, offset, whence):
if not isinstance(offset, baseinteger):
raise TypeError("offset can only be an instance of type baseinteger")
if not isinstance(whence, FileSeekOrigin):
raise TypeError("whence can only be an instance of type FileSeekOrigin")
new_o... | Changes the current file position of this file.
The file current position always applies to the :py:func:`IFile.read`
method. Same for the :py:func:`IFile.write` method it except when
the :py:func:`IFile.access_mode` is :py:attr:`FileAccessMode.append_only`
or :py:attr:`Fil... |
360,654 | async def read(self, count=-1):
await self.wait("read")
start = _now()
data = await super().read(count)
self.append("read", data, start)
return data | :py:func:`asyncio.coroutine`
:py:meth:`aioftp.StreamIO.read` proxy |
360,655 | def create_api(self):
created_api = self.client.create_rest_api(name=self.trigger_settings.get(, self.app_name))
api_id = created_api[]
self.log.info("Successfully created API")
return api_id | Create the REST API. |
360,656 | def hypercube(number_of_samples, variables):
number_of_dimensions = len(variables)
segment_ranges = []
for i in range(number_of_samples):
ratio = 1.0 / number_of_samples
segment_ranges.append((ratio * i, ratio * (i + 1)))
x = []
for i in range(number_of_dimensions):
... | This implements Latin Hypercube Sampling.
See https://mathieu.fenniak.net/latin-hypercube-sampling/ for intuitive explanation of what it is
:param number_of_samples: number of segments/samples
:param variables: initial parameters and conditions (list of ranges, i.e. (70, 110), (0.1, 0.5) ..)
:return: |
360,657 | def _dilated_conv_layer(self, output_channels, dilation_rate, apply_relu,
name):
layer_components = [
conv.Conv2D(
output_channels, [3, 3],
initializers=self._initializers,
regularizers=self._regularizers,
rate=dilation_rate,
... | Create a dilated convolution layer.
Args:
output_channels: int. Number of output channels for each pixel.
dilation_rate: int. Represents how many pixels each stride offset will
move. A value of 1 indicates a standard convolution.
apply_relu: bool. If True, a ReLU non-linearlity is added.
... |
360,658 | def create(cls, changes, ref, excluded_categories=set()):
ref = dict(ref)
obj = obj_deref(ref)
if isinstance(obj, Category):
if any(c.id in excluded_categories for c in obj.chain_query):
return
else:
event = obj if isinstance(obj, Event) ... | Create a new change in all queues.
:param changes: the change types, an iterable containing
:class:`ChangeType`
:param ref: the object reference (returned by `obj_ref`)
of the changed object
:param excluded_categories: set of categories (IDs) whos... |
360,659 | def get_untranscribed_prefixes_from_file(target_directory: Path) -> List[str]:
untranscribed_prefix_fn = target_directory / "untranscribed_prefixes.txt"
if untranscribed_prefix_fn.exists():
with untranscribed_prefix_fn.open() as f:
prefixes = f.readlines()
return [prefix.strip... | The file "untranscribed_prefixes.txt" will specify prefixes which
do not have an associated transcription file if placed in the target directory.
This will fetch those prefixes from that file and will return an empty
list if that file does not exist.
See find_untranscribed_wavs function for finding un... |
360,660 | def fail_acs_response(request, *args, **kwargs):
failure_function = import_string(get_custom_setting(,
))
return failure_function(request, *args, **kwargs) | Serves as a common mechanism for ending ACS in case of any SAML related failure.
Handling can be configured by setting the SAML_ACS_FAILURE_RESPONSE_FUNCTION as
suitable for the project.
The default behavior uses SAML specific template that is rendered on any ACS error,
but this can be simply changed s... |
360,661 | def Down(self, n = 1, dl = 0):
self.Delay(dl)
self.keyboard.tap_key(self.keyboard.down_key, n) | 下方向键n次 |
360,662 | def get_saml_slos(cls, logout_request):
try:
root = etree.fromstring(logout_request)
return root.xpath(
"//samlp:SessionIndex",
namespaces={: "urn:oasis:names:tc:SAML:2.0:protocol"})
except etree.XMLSyntaxError:
return None | returns saml logout ticket info |
360,663 | def copy(self):
layout_copy = type(self)()
layout_copy._p2v = self._p2v.copy()
layout_copy._v2p = self._v2p.copy()
return layout_copy | Returns a copy of a Layout instance. |
360,664 | def init_app(self, app, session=None, parameters=None):
if parameters is not None and not isinstance(parameters, ParamsBuilder):
raise InvalidUsage("parameters should be a pysnow.ParamsBuilder object, not %r" % type(parameters).__name__)
self._session = session
self._param... | Initializes snow extension
Set config default and find out which client type to use
:param app: App passed from constructor or directly to init_app (factory)
:param session: requests-compatible session to pass along to init_app
:param parameters: `ParamsBuilder` object passed to `Clien... |
360,665 | def enable_peer_bfd(self, **kwargs):
method_name = \
bfd_enable = getattr(self._rbridge, method_name)
kwargs[] = kwargs.pop()
callback = kwargs.pop(, self._callback)
config = bfd_enable(**kwargs)
if kwargs.pop(, False):
tag =
... | BFD enable for each specified peer.
Args:
rbridge_id (str): Rbridge to configure. (1, 225, etc)
peer_ip (str): Peer IPv4 address for BFD setting.
delete (bool): True if BFD configuration should be deleted.
Default value will be False if not specified.
... |
360,666 | def getProcessName(self, pid):
ps = subprocess.check_output(["ps", "aux"]).decode("ascii")
processes = ps.split("\n")
cols = len(processes[0].split()) - 1
for row in processes[1:]:
if row != "":
proc = row.split(None, cols)
if proc[1].... | Searches all processes for the given PID, then returns the originating command |
360,667 | def _set_pwm(self, raw_values):
for i in range(len(self._pins)):
self._device.set_pwm(self._pins[i], 0, raw_values[i]) | Set pwm values on the controlled pins.
:param raw_values: Raw values to set (0-4095). |
360,668 | def vector_cross(vector1, vector2):
try:
if vector1 is None or len(vector1) == 0 or vector2 is None or len(vector2) == 0:
raise ValueError("Input vectors cannot be empty")
except TypeError as e:
print("An error occurred: {}".format(e.args[-1]))
raise TypeError("Input mus... | Computes the cross-product of the input vectors.
:param vector1: input vector 1
:type vector1: list, tuple
:param vector2: input vector 2
:type vector2: list, tuple
:return: result of the cross product
:rtype: tuple |
360,669 | def _add_resource_descriptions_to_pools(self, meta_list):
if not meta_list:
return
for meta in meta_list:
getattr(resources, meta.resource_type).add(meta) | Takes a list of resource descriptions adding them
to the resource pool they belong to scheduling them for loading. |
360,670 | def _set_fcoe_map_cee_map(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=fcoe_map_cee_map.fcoe_map_cee_map, is_container=, presence=False, yang_name="fcoe-map-cee-map", rest_name="cee-map", parent=self, path_helper=self._path_helper, extmethods=self.... | Setter method for fcoe_map_cee_map, mapped from YANG variable /fcoe/fcoe_map/fcoe_map_cee_map (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoe_map_cee_map is considered as a private
method. Backends looking to populate this variable should
do so via calli... |
360,671 | def _group_sql(self, quote_char=None, groupby_alias=True, **kwargs):
clauses = []
selected_aliases = {s.alias for s in self._selects}
for field in self._groupbys:
if groupby_alias and field.alias and field.alias in selected_aliases:
clauses.append("{quote}{al... | Produces the GROUP BY part of the query. This is a list of fields. The clauses are stored in the query under
self._groupbys as a list fields.
If an groupby field is used in the select clause,
determined by a matching alias, and the groupby_alias is set True
then the GROUP BY clause wil... |
360,672 | def append_dictionary_to_file(localization_key_to_comment, file_path, section_name):
output_file = open_strings_file(file_path, "a")
write_section_header_to_file(output_file, section_name)
for entry_key, entry_comment in sorted(localization_key_to_comment.iteritems(), key=operator.itemgetter(1)):
... | Appends dictionary of localization keys and comments to a file
Args:
localization_key_to_comment (dict): A mapping between localization keys and comments.
file_path (str): The path of the file to append to.
section_name (str): The name of the section. |
360,673 | def collect_translations(self):
languages = {}
locale_data = {}
for language_code, label in settings.LANGUAGES:
languages[language_code] = % label
trans_cat, trans_fallback_cat = self.get_catalog(language_code)
locale_dat... | Collect all `domain` translations and return `Tuple[languages, locale_data]` |
360,674 | def template_tag(library, name):
def _inner(cls):
if hasattr(cls, ):
compile_function = cls.parse
else:
compile_function = cls
library.tag(name, compile_function)
return cls
return _inner | Decorator to register class tags
:param library: The template tag library, typically instantiated as ``register = Library()``.
:type library: :class:`~django.template.Library`
:param name: The name of the template tag
:type name: str
Example:
.. code-block:: python
@template_tag(regi... |
360,675 | def transform(self, trans):
clone = deepcopy(self)
for n in clone.iter_sections():
n.points[:, 0:3] = trans(n.points[:, 0:3])
return clone | Return a copy of this neurite with a 3D transformation applied |
360,676 | def to_hdf(path_or_buf, key, value, mode=None, complevel=None, complib=None,
append=None, **kwargs):
if append:
f = lambda store: store.append(key, value, **kwargs)
else:
f = lambda store: store.put(key, value, **kwargs)
path_or_buf = _stringify_path(path_or_buf)
if isi... | store this object, close it if we opened it |
360,677 | def prt_txt(self, prt=sys.stdout, pre=):
data_nts = self.get_d1nts()
for ntdata in data_nts:
prt.write("{PRE}{L:1} {NS} {d:6,} D{D:02} {GO} {NAME}\n".format(
PRE=pre,
L=ntdata.D1,
d=ntdata.dcnt,
NS=ntdata.NS,
... | Print letters, descendant count, and GO information. |
360,678 | def define_cyclic_can_msg(self, channel, can_msg=None):
if can_msg is not None:
c_can_msg = (CanMsg * len(can_msg))(*can_msg)
c_count = DWORD(len(can_msg))
else:
c_can_msg = CanMsg()
c_count = 0
UcanDefineCyclicCanMsg(self._handle, channel... | Defines a list of CAN messages for automatic transmission.
:param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param list(CanMsg) can_msg:
List of CAN messages (up to 16, see structure :class:`CanMsg`), or None to delete an older list. |
360,679 | def AddHeader(self, header, value):
self.user_headers.append((header, value))
return self | Add a header to send. |
360,680 | def people_per_project(self, project_id, company_id):
path = % (project_id, company_id)
return self._request(path) | This will return all of the people in the given company that can
access the given project. |
360,681 | def _parse_response(self, resp):
access = resp["access"]
token = access.get("token")
self.token = token["id"]
self.tenant_id = token["tenant"]["id"]
self.tenant_name = token["tenant"]["name"]
self.expires = self._parse_api_time(token["expires"])
self.serv... | Gets the authentication information from the returned JSON. |
360,682 | def open_stream(self, destination, timeout_ms=None):
timeout = timeouts.PolledTimeout.from_millis(timeout_ms)
stream_transport = self._make_stream_transport()
self.transport.write_message(
adb_message.AdbMessage(
command=,
arg0=stream_transport.local_id, arg1=0,
... | Opens a new stream to a destination service on the device.
Not the same as the posix 'open' or any other Open methods, this
corresponds to the OPEN message described in the ADB protocol
documentation mentioned above. It creates a stream (uniquely identified
by remote/local ids) that connects to a part... |
360,683 | def _convert_source_mapping(offset, slither):
startlengthfilenamefile.sol
sourceUnits = slither.source_units
position = re.findall(, offset)
if len(position) != 1:
return {}
s, l, f = position[0]
s = int(s)
l = int(l)
f = int(f)
if f... | Convert a text offset to a real offset
see https://solidity.readthedocs.io/en/develop/miscellaneous.html#source-mappings
Returns:
(dict): {'start':0, 'length':0, 'filename': 'file.sol'} |
360,684 | def apply_files_filter(self, frame, filename, force_check_project_scope):
cache_key = (frame.f_code.co_firstlineno, frame.f_code.co_name, filename, force_check_project_scope)
try:
return self._apply_filter_cache[cache_key]
except KeyError:
if self.plugin is not N... | Should only be called if `self.is_files_filter_enabled == True`.
Note that it covers both the filter by specific paths includes/excludes as well
as the check which filters out libraries if not in the project scope.
:param force_check_project_scope:
Check that the file is in the pro... |
360,685 | def usernameFromRequest(request):
username = request.args.get(, [])[0]
if not in username:
username = % (
username, request.getHeader().split()[0])
return username | Take an HTTP request and return a username of the form <user>@<domain>.
@type request: L{inevow.IRequest}
@param request: A HTTP request
@return: A C{str} |
360,686 | def add_to_win32_PATH(script_fpath, *add_path_list):
r
import utool as ut
write_dir = dirname(script_fpath)
key =
rtype =
win_pathlist = list(os.environ[].split(os.path.pathsep))
new_path_list = ut.unique_ordered(win_pathlist + list(add_path_list))
print(.join(new_path_list))... | r"""
Writes a registery script to update the PATH variable into the sync registry
CommandLine:
python -m utool.util_win32 --test-add_to_win32_PATH --newpath "C:\Program Files (x86)\Graphviz2.38\bin"
Example:
>>> # DISABLE_DOCTEST
>>> # SCRIPT
>>> from utool.util_win32 impor... |
360,687 | def _next_mutation(self):
if self._keep_running():
current_idx = self.model.current_index()
self.session_info.current_index = current_idx
next_idx = self._test_list.current()
if next_idx is None:
return False
skip = next_idx - ... | :return: True if mutated, False otherwise |
360,688 | def gen_source_models(self, gsim_lt):
samples_by_lt_path = self.samples_by_lt_path()
for i, rlz in enumerate(get_effective_rlzs(self)):
smpath = rlz.lt_path
num_samples = samples_by_lt_path[smpath]
num_gsim_paths = (num_samples if self.num_samples
... | Yield empty LtSourceModel instances (one per effective realization) |
360,689 | def summary_gradient_updates(grads, opt, lr):
vars_grads = {}
for v in tf.trainable_variables():
vars_grads[v.name] = [v, None, None]
for g, v in grads:
vars_grads[v.name][1] = g
vars_grads[v.name][2] = opt.get_slot(v, )
ret = []
for vname, (v, g, a) in ... | get summary ops for the magnitude of gradient updates |
360,690 | def _configure_common(
self,
prefix,
fallback_level,
fallback_format,
handler_name,
handler,
custom_args=
):
log_level = self.config.get_option(
, prefix + ,
None, fallback_level
... | commom configuration code
Args:
prefix (str): A prefix for the `log_level` and `log_format` keys to use with the config. #FIXME: Hacky, add separate sections for each logger config?
fallback_level (str): Fallback/minimum log level, for if config does not have one.
fallback_f... |
360,691 | def best_unique_genomes(self, n):
best_unique = {}
for g in self.most_fit_genomes:
best_unique[g.key] = g
best_unique_list = list(best_unique.values())
def key(genome):
return genome.fitness
return sorted(best_unique_list, key=key, reverse=True)... | Returns the most n fit genomes, with no duplication. |
360,692 | def getbalance(self, **params):
if not all([self.api_key, self.api_secret]):
raise AuthException()
endpoint = "/v1/me/getbalance"
return self.request(endpoint, params=params) | Get Account Asset Balance
API Type
--------
HTTP Private API
Docs
----
https://lightning.bitflyer.jp/docs?lang=en#get-account-asset-balance |
360,693 | def write_can_msg(self, channel, can_msg):
c_can_msg = (CanMsg * len(can_msg))(*can_msg)
c_count = DWORD(len(can_msg))
UcanWriteCanMsgEx(self._handle, channel, c_can_msg, c_count)
return c_count | Transmits one ore more CAN messages through the specified CAN channel of the device.
:param int channel:
CAN channel, which is to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param list(CanMsg) can_msg: List of CAN message structure (see structure :class:`CanMsg`).... |
360,694 | def send_scp_burst(self, buffer_size, window_size,
parameters_and_callbacks):
parameters_and_callbacks = iter(parameters_and_callbacks)
self.sock.setblocking(False)
max_length = buffer_size + consts.SDP_HEADER_LENGTH
receive_length = in... | Send a burst of SCP packets and call a callback for each returned
packet.
Parameters
----------
buffer_size : int
Number of bytes held in an SCP buffer by SARK, determines how many
bytes will be expected in a socket.
window_size : int
Number o... |
360,695 | def ensure_working_tree(self):
if not self.supports_working_tree:
raise MissingWorkingTreeError(compact(, friendly_name=self.friendly_name, directory=format_path(self.local))) | Make sure the local repository has working tree support.
:raises: :exc:`~vcs_repo_mgr.exceptions.MissingWorkingTreeError` when
the local repository doesn't support a working tree. |
360,696 | def calculate_one_hot_encoder_output_shapes(operator):
]
C
check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1)
if operator.inputs[0].type.shape[1] != 1 or len(operator.inputs[0].type.shape) > 2:
raise RuntimeError()
int_categories = operator.raw_operator.on... | Allowed input/output patterns are
1. [N, 1] ---> [N, C']
C' is the total number of categorical values. |
360,697 | def _set_vlan_and_bd(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=vlan_and_bd.vlan_and_bd, is_container=, presence=False, yang_name="vlan-and-bd", rest_name="", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths... | Setter method for vlan_and_bd, mapped from YANG variable /overlay_gateway/map/vlan_and_bd (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_vlan_and_bd is considered as a private
method. Backends looking to populate this variable should
do so via calling thisOb... |
360,698 | def wrap_handler(cls, handler, protocol, **kwargs):
def _wrapper(request, *args, **kwargs):
instance = cls(request=request, **kwargs)
if protocol == Resource.Protocol.http:
return instance._wrap_http(handler, request=request, **kwargs)
elif protocol =... | Wrap a request handler with the matching protocol handler |
360,699 | def reduce_fit(interface, state, label, inp):
from disco.util import kvgroup
import numpy as np
out = interface.output(0)
fit_model = {"y_labels": [], "y_sum": 0, "iv": set()}
combiner = {}
means, variances = [], []
k_prev = ""
for key, value in kvgroup(inp):
... | Function separates aggregation of continuous and discrete features.
For continuous features it aggregates partially calculated means and variances and returns them. For discrete
features it aggregates pairs and returns them. Pairs with label occurrences are used to calculate prior probabilities |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.