Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
380,000 | def sepBy(p, sep):
return separated(p, sep, 0, maxt=float(), end=False) | `sepBy(p, sep)` parses zero or more occurrences of p, separated by `sep`.
Returns a list of values returned by `p`. |
380,001 | async def _download_predicate_data(self, class_, controller):
await self.authenticate()
url = (
.format(self.base_url, controller, class_))
resp = await self._ratelimited_get(url)
await _raise_for_status(resp)
resp_json = await resp.json()
retu... | Get raw predicate information for given request class, and cache for
subsequent calls. |
380,002 | def _transport_interceptor(self, callback):
def add_item_to_queue(header, message):
queue_item = (
Priority.TRANSPORT,
next(
self._transport_interceptor_counter
),
(callback, header, message),
... | Takes a callback function and returns a function that takes headers and
messages and places them on the main service queue. |
380,003 | def is_anagram(s, t):
maps = {}
mapt = {}
for i in s:
maps[i] = maps.get(i, 0) + 1
for i in t:
mapt[i] = mapt.get(i, 0) + 1
return maps == mapt | :type s: str
:type t: str
:rtype: bool |
380,004 | def v_from_i(resistance_shunt, resistance_series, nNsVth, current,
saturation_current, photocurrent, method=):
s responsibility to ensure that the arguments are all float64
and within the proper ranges.
Parameters
----------
resistance_shunt : numeric
Shunt resistance in ohms ... | Device voltage at the given device current for the single diode model.
Uses the single diode model (SDM) as described in, e.g.,
Jain and Kapoor 2004 [1].
The solution is per Eq 3 of [1] except when resistance_shunt=numpy.inf,
in which case the explict solution for voltage is used.
Ideal device pa... |
380,005 | def lookup(self, hostname):
matches = [
config
for config in self._config
if self._allowed(config["host"], hostname)
]
ret = SSHConfigDict()
for match in matches:
for key, value in match["config"].items():
if key n... | Return a dict (`SSHConfigDict`) of config options for a given hostname.
The host-matching rules of OpenSSH's ``ssh_config`` man page are used:
For each parameter, the first obtained value will be used. The
configuration files contain sections separated by ``Host``
specifications, and t... |
380,006 | def ccdmask(flat1, flat2=None, mask=None, lowercut=6.0, uppercut=6.0,
siglev=1.0, mode=, nmed=(7, 7), nsig=(15, 15)):
if flat2 is None:
flat1, flat2 = flat2, flat1
flat1 = numpy.ones_like(flat2)
if mask is None:
mask = numpy.zeros_like(flat1, dtype=)
... | Find cosmetic defects in a detector using two flat field images.
Two arrays representing flat fields of different exposure times are
required. Cosmetic defects are selected as points that deviate
significantly of the expected normal distribution of pixels in
the ratio between `flat2` and `flat1`. The m... |
380,007 | def delete_dashboard(self, id, **kwargs):
kwargs[] = True
if kwargs.get():
return self.delete_dashboard_with_http_info(id, **kwargs)
else:
(data) = self.delete_dashboard_with_http_info(id, **kwargs)
return data | Delete a specific dashboard # 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.delete_dashboard(id, async_req=True)
>>> result = thread.get()
:param asyn... |
380,008 | def remove_from_category(self, category):
ctype = ContentType.objects.get_for_model(self)
self.categories.model.objects.filter(category=category, content_type=ctype, object_id=self.id).delete() | Removes this object from a given category.
:param Category category:
:return: |
380,009 | def com_adobe_fonts_check_family_consistent_upm(ttFonts):
upm_set = set()
for ttFont in ttFonts:
upm_set.add(ttFont[].unitsPerEm)
if len(upm_set) > 1:
yield FAIL, ("Fonts have different units per em: {}."
).format(sorted(upm_set))
else:
yield PASS, "Font... | Fonts have consistent Units Per Em? |
380,010 | def pypi(
click_ctx,
requirements,
index=None,
python_version=3,
exclude_packages=None,
output=None,
subgraph_check_api=None,
no_transitive=True,
no_pretty=False,
):
requirements = [requirement.strip() for requirement in requirements.split("\\n") if requirement]
if not ... | Manipulate with dependency requirements using PyPI. |
380,011 | def verify_signature(self,
signing_key,
message,
signature,
padding_method,
signing_algorithm=None,
hashing_algorithm=None,
digital_signature_alg... | Verify a message signature.
Args:
signing_key (bytes): The bytes of the signing key to use for
signature verification. Required.
message (bytes): The bytes of the message that corresponds with
the signature. Required.
signature (bytes): The by... |
380,012 | def _setLearningMode(self, l4Learning = False, l2Learning=False):
for column in self.L4Columns:
column.setParameter("learn", 0, l4Learning)
for column in self.L2Columns:
column.setParameter("learningMode", 0, l2Learning) | Sets the learning mode for L4 and L2. |
380,013 | def format(self, status, headers, environ, bucket, delay):
entity = ("This request was rate-limited. "
"Please retry your request after %s." %
time.strftime("%Y-%m-%dT%H:%M:%SZ",
time.gmtime(bucket.next)))
h... | Formats a response entity. Returns a tuple of the desired
status code and the formatted entity. The default status code
is passed in, as is a dictionary of headers.
:param status: The default status code. Should be returned to
the caller, or an alternate selected. The... |
380,014 | def move(self, x, y):
if not isinstance(x, baseinteger):
raise TypeError("x can only be an instance of type baseinteger")
if not isinstance(y, baseinteger):
raise TypeError("y can only be an instance of type baseinteger")
self._call("move",
i... | Changes the overlay's position relative to the IFramebuffer.
in x of type int
in y of type int |
380,015 | def from_word2vec(fname, fvocab=None, binary=False):
vocabulary = None
if fvocab is not None:
logger.info("loading word counts from %s" % (fvocab))
vocabulary = Embedding.from_word2vec_vocab(fvocab)
logger.info("loading projection weights from %s" % (fname))
if binary:
words, vec... | Load the input-hidden weight matrix from the original C word2vec-tool format.
Note that the information stored in the file is incomplete (the binary tree is missing),
so while you can query for word similarity etc., you cannot continue training
with a model loaded this way.
`binary` is a boolean indic... |
380,016 | def append(self, item):
self.real_list.append(item)
self.observer(UpdateType.CREATED, item, len(self.real_list) - 1) | See :meth:`list.append()` method
Calls observer ``self.observer(UpdateType.CREATED, item, index)`` where
**index** is *item position* |
380,017 | def bilinear_sampling(input_layer, x, y, name=PROVIDED):
input_layer.get_shape().assert_has_rank(4)
return _interpolate(im=input_layer, x=x, y=y, name=name) | Performs bilinear sampling. This must be a rank 4 Tensor.
Implements the differentiable sampling mechanism with bilinear kernel
in https://arxiv.org/abs/1506.02025.
Given (x, y) coordinates for each output pixel, use bilinear sampling on
the input_layer to fill the output.
Args:
input_layer: The chaina... |
380,018 | def validate(self, instance, value):
try:
compval = complex(value)
if not self.cast and (
abs(value.real - compval.real) > TOL or
abs(value.imag - compval.imag) > TOL
):
self.error(
instance=... | Checks that value is a complex number
Floats and Integers are coerced to complex numbers |
380,019 | def stringify(self) :
"a pretty str version of getChain()"
l = []
h = self.head
while h :
l.append(str(h._key))
h = h.nextDoc
return "<->".join(l) | a pretty str version of getChain() |
380,020 | def parse_version(str_):
v = re.findall(r"\d+.\d+.\d+", str_)
if v:
return v[0]
else:
print("cannot parse string {}".format(str_))
raise KeyError | Parses the program's version from a python variable declaration. |
380,021 | def send_signal(self, backend, signal):
backend = self._expand_host(backend)
if backend in self.backends:
try:
return self._work(backend, self._package(signal), log=False)
except socket.error:
raise BackendNotAvailableError
else:
... | Sends the `signal` signal to `backend`. Raises ValueError if `backend`
is not registered with the client. Returns the result. |
380,022 | def wgs84togcj02(lng, lat):
if out_of_china(lng, lat):
return lng, lat
dlat = transformlat(lng - 105.0, lat - 35.0)
dlng = transformlng(lng - 105.0, lat - 35.0)
radlat = lat / 180.0 * pi
magic = math.sin(radlat)
magic = 1 - ee * magic * magic
sqrtmagic = math.sqrt(magic)
d... | WGS84转GCJ02(火星坐标系)
:param lng:WGS84坐标系的经度
:param lat:WGS84坐标系的纬度
:return: |
380,023 | def _get_imported_module(self, module_name):
imp_mod = self.by_name.get(module_name)
if imp_mod:
return imp_mod
no_obj = module_name.rsplit(, 1)[0]
imp_mod2 = self.by_name.get(no_obj)
if imp_mod2:
return imp_mod2
... | try to get imported module reference by its name |
380,024 | def isect(list1, list2):
r
set2 = set(list2)
return [item for item in list1 if item in set2] | r"""
returns list1 elements that are also in list2. preserves order of list1
intersect_ordered
Args:
list1 (list):
list2 (list):
Returns:
list: new_list
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list1 = ['featweig... |
380,025 | def start(self):
self._context.add_service_listener(
self, self.requirement.filter, self.requirement.specification
) | Starts the dependency manager |
380,026 | def getDelOps(self, buid):
return (
(, (buid, self.form.name, self.name, self.storinfo)),
) | Get a list of storage operations to delete this property from the buid.
Args:
buid (bytes): The node buid.
Returns:
(tuple): The storage operations |
380,027 | def from_css(Class, csstext, encoding=None, href=None, media=None, title=None, validate=None):
styles = Class()
cssStyleSheet = cssutils.parseString(csstext, encoding=encoding, href=href, media=media, title=title, validate=validate)
for rule in cssStyleSheet.cssRules:
if rul... | parse CSS text into a Styles object, using cssutils |
380,028 | def blob_handler(self, cmd):
self.blobs[cmd.id] = cmd
self.keep = False | Process a BlobCommand. |
380,029 | def _algebraic_rules_scalar():
a = wc("a", head=SCALAR_VAL_TYPES)
b = wc("b", head=SCALAR_VAL_TYPES)
x = wc("x", head=SCALAR_TYPES)
y = wc("y", head=SCALAR_TYPES)
z = wc("z", head=SCALAR_TYPES)
indranges__ = wc("indranges__", head=IndexRangeBase)
ScalarTimes._binary_rules.update(check... | Set the default algebraic rules for scalars |
380,030 | def _unique_ordered_lines(line_numbers):
if len(line_numbers) == 0:
return []
line_set = set(line_numbers)
return sorted([line for line in line_set]) | Given a list of line numbers, return a list in which each line
number is included once and the lines are ordered sequentially. |
380,031 | def question_detail(request, topic_slug, slug):
url = reverse(, kwargs={: topic_slug})
return _fragmentify(Question, slug, url) | A detail view of a Question.
Simply redirects to a detail page for the related :model:`faq.Topic`
(:view:`faq.views.topic_detail`) with the addition of a fragment
identifier that links to the given :model:`faq.Question`.
E.g. ``/faq/topic-slug/#question-slug``. |
380,032 | def _to_dict(self):
_dict = {}
if hasattr(self, ) and self.text is not None:
_dict[] = self.text
return _dict | Return a json dictionary representing this model. |
380,033 | def invert_pixel_mask(mask):
inverted_mask = np.ones(shape=(80, 336), dtype=np.dtype())
inverted_mask[mask >= 1] = 0
return inverted_mask | Invert pixel mask (0->1, 1(and greater)->0).
Parameters
----------
mask : array-like
Mask.
Returns
-------
inverted_mask : array-like
Inverted Mask. |
380,034 | def _validate_arguments(self):
if self._has_terms():
[term._validate_arguments() for term in self._terms]
return self | method to sanitize model parameters
Parameters
---------
None
Returns
-------
None |
380,035 | def random_sleep(self, previous_attempt_number, delay_since_first_attempt_ms):
return random.randint(self._wait_random_min, self._wait_random_max) | Sleep a random amount of time between wait_random_min and wait_random_max |
380,036 | def safe_read_file(file_path: Path) -> str:
for encoding in FILE_ENCODINGS:
try:
return file_path.read_text(encoding=encoding)
except UnicodeError:
pass
raise GuesslangError(.format(file_path)) | Read a text file. Several text encodings are tried until
the file content is correctly decoded.
:raise GuesslangError: when the file encoding is not supported
:param file_path: path to the input file
:return: text file content |
380,037 | def get_fermi(self, c, T, rtol=0.01, nstep=50, step=0.1, precision=8):
fermi = self.efermi
for _ in range(precision):
frange = np.arange(-nstep, nstep + 1) * step + fermi
calc_doping = np.array([self.get_doping(f, T) for f in frange])
relative_error = abs(c... | Finds the fermi level at which the doping concentration at the given
temperature (T) is equal to c. A greedy algorithm is used where the
relative error is minimized by calculating the doping at a grid which
is continuously become finer.
Args:
c (float): doping concentration.... |
380,038 | def stl(A, b):
r
from scipy.linalg import solve_triangular
A = asarray(A, float)
b = asarray(b, float)
return solve_triangular(A, b, lower=True, check_finite=False) | r"""Shortcut to ``solve_triangular(A, b, lower=True, check_finite=False)``.
Solve linear systems :math:`\mathrm A \mathbf x = \mathbf b` when
:math:`\mathrm A` is a lower-triangular matrix.
Args:
A (array_like): A lower-triangular matrix.
b (array_like): Ordinate values.
Returns:
... |
380,039 | def GetHostMemUsedMB(self):
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetHostMemUsedMB(self.handle.value, byref(counter))
if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
return counter.value | Undocumented. |
380,040 | def get_table_info(conn, tablename):
r = conn.execute("pragma table_info()".format(tablename))
ret = TableInfo(((row["name"], row) for row in r))
return ret | Returns TableInfo object |
380,041 | def wait_for_element_not_present(self, locator):
for i in range(timeout_seconds):
if self.driver.is_element_present(locator):
time.sleep(1)
else:
break
else:
raise ElementVisiblityTimeout("%s presence timed out" % locator)
... | Synchronization helper to wait until some element is removed from the page
:raises: ElementVisiblityTimeout |
380,042 | def autoset_id(self):
try:
self.id_
except AttributeError:
pass
else:
if self.id_:
return
self.id_ = to_nmtoken(random.getrandbits(8*RANDOM_ID_BYTES)) | If the :attr:`id_` already has a non-false (false is also the empty
string!) value, this method is a no-op.
Otherwise, the :attr:`id_` attribute is filled with
:data:`RANDOM_ID_BYTES` of random data, encoded by
:func:`aioxmpp.utils.to_nmtoken`.
.. note::
This method... |
380,043 | def ip2long(ip):
if not validate_ip(ip):
return None
quads = ip.split()
if len(quads) == 1:
quads = quads + [0, 0, 0]
elif len(quads) < 4:
host = quads[-1:]
quads = quads[:-1] + [0, ] * (4 - len(quads)) + host
lngip = 0
for q in quads:
... | Convert a dotted-quad ip address to a network byte order 32-bit
integer.
>>> ip2long('127.0.0.1')
2130706433
>>> ip2long('127.1')
2130706433
>>> ip2long('127')
2130706432
>>> ip2long('127.0.0.256') is None
True
:param ip: Dotted-quad ip address (eg. '127.0.0.1').
:type ip... |
380,044 | def generate(self):
answer = self.rand.randrange(self.max)
answer = str(answer).zfill(self.digits)
image_data = self.image_generator.generate(answer)
base64_captcha = base64.b64encode(image_data.getvalue()).decode("ascii")
logging.debug( + answer)... | Generates and returns a numeric captcha image in base64 format.
Saves the correct answer in `session['captcha_answer']`
Use later as:
src = captcha.generate()
<img src="{{src}}"> |
380,045 | def populate(self, priority, address, rtr, data):
assert isinstance(data, bytes)
self.needs_no_rtr(rtr)
self.needs_data(data, 7)
self.set_attributes(priority, address, rtr)
self.channel = (data[0] & 0x03) +1
self.pulses = (data[0] >> 2) * 100
self.counte... | -DB1 last 2 bits = channel
-DB1 first 6 bist = pulses
-DB2-5 = pulse counter
-DB6-7 = ms/pulse
:return: None |
380,046 | def apply_classifier(self, name, samples=None, subset=None):
if samples is not None:
subset = self.make_subset(samples)
samples = self._get_samples(subset)
c = self.classifiers[name]
labs = c.classifier.ulabels_
with self.pbar.set(total=len(samples), desc=... | Apply a clustering classifier based on all samples, or a subset.
Parameters
----------
name : str
The name of the classifier to apply.
subset : str
The subset of samples to apply the classifier to.
Returns
-------
name : str |
380,047 | def plot_ranges_from_cli(opts):
mins = {}
for x in opts.mins:
x = x.split()
if len(x) != 2:
raise ValueError("option --mins not specified correctly; see help")
mins[x[0]] = float(x[1])
maxs = {}
for x in opts.maxs:
x = x.split()
if len(x) != 2:
... | Parses the mins and maxs arguments from the `plot_posterior` option
group.
Parameters
----------
opts : ArgumentParser
The parsed arguments from the command line.
Returns
-------
mins : dict
Dictionary of parameter name -> specified mins. Only parameters that
were s... |
380,048 | def dist_iter(self, g_nums, ats_1, ats_2, invalid_error=False):
import numpy as np
from .utils import pack_tups
if _DEBUG:
print("g_nums = {0}".format(g_nums))
print("ats_1 = {0}".format(ats_1))
print("ats_2 = {0}".format(ats_2))... | Iterator over selected interatomic distances.
Distances are in Bohrs as with :meth:`dist_single`.
See `above <toc-generators_>`_ for more information on
calling options.
Parameters
----------
g_nums
|int| or length-R iterable |int| or |None| --
... |
380,049 | def add_contact(self, phone_number: str, first_name: str, last_name: str=None, on_success: callable=None):
pass | Add contact by phone number and name (last_name is optional).
:param phone: Valid phone number for contact.
:param first_name: First name to use.
:param last_name: Last name to use. Optional.
:param on_success: Callback to call when adding, will contain success status and the current con... |
380,050 | def monthly_mean_at_each_ind(monthly_means, sub_monthly_timeseries):
time = monthly_means[TIME_STR]
start = time.indexes[TIME_STR][0].replace(day=1, hour=0)
end = time.indexes[TIME_STR][-1]
new_indices = pd.DatetimeIndex(start=start, end=end, freq=)
arr_new = monthly_means.reindex(time=new_indi... | Copy monthly mean over each time index in that month.
Parameters
----------
monthly_means : xarray.DataArray
array of monthly means
sub_monthly_timeseries : xarray.DataArray
array of a timeseries at sub-monthly time resolution
Returns
-------
xarray.DataArray with eath mont... |
380,051 | def matlab_compatible(name):
compatible_name = [ch if ch in ALLOWED_MATLAB_CHARS else "_" for ch in name]
compatible_name = "".join(compatible_name)
if compatible_name[0] not in string.ascii_letters:
compatible_name = "M_" + compatible_name
return compatible_name[:60] | make a channel name compatible with Matlab variable naming
Parameters
----------
name : str
channel name
Returns
-------
compatible_name : str
channel name compatible with Matlab |
380,052 | def get_mcu_definition(self, project_file):
return mcu | Parse project file to get mcu definition |
380,053 | def _get_f2rx(self, C, r_x, r_1, r_2):
drx = (r_x - r_1) / (r_2 - r_1)
return self.CONSTS["h4"] + (C["h5"] * drx) + (C["h6"] * (drx ** 2.)) | Defines the f2 scaling coefficient defined in equation 10 |
380,054 | def warn_on_var_indirection(self) -> bool:
return not self.use_var_indirection and self._opts.entry(
WARN_ON_VAR_INDIRECTION, True
) | If True, warn when a Var reference cannot be direct linked (iff
use_var_indirection is False).. |
380,055 | def _handleCallInitiated(self, regexMatch, callId=None, callType=1):
if self._dialEvent:
if regexMatch:
groups = regexMatch.groups()
if len(groups) >= 2:
self._dialResponse = (int(groups[0]) , int(groups[1]))
... | Handler for "outgoing call initiated" event notification line |
380,056 | def process_raw_data(cls, raw_data):
properties = raw_data["properties"]
raw_content = properties.get("addressSpace", None)
if raw_content is not None:
address_space = AddressSpace.from_raw_data(raw_content)
properties["addressSpace"] = address_space
ra... | Create a new model using raw API response. |
380,057 | def _trade(self, security, price=0, amount=0, volume=0, entrust_bs="buy"):
stock = self._search_stock_info(security)
balance = self.get_balance()[0]
if stock is None:
raise exceptions.TradeError(u"没有查询要操作的股票信息")
if not volume:
volume = int(float(price) * ... | 调仓
:param security:
:param price:
:param amount:
:param volume:
:param entrust_bs:
:return: |
380,058 | def configure(cls, name, config, prefix=):
if name in cls._depots:
raise RuntimeError( % (name,))
if cls._default_depot is None:
cls._default_depot = name
cls._depots[name] = cls.from_config(config, prefix)
return cls._depots[name] | Configures an application depot.
This configures the application wide depot from a settings dictionary.
The settings dictionary is usually loaded from an application configuration
file where all the depot options are specified with a given ``prefix``.
The default ``prefix`` is *depot.*... |
380,059 | def decrypt(self, data):
next_payload, is_critical, payload_len = const.PAYLOAD_HEADER.unpack(data[:const.PAYLOAD_HEADER.size])
next_payload = payloads.Type(next_payload)
logger.debug("next payload: {!r}".format(next_payload))
try:
iv_len = 16
iv = bytes(... | Decrypts an encrypted (SK, 46) IKE payload using self.SK_er
:param data: Encrypted IKE payload including headers (payloads.SK())
:return: next_payload, data_containing_payloads
:raise IkeError: If packet is corrupted. |
380,060 | def _get_options(ret=None):
defaults = {: ,
: ,
: ,
: ,
: 3306,
: None,
: None,
: None}
attrs = {: ,
: ,
: ,
: ,
: ,
: ,
... | Returns options used for the MySQL connection. |
380,061 | def setClockShowDate(kvalue, **kwargs):
*
if kvalue is not True and kvalue is not False:
return False
_gsession = _GSettings(user=kwargs.get(),
schema=,
key=)
return _gsession._set(kvalue) | Set whether the date is visible in the clock
CLI Example:
.. code-block:: bash
salt '*' gnome.setClockShowDate <True|False> user=<username> |
380,062 | async def clear(self, using_db=None) -> None:
db = using_db if using_db else self.model._meta.db
through_table = Table(self.field.through)
query = (
db.query_class.from_(through_table)
.where(getattr(through_table, self.field.backward_key) == self.instance.id)
... | Clears ALL relations. |
380,063 | def _getArrays(items, attr, defaultValue):
arrays = dict([(key, []) for key in attr])
for item in items:
for key in attr:
arrays[key].append(getattr(item, key, defaultValue))
for key in [_ for _ in viewkeys(arrays)]:
arrays[key] = numpy.array(arrays[key])
return arrays | Return arrays with equal size of item attributes from a list of sorted
"items" for fast and convenient data processing.
:param attr: list of item attributes that should be added to the returned
array.
:param defaultValue: if an item is missing an attribute, the "defaultValue"
is added to th... |
380,064 | def merge_leaderboards(self, destination, keys, aggregate=):
keys.insert(0, self.leaderboard_name)
self.redis_connection.zunionstore(destination, keys, aggregate) | Merge leaderboards given by keys with this leaderboard into a named destination leaderboard.
@param destination [String] Destination leaderboard name.
@param keys [Array] Leaderboards to be merged with the current leaderboard.
@param options [Hash] Options for merging the leaderboards. |
380,065 | def load_cml(cml_filename):
parser = make_parser()
parser.setFeature(feature_namespaces, 0)
dh = CMLMoleculeLoader()
parser.setContentHandler(dh)
parser.parse(cml_filename)
return dh.molecules | Load the molecules from a CML file
Argument:
| ``cml_filename`` -- The filename of a CML file.
Returns a list of molecule objects with optional molecular graph
attribute and extra attributes. |
380,066 | def set_uid(self):
if self.user:
uid = getpwnam(self.user).pw_uid
try:
os.setuid(uid)
except Exception:
message = ( +
)
print(message.format(self.user, self.group))
sys.exit(1) | Change the user of the running process |
380,067 | def options(self, **options):
for k in options:
self._jreader = self._jreader.option(k, to_str(options[k]))
return self | Adds input options for the underlying data source.
You can set the following option(s) for reading files:
* ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps
in the JSON/CSV datasources or partition values.
If it isn't set, it use... |
380,068 | def copy(self, filename, id_=-1, pre_callback=None, post_callback=None):
for repo in self._children:
if is_package(filename):
copy_method = repo.copy_pkg
else:
copy_method = repo.copy_script
if pre_callback:
... | Copy a package or script to all repos.
Determines appropriate location (for file shares) and type based
on file extension.
Args:
filename: String path to the local file to copy.
id_: Package or Script object ID to target. For use with JDS
and CDP DP's on... |
380,069 | def authenticate(cmd_args, endpoint=, force=False):
server = server_url(cmd_args)
network.check_ssl()
access_token = None
try:
assert not force
access_token = refresh_local_token(server)
except Exception:
print()
access_token = perform_oauth(get_code, cmd_args, ... | Returns an OAuth token that can be passed to the server for
identification. If FORCE is False, it will attempt to use a cached token
or refresh the OAuth token. |
380,070 | def gps_0(self):
return GPSInfo(self._eph, self._epv, self._fix_type, self._satellites_visible) | GPS position information (:py:class:`GPSInfo`). |
380,071 | def _next_dir_gen(self, root):
for e in root.getiterator(common._T_COMMON_PREFIXES):
yield common.GCSFileStat(
self._path + + e.find(common._T_PREFIX).text,
st_size=None, etag=None, st_ctime=None, is_dir=True)
e.clear()
yield None | Generator for next directory element in the document.
Args:
root: root element in the XML tree.
Yields:
GCSFileStat for the next directory. |
380,072 | def cell(self, row_idx, col_idx):
return _Cell(self._tbl.tc(row_idx, col_idx), self) | Return cell at *row_idx*, *col_idx*.
Return value is an instance of |_Cell|. *row_idx* and *col_idx* are
zero-based, e.g. cell(0, 0) is the top, left cell in the table. |
380,073 | def individuals(self, ind_ids=None):
if ind_ids:
for ind_id in ind_ids:
for ind in self.individual_objs:
if ind.ind_id == ind_id:
yield ind
else:
for ind in self.individual_objs:
yield ind | Return information about individuals
Args:
ind_ids (list(str)): List of individual ids
Returns:
individuals (Iterable): Iterable with Individuals |
380,074 | def write(self, handle):
if not self._frames:
return
def add(name, desc, bpe, format, bytes, *dimensions):
group.add_param(name,
desc=desc,
bytes_per_element=bpe,
bytes=struct.pack(forma... | Write metadata and point + analog frames to a file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle. |
380,075 | def run(**options):
with Dotfile(options) as conf:
if conf[] is None:
msg = "No context file has been provided"
LOGGER.error(msg)
raise RuntimeError(msg)
if not os.path.exists(conf[]):
msg = "Context file {} not found".format(conf[])
L... | _run_
Run the dockerstache process to render templates
based on the options provided
If extend_context is passed as options it will be used to
extend the context with the contents of the dictionary provided
via context.update(extend_context) |
380,076 | async def get_status(self, filters=None, utc=False):
client_facade = client.ClientFacade.from_connection(self.connection())
return await client_facade.FullStatus(filters) | Return the status of the model.
:param str filters: Optional list of applications, units, or machines
to include, which can use wildcards ('*').
:param bool utc: Display time as UTC in RFC3339 format |
380,077 | def pad_shape_right_with_ones(x, ndims):
if not (isinstance(ndims, int) and ndims >= 0):
raise ValueError(
.format(ndims))
if ndims == 0:
return x
x = tf.convert_to_tensor(value=x)
original_shape = x.shape
new_shape = distribution_util.pad(
tf.shape(input=x), axis=0, back=Tru... | Maybe add `ndims` ones to `x.shape` on the right.
If `ndims` is zero, this is a no-op; otherwise, we will create and return a
new `Tensor` whose shape is that of `x` with `ndims` ones concatenated on the
right side. If the shape of `x` is known statically, the shape of the return
value will be as well.
Args... |
380,078 | def get(self, sid):
return CredentialListContext(self._version, account_sid=self._solution[], sid=sid, ) | Constructs a CredentialListContext
:param sid: Fetch by unique credential list Sid
:returns: twilio.rest.api.v2010.account.sip.credential_list.CredentialListContext
:rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListContext |
380,079 | def fields2jsonschema(self, fields, schema=None, use_refs=True, dump=True, name=None):
Meta = getattr(schema, , None)
if getattr(Meta, , None):
declared_fields = set(schema._declared_fields.keys())
if set(getattr(Meta, , set())) > declared_fields:
import ... | Return the JSON Schema Object for a given marshmallow
:class:`Schema <marshmallow.Schema>`. Schema may optionally provide the ``title`` and
``description`` class Meta options.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject
Example: ::
... |
380,080 | def parser():
query_parser = current_app.config[]
if isinstance(query_parser, six.string_types):
query_parser = import_string(query_parser)
return query_parser | Return search query parser. |
380,081 | def _really_start_hb(self):
if self._beating and not self.hb_stream.closed():
self._hb_periodic_callback.start() | callback for delayed heartbeat start
Only start the hb loop if we haven't been closed during the wait. |
380,082 | def find_permission_view_menu(self, permission_name, view_menu_name):
permission = self.find_permission(permission_name)
view_menu = self.find_view_menu(view_menu_name)
if permission and view_menu:
return self.permissionview_model.objects(
permission=permissi... | Finds and returns a PermissionView by names |
380,083 | def format(self, exclude_class=False):
if exclude_class:
msg = self.msg
else:
msg = "%s: %s" % (self.__class__.__name__, self.msg)
if len(self.params) != 0:
paramstring = "\n".join([str(key) + ": " + str(val) for key, val in self.params.items()])
... | Format this exception as a string including class name.
Args:
exclude_class (bool): Whether to exclude the exception class
name when formatting this exception
Returns:
string: a multiline string with the message, class name and
key value paramete... |
380,084 | def _load_data(self, group, record_offset=0, record_count=None):
has_yielded = False
offset = 0
_count = record_count
channel_group = group.channel_group
if group.data_location == v23c.LOCATION_ORIGINAL_FILE:
stream = self._file
else:
... | get group's data block bytes |
380,085 | def detect_phantomjs(version=):
if settings.phantomjs_path() is not None:
phantomjs_path = settings.phantomjs_path()
else:
if hasattr(shutil, "which"):
phantomjs_path = shutil.which("phantomjs") or "phantomjs"
else:
phantomjs_path = "phantomjs"
... | Detect if PhantomJS is avaiable in PATH, at a minimum version.
Args:
version (str, optional) :
Required minimum version for PhantomJS (mostly for testing)
Returns:
str, path to PhantomJS |
380,086 | def variable_map_items(variable_map):
for key, var_or_vars in six.iteritems(variable_map):
if isinstance(var_or_vars, (list, tuple)):
for variable in var_or_vars:
yield key, variable
else:
yield key, var_or_vars | Yields an iterator over (string, variable) pairs in the variable map.
In general, variable maps map variable names to either a `tf.Variable`, or
list of `tf.Variable`s (in case of sliced variables).
Args:
variable_map: dict, variable map over which to iterate.
Yields:
(string, tf.Variable) pairs. |
380,087 | def _add_mac_token(self, uri, http_method=, body=None,
headers=None, token_placement=AUTH_HEADER, ext=None, **kwargs):
if token_placement != AUTH_HEADER:
raise ValueError("Invalid token placement.")
headers = tokens.prepare_mac_header(self.access_token, uri,
... | Add a MAC token to the request authorization header.
Warning: MAC token support is experimental as the spec is not yet stable. |
380,088 | def do_one_iteration(self):
if self.control_stream:
self.control_stream.flush()
for stream in self.shell_streams:
stream.flush(zmq.POLLIN, 1)
stream.flush(zmq.POLLOUT) | step eventloop just once |
380,089 | def list_installed():
*
result = __salt__[](_package_name(), versions_as_list=True)
if result is None:
return []
if six.PY2:
return sorted(result, cmp=_cmp_version)
else:
return sorted(result, key=functools.cmp_to_key(_cmp_version)) | Return a list of all installed kernels.
CLI Example:
.. code-block:: bash
salt '*' kernelpkg.list_installed |
380,090 | def check_cv(cv=3, y=None, classifier=False):
if cv is None:
cv = 3
if not is_dask_collection(y) or not isinstance(cv, numbers.Integral):
return model_selection.check_cv(cv, y, classifier)
if classifier:
target_type = delayed(type_of_target, pure=True)(y).co... | Dask aware version of ``sklearn.model_selection.check_cv``
Same as the scikit-learn version, but works if ``y`` is a dask object. |
380,091 | def is_period_arraylike(arr):
if isinstance(arr, (ABCPeriodIndex, ABCPeriodArray)):
return True
elif isinstance(arr, (np.ndarray, ABCSeries)):
return is_period_dtype(arr.dtype)
return getattr(arr, , None) == | Check whether an array-like is a periodical array-like or PeriodIndex.
Parameters
----------
arr : array-like
The array-like to check.
Returns
-------
boolean
Whether or not the array-like is a periodical array-like or
PeriodIndex instance.
Examples
--------
... |
380,092 | def identify_protocol(method, value):
for protocol_name in PROTOCOLS:
protocol = importlib.import_module(f"federation.protocols.{protocol_name}.protocol")
if getattr(protocol, f"identify_{method}")(value):
return protocol
else:
raise NoSuitableProtocolFoundError() | Loop through protocols, import the protocol module and try to identify the id or request. |
380,093 | def blackbox_and_coarse_grain(blackbox, coarse_grain):
if blackbox is None:
return
for box in blackbox.partition:
outputs = set(box) & set(blackbox.output_indices)
if coarse_grain is None and len(outputs) > 1:
raise ValueError(
... | Validate that a coarse-graining properly combines the outputs of a
blackboxing. |
380,094 | def _handle_utf8_payload(body, properties):
if not in properties:
properties[] =
encoding = properties[]
if compatibility.is_unicode(body):
body = body.encode(encoding)
elif compatibility.PYTHON3 and isinstance(body, str):
body = bytes(body,... | Update the Body and Properties to the appropriate encoding.
:param bytes|str|unicode body: Message payload
:param dict properties: Message properties
:return: |
380,095 | def schur_complement(mat, row, col):
a = mat[:row, :col]
b = mat[:row, col:]
c = mat[row:, :col]
d = mat[row:, col:]
return a - b.dot(d.I).dot(c) | compute the schur complement of the matrix block mat[row:,col:] of the matrix mat |
380,096 | def append_op(self, operation):
if operation not in self.ops:
self.ops.append(operation)
return self | Append an :class:`Operation <stellar_base.operation.Operation>` to
the list of operations.
Add the operation specified if it doesn't already exist in the list of
operations of this :class:`Builder` instance.
:param operation: The operation to append to the list of operations.
:... |
380,097 | def count_names_by_namespace(graph, namespace):
if namespace not in graph.defined_namespace_keywords:
raise IndexError(.format(namespace, graph))
return Counter(_namespace_filtered_iterator(graph, namespace)) | Get the set of all of the names in a given namespace that are in the graph.
:param pybel.BELGraph graph: A BEL graph
:param str namespace: A namespace keyword
:return: A counter from {name: frequency}
:rtype: collections.Counter
:raises IndexError: if the namespace is not defined in the graph. |
380,098 | def deleteThreads(self, thread_ids):
thread_ids = require_list(thread_ids)
data_unpin = dict()
data_delete = dict()
for i, thread_id in enumerate(thread_ids):
data_unpin["ids[{}]".format(thread_id)] = "false"
data_delete["ids[{}]".format(i)] = thread_id
... | Deletes threads
:param thread_ids: Thread IDs to delete. See :ref:`intro_threads`
:return: Whether the request was successful
:raises: FBchatException if request failed |
380,099 | def logout(self):
response = None
try:
response = requests.delete(
urls.login(),
headers={
: .format(self._vid)})
except requests.exceptions.RequestException as ex:
raise RequestError(ex)
_validate_respo... | Logout and remove vid |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.