code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|
def begin_transaction(
self,
database,
options_=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
if "begin_transaction" not in self._inner_api_calls:
self._inn... | Starts a new transaction.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> database = client.database_root_path('[PROJECT]', '[DATABASE]')
>>>
>>> response = c... |
def cursor(self, pos):
row = self.indexAt(pos).row()
if row == -1:
row = self.model().rowCount()
row_height = self.rowHeight(0)
y = row_height*row
x = self.width()
return QtCore.QLine(0,y,x,y) | Returns a line at the nearest row split between tests.
Re-implemented from :meth:`AbstractDragView<sparkle.gui.abstract_drag_view.AbstractDragView.cursor>` |
def split(table, field, pattern, newfields=None, include_original=False,
maxsplit=0, flags=0):
return SplitView(table, field, pattern, newfields, include_original,
maxsplit, flags) | Add one or more new fields with values generated by splitting an
existing value around occurrences of a regular expression. E.g.::
>>> import petl as etl
>>> table1 = [['id', 'variable', 'value'],
... ['1', 'parad1', '12'],
... ['2', 'parad2', '15'],
... ... |
def loadInputs(self, fname):
inputsfname = os.path.join(systools.get_appdir(), fname)
try:
with open(inputsfname, ) as jf:
inputsdict = json.load(jf)
except:
logger = logging.getLogger()
logger.warning("Unable to load app data from fil... | Load previsouly saved input values, and load them to GUI widgets
:param fname: file path where stashed input values are stored
:type fname: str |
def index(self, value):
for idx, val in enumerate(self):
if value == val:
return idx
raise ValueError(.format(value)) | Return index of *value* in self.
Raises ValueError if *value* is not found. |
def _format_date(self, obj) -> str:
if obj is None:
return
if isinstance(obj, datetime):
obj = obj.date()
return date_format(obj, ) | Short date format.
:param obj: date or datetime or None
:return: str |
def get_hash(self):
if self.__index_hash:
return self.__index_hash
key = self.request.method
key += URLHelper.get_protocol(self.request.url)
key += URLHelper.get_subdomain(self.request.url)
key += URLHelper.get_hostname(self.request.url)
key += URL... | Generate and return the dict index hash of the given queue item.
Note:
Cookies should not be included in the hash calculation because
otherwise requests are crawled multiple times with e.g. different
session keys, causing infinite crawling recursion.
Note:
... |
def worker_unreject(self, chosen_hit, assignment_ids = None):
if chosen_hit:
workers = self.amt_services.get_workers("Rejected")
assignment_ids = [worker[] for worker in workers if \
worker[] == chosen_hit]
for assignment_id in assignment_id... | Unreject worker |
def map_masked_1d_array_to_2d_array_from_array_1d_shape_and_one_to_two(array_1d, shape, one_to_two):
array_2d = np.zeros(shape)
for index in range(len(one_to_two)):
array_2d[one_to_two[index, 0], one_to_two[index, 1]] = array_1d[index]
return array_2d | For a 1D array that was computed by mapping unmasked values from a 2D array of shape (rows, columns), map its \
values back to the original 2D array where masked values are set to zero.
This uses a 1D array 'one_to_two' where each index gives the 2D pixel indexes of the 1D array's unmasked pixels, \
for ex... |
def check_token(token):
user = models.User.objects(api_key=token).first()
return user or None | Verify http header token authentification |
def groupby(iterable, key=0, filter=None):
if isinstance(key, (basestring, int)):
key = itemgetter(key)
elif isinstance(key, (tuple, list)):
key = itemgetter(*key)
for label, grp in igroupby(iterable, key):
yield label, list(grp) | wrapper to itertools.groupby that returns a list of each group, rather
than a generator and accepts integers or strings as the key and
automatically converts them to callables with itemgetter(key)
Arguments:
iterable: iterable
key: string, int or callable that tells how to group
Return... |
def on_disconnect(self=None) -> callable:
def decorator(func: callable) -> Handler:
handler = pyrogram.DisconnectHandler(func)
if self is not None:
self.add_handler(handler)
return handler
return decorator | Use this decorator to automatically register a function for handling disconnections.
This does the same thing as :meth:`add_handler` using the :class:`DisconnectHandler`. |
def com_google_fonts_check_metadata_valid_copyright(font_metadata):
import re
string = font_metadata.copyright
does_match = re.search(r,
string)
if does_match:
yield PASS, "METADATA.pb copyright string is good"
else:
yield FAIL, ("METADATA.pb: Copyright notices should mat... | Copyright notices match canonical pattern in METADATA.pb |
def remote_run(cmd, instance_name, detach=False, retries=1):
if detach:
cmd = SCREEN.format(command=cmd)
args = SSH.format(instance_name=instance_name).split()
args.append(cmd)
for i in range(retries + 1):
try:
if i > 0:
tf.logging.info("Retry %d for %s", i, args)
return sp.check_... | Run command on GCS instance, optionally detached. |
def popitem(self):
with self.__timer as time:
self.expire(time)
try:
key = next(iter(self.__links))
except StopIteration:
raise KeyError( % self.__class__.__name__)
else:
return (key, self.pop(key)) | Remove and return the `(key, value)` pair least recently used that
has not already expired. |
def check_resume(args: argparse.Namespace, output_folder: str) -> bool:
resume_training = False
training_state_dir = os.path.join(output_folder, C.TRAINING_STATE_DIRNAME)
if os.path.exists(output_folder):
if args.overwrite_output:
logger.info("Removing existing output folder %s.", o... | Check if we should resume a broken training run.
:param args: Arguments as returned by argparse.
:param output_folder: Main output folder for the model.
:return: Flag signaling if we are resuming training and the directory with
the training status. |
def format_map(self, format_string, mapping):
return self.vformat(format_string, args=None, kwargs=mapping) | format a string by a map
Args:
format_string(str): A format string
mapping(dict): A map to format the string
Returns:
A formatted string.
Raises:
KeyError: if key is not provided by the given map. |
def slices(self):
if self.chunks is None:
yield tuple(slice(None, s) for s in self.shape)
else:
ceilings = tuple(-(-s // c) for s, c in zip(self.shape, self.chunks))
for idx in np.ndindex(ceilings):
out = []
for i, c, s in zi... | Returns a generator yielding tuple of slice objects.
Order is not guaranteed. |
def _radial_profile(autocorr, r_max, nbins=100):
r
if len(autocorr.shape) == 2:
adj = sp.reshape(autocorr.shape, [2, 1, 1])
inds = sp.indices(autocorr.shape) - adj/2
dt = sp.sqrt(inds[0]**2 + inds[1]**2)
elif len(autocorr.shape) == 3:
adj = sp.reshape(autocorr.shape, [3, 1, 1... | r"""
Helper functions to calculate the radial profile of the autocorrelation
Masks the image in radial segments from the center and averages the values
The distance values are normalized and 100 bins are used as default.
Parameters
----------
autocorr : ND-array
The image of autocorrela... |
def _sumDiceRolls(self, rollList):
if isinstance(rollList, RollList):
self.rolls.append(rollList)
return rollList.sum()
else:
return rollList | convert from dice roll structure to a single integer result |
def setType(self, polygonID, polygonType):
self._connection._beginMessage(
tc.CMD_SET_POLYGON_VARIABLE, tc.VAR_TYPE, polygonID, 1 + 4 + len(polygonType))
self._connection._packString(polygonType)
self._connection._sendExact() | setType(string, string) -> None
Sets the (abstract) type of the polygon. |
def pixel_to_utm(row, column, transform):
east = transform[0] + column * transform[1]
north = transform[3] + row * transform[5]
return east, north | Convert pixel coordinate to UTM coordinate given a transform
:param row: row pixel coordinate
:type row: int or float
:param column: column pixel coordinate
:type column: int or float
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
... |
def get_mipmap_pixel(
self, left: float, top: float, right: float, bottom: float
) -> Tuple[int, int, int]:
color = lib.TCOD_image_get_mipmap_pixel(
self.image_c, left, top, right, bottom
)
return (color.r, color.g, color.b) | Get the average color of a rectangle in this Image.
Parameters should stay within the following limits:
* 0 <= left < right < Image.width
* 0 <= top < bottom < Image.height
Args:
left (float): Left corner of the region.
top (float): Top corner of the region.
... |
def get_query_results(self, query_execution_id):
query_state = self.check_query_status(query_execution_id)
if query_state is None:
self.log.error()
return None
elif query_state in self.INTERMEDIATE_STATES or query_state in self.FAILURE_STATES:
self.lo... | Fetch submitted athena query results. returns none if query is in intermediate state or
failed/cancelled state else dict of query output
:param query_execution_id: Id of submitted athena query
:type query_execution_id: str
:return: dict |
def get_debug_info():
from . import __version__
from .parser import SPEC_VERSION
d = OrderedDict()
d[] = % __version__
d[] = SPEC_VERSION
return d | Return a list of lines with backend info. |
def update_list_positions_obj(client, positions_obj_id, revision, values):
return _update_positions_obj(client, client.api.Endpoints.LIST_POSITIONS, positions_obj_id, revision, values) | Updates the ordering of lists to have the given value. The given ID and revision should match the singleton object defining how lists are laid out.
See https://developer.wunderlist.com/documentation/endpoints/positions for more info
Return:
The updated ListPositionsObj-mapped object defining the order of ... |
def get_cpuid_leaf_by_ordinal(self, ordinal):
if not isinstance(ordinal, baseinteger):
raise TypeError("ordinal can only be an instance of type baseinteger")
(idx, idx_sub, val_eax, val_ebx, val_ecx, val_edx) = self._call("getCPUIDLeafByOrdinal",
in_p=[ordinal])... | Used to enumerate CPUID information override values.
in ordinal of type int
The ordinal number of the leaf to get.
out idx of type int
CPUID leaf index.
out idx_sub of type int
CPUID leaf sub-index.
out val_eax of type int
CPUID leaf va... |
def combine_slices(self, slices, tensor_shape, device=None):
if tensor_shape.ndims == 0:
return slices[0]
ret = slices[:]
tensor_layout = self.tensor_layout(tensor_shape)
for mesh_dim, tensor_axis in zip(
self.shape, tensor_layout.mesh_axis_to_tensor_axis(self.ndims)):
slice_si... | Turns a set of slices into a single tensor.
Args:
slices: list of tf.Tensor with length self.size.
tensor_shape: Shape.
device: optional str. If absent, we use the devices of the slices.
Returns:
tf.Tensor. |
def create(cls, schema, name):
fn = cls.tags.get(name, XBuiltin)
return fn(schema, name) | Create an object based on the root tag name.
@param schema: A schema object.
@type schema: L{schema.Schema}
@param name: The name.
@type name: str
@return: The created object.
@rtype: L{XBuiltin} |
def to_shapely_polygon(self):
import shapely.geometry
return shapely.geometry.Polygon([(point[0], point[1]) for point in self.exterior]) | Convert this polygon to a Shapely polygon.
Returns
-------
shapely.geometry.Polygon
The Shapely polygon matching this polygon's exterior. |
def readU8(self, register):
result = self._bus.read_byte_data(self._address, register) & 0xFF
self._logger.debug("Read 0x%02X from register 0x%02X",
result, register)
return result | Read an unsigned byte from the specified register. |
def data_indicators(self, indicators, entity_count):
data = []
for xid, indicator_data in indicators.items():
entity_count += 1
if isinstance(indicator_data, dict):
data.append(indicator_data)
else:
data.append(indicat... | Process Indicator data. |
def run_followers(self, prompt):
assert isinstance(prompt, Prompt)
self.pending_prompts.put(prompt)
if self.iteration_lock.acquire(False):
start_time = time.time()
i = 0
try:
while True:
try:
... | First caller adds a prompt to queue and
runs followers until there are no more
pending prompts.
Subsequent callers just add a prompt
to the queue, avoiding recursion. |
def revoke(self, role):
if role in self.roles:
self.roles.remove(role) | Remove a role from the entity.
:type role: str
:param role: The role to remove from the entity. |
def toggle_comments(self):
if not self.__comment_marker:
return True
cursor = self.textCursor()
if not cursor.hasSelection():
cursor.movePosition(QTextCursor.StartOfBlock)
line = foundations.strings.to_string(self.document().findBlockByNumber(cursor... | Toggles comments on the document selected lines.
:return: Method success.
:rtype: bool |
def plot_gallery(saveplot=False):
from colorspacious import cspace_converter
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
x = np.linspace(0.0, 1.0, 256)
fig, axes = plt.subplots(nrows=int(len(cm.cmap_d)/2), ncols=1, figsize=(6, 12))
fig.subplots_adjust(top... | Make plot of colormaps and labels, like in the matplotlib
gallery.
:param saveplot=False: Whether to save the plot or not. |
def snapshot(self, at):
if self._name_parts.decorator != :
raise Exception("Cannot use snapshot() on an already decorated table")
value = Table._convert_decorator_time(at)
return Table("%s@%s" % (self._full_name, str(value)), context=self._context) | Return a new Table which is a snapshot of this table at the specified time.
Args:
at: the time of the snapshot. This can be a Python datetime (absolute) or timedelta
(relative to current time). The result must be after the table was created and no more
than seven days in the past. Passing... |
def remove_node_attributes(G: nx.DiGraph, attributes: Union[str, Iterable[str]]):
G = G.copy()
for _, data in G.nodes(data=True):
for attribute in setwrap(attributes):
if attribute in data:
del data[attribute]
return G | Return a copy of the graph with the given attributes
deleted from all nodes. |
def split(str, pattern, limit=-1):
sc = SparkContext._active_spark_context
return Column(sc._jvm.functions.split(_to_java_column(str), pattern, limit)) | Splits str around matches of the given pattern.
:param str: a string expression to split
:param pattern: a string representing a regular expression. The regex string should be
a Java regular expression.
:param limit: an integer which controls the number of times `pattern` is applied.
* ``l... |
def _exclude_by_filter(self, frame, filename):
try:
return self._exclude_by_filter_cache[filename]
except KeyError:
cache = self._exclude_by_filter_cache
abs_real_path_and_basename = get_abs_path_real_path_and_base_from_file(filename)
... | :param str filename:
The filename to filter.
:return: True if it should be excluded, False if it should be included and None
if no rule matched the given file. |
def read_headers(rfile, hdict=None):
if hdict is None:
hdict = {}
while True:
line = rfile.readline()
if not line:
raise ValueError("Illegal end of headers.")
if line == CRLF:
break
if not line.endswith(... | Read headers from the given stream into the given header dict.
If hdict is None, a new header dict is created. Returns the populated
header dict.
Headers which are repeated are folded together using a comma if their
specification so dictates.
This function raises ValueError when the r... |
def remove_device(self, device: Union[DeviceType, str]) -> None:
try:
if self.mutable:
_device = self.get_contentclass()(device)
try:
del self._name2device[_device.name]
except KeyError:
raise ValueError... | Remove the given |Node| or |Element| object from the actual
|Nodes| or |Elements| object.
You can pass either a string or a device:
>>> from hydpy import Node, Nodes
>>> nodes = Nodes('node_x', 'node_y')
>>> node_x, node_y = nodes
>>> nodes.remove_device(Node('node_y'))... |
def _aggregate(self, source, aggregators, data, result):
if data is None:
return
if hasattr(aggregators, ):
for key, value in six.iteritems(aggregators):
if isinstance(key, tuple):
key, regex = key
for dataKey, dataValue in six.iteritems(data):
if... | Performs aggregation at a specific node in the data/aggregator tree. |
def main():
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument(, , required=True, action=,
help=)
arg_parser.add_argument(, , required=True, action=,
help=)
arg_parser.add_argument(, , required=True, action=,
... | Main routine. |
def zero_pad(m, n=1):
return np.pad(m, (n, n), mode=, constant_values=[0]) | Pad a matrix with zeros, on all sides. |
def _validate_annotation(self, annotation):
required_keys = set(self._required_keys)
keys = set(key for key, val in annotation.items() if val)
missing_keys = required_keys.difference(keys)
if missing_keys:
error = .format(
missing_keys)
ra... | Ensures that the annotation has the right fields. |
def assert_has_calls(self, calls, any_order=False):
if not any_order:
if calls not in self.mock_calls:
raise AssertionError(
% (calls, self.mock_calls)
)
return
all_calls = list(self.mock_calls)
... | assert the mock has been called with the specified calls.
The `mock_calls` list is checked for the calls.
If `any_order` is False (the default) then the calls must be
sequential. There can be extra calls before or after the
specified calls.
If `any_order` is True then the calls... |
def check_permissions(self, request):
obj = (
hasattr(self, ) and self.get_controlled_object() or
hasattr(self, ) and self.get_object() or getattr(self, , None)
)
user = request.user
perms = self.get_required_permissions(self)
... | Retrieves the controlled object and perform the permissions check. |
def plot_learning_curve(clf, X, y, title=, cv=None,
shuffle=False, random_state=None,
train_sizes=None, n_jobs=1, scoring=None,
ax=None, figsize=None, title_fontsize="large",
text_fontsize="medium"):
if ax is None:
... | Generates a plot of the train and test learning curves for a classifier.
Args:
clf: Classifier instance that implements ``fit`` and ``predict``
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
... |
def pi_revision():
with open(, ) as infile:
for line in infile:
match = re.match(, line, flags=re.IGNORECASE)
if match and match.group(1) in [, , ]:
return 1
elif match:
... | Detect the revision number of a Raspberry Pi, useful for changing
functionality like default I2C bus based on revision. |
def stop(self):
self._stopped = True
threads = [self._accept_thread]
threads.extend(self._server_threads)
self._listening_sock.close()
for sock in list(self._server_socks):
try:
sock.shutdown(socket.SHUT_RDWR)
except socket.error:
... | Stop serving. Always call this to clean up after yourself. |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
C = self.COEFFS[imt]
dc1 = -0.3
C_PGA = self.COEFFS[PGA()]
pga1000 = np.exp(
self._compute_pga_rock(C_PGA, dc1, sites, rup, dists))
mean = (self... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. |
def fill_binop(left, right, fill_value):
if fill_value is not None:
left_mask = isna(left)
right_mask = isna(right)
left = left.copy()
right = right.copy()
mask = left_mask ^ right_mask
left[left_mask & mask] = fill_value
right[right_mask &... | If a non-None fill_value is given, replace null entries in left and right
with this value, but only in positions where _one_ of left/right is null,
not both.
Parameters
----------
left : array-like
right : array-like
fill_value : object
Returns
-------
left : array-like
rig... |
def get_graph_data(self, graph, benchmark):
if benchmark.get():
param_iter = enumerate(zip(itertools.product(*benchmark[]),
graph.get_steps()))
else:
param_iter = [(None, (None, graph.get_steps()))]
for j, (param, steps... | Iterator over graph data sets
Yields
------
param_idx
Flat index to parameter permutations for parameterized benchmarks.
None if benchmark is not parameterized.
entry_name
Name for the data set. If benchmark is non-parameterized, this is the
... |
def count(self):
return self.mapPartitions(lambda i: [sum(1 for _ in i)]).reduce(operator.add) | Return a new DStream in which each RDD has a single element
generated by counting each RDD of this DStream. |
def simple_predictive_probability_multistate(
self, M_c, X_L_list, X_D_list, Y, Q):
return su.simple_predictive_probability_multistate(
M_c, X_L_list, X_D_list, Y, Q) | Calculate probability of a cell taking a value given a latent state.
:param Y: A list of constraints to apply when querying. Each constraint
is a triplet of (r,d,v): r is the row index, d is the column
index and v is the value of the constraint
:type Y: list of lists
:... |
def pdf(cls, mass, log_mode=True):
log_mass = np.log10(mass)
mb = mbreak = [0.08, 0.5]
a = alpha = [0.3, 1.3, 2.3]
norm = 0.27947743949440446
b = 1./norm
c = b * mbreak[0]**(alpha[1]-alpha[0])
d = c * mbreak[1]**(alpha[2]-alpha[1])
... | PDF for the Kroupa IMF.
Normalization is set over the mass range from 0.1 Msun to 100 Msun |
def submit_cookbook(self, cookbook, params={}, _extra_params={}):
self._check_user_parameters(params)
files = {: cookbook}
return self._submit(params, files, _extra_params=_extra_params) | Submit a cookbook. |
def _merge_ex_dicts(sexdict, oexdict):
for okey, ovalue in oexdict.items():
if okey in sexdict:
svalue = sexdict[okey]
for fkey, fvalue in ovalue.items():
if fkey not... | Merge callable look-up tables from two objects. |
def load(target:str, namespace:str=None, default=nodefault, executable:bool=False, separators:Sequence[str]=(, ),
protect:bool=True):
assert check_argument_types()
if namespace and not in target:
allowable = dict((i.name, i) for i in iter_entry_points(namespace))
if target not in allowable:
raise ... | This helper function loads an object identified by a dotted-notation string.
For example::
# Load class Foo from example.objects
load('example.objects:Foo')
# Load the result of the class method ``new`` of the Foo object
load('example.objects:Foo.new', executable=True)
If a plugin namespace is provid... |
def assemble(
cls,
args,
input_tube,
output_tubes,
size,
disable_result,
do_stop_task,
):
workers = []
for ii in range(size):
worker = cls(**args)
worker.init2(
input_tube,
... | Create, assemble and start workers.
Workers are created of class *cls*, initialized with *args*, and given
task/result communication channels *input_tube* and *output_tubes*.
The number of workers created is according to *size* parameter.
*do_stop_task* indicates whether doTask() will be... |
def _extract_links_from_lecture_assets(self, asset_ids):
links = {}
def _add_asset(name, url, destination):
filename, extension = os.path.splitext(clean_url(name))
if extension is :
return
extension = clean_filename(
extensio... | Extract links to files of the asset ids.
@param asset_ids: List of asset ids.
@type asset_ids: [str]
@return: @see CourseraOnDemand._extract_links_from_text |
def iter_breadth_first(self, root=None):
if root == None:
root = self
yield root
last = root
for node in self.iter_breadth_first(root):
if isinstance(node, DictCell):
for subpart in node:
yield subpart... | Traverses the belief state's structure breadth-first |
def get_form_kwargs(self):
kwargs = {}
for key in six.iterkeys(self.form_classes):
if self.request.method in (, ):
kwargs[key] = {
: self.request.POST,
: self.request.FILES,
}
else:
... | Build the keyword arguments required to instantiate the form. |
def get_port_profile_for_intf_output_interface_interface_type(self, **kwargs):
config = ET.Element("config")
get_port_profile_for_intf = ET.Element("get_port_profile_for_intf")
config = get_port_profile_for_intf
output = ET.SubElement(get_port_profile_for_intf, "output")
... | Auto Generated Code |
def DateField(formatter=types.DEFAULT_DATE_FORMAT, default=NOTHING,
required=True, repr=True, cmp=True, key=None):
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, date)
converter = converters.to_date_field(formatter)
retur... | Create new date field on a model.
:param formatter: date formatter string (default: "%Y-%m-%d")
:param default: any date or string that can be converted to a date value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in obje... |
def generate(self, save=True):
stretched_photo, crop_box = self._generate_img()
if not crop_box:
crop_box = 0, 0, 0, 0
self.crop_left, self.crop_top, right, bottom = crop_box
self.crop_width = right - self.crop_left
self.crop_height = bottom - self... | Generates photo file in current format.
If ``save`` is ``True``, file is saved too. |
def open_dataset(self, recent=None, debug_filename=None, bids=False):
if recent:
filename = recent
elif debug_filename is not None:
filename = debug_filename
else:
try:
dir_name = dirname(self.filename)
except (AttributeE... | Open a new dataset.
Parameters
----------
recent : path to file
one of the recent datasets to read |
def datasets_delete(self, dataset_name, delete_contents):
url = Api._ENDPOINT + (Api._DATASETS_PATH % dataset_name)
args = {}
if delete_contents:
args[] = True
return datalab.utils.Http.request(url, method=, args=args,
credentials=self._credentials, raw_r... | Issues a request to delete a dataset.
Args:
dataset_name: the name of the dataset to delete.
delete_contents: if True, any tables in the dataset will be deleted. If False and the
dataset is non-empty an exception will be raised.
Returns:
A parsed result object.
Raises:
Exc... |
def to_location(location):
if not location:
raise SbgError()
if isinstance(location, six.string_types):
return location
else:
raise SbgError() | Serializes location to string
:param location: object to serialize
:return: string |
def all(self, data={}, **kwargs):
return super(Invoice, self).all(data, **kwargs) | Fetch all Invoice entities
Returns:
Dictionary of Invoice data |
def login(self, username, password, mode="demo"):
url = "https://trading212.com/it/login"
try:
logger.debug(f"visiting %s" % url)
self.browser.visit(url)
logger.debug(f"connected to %s" % url)
except selenium.common.exceptions.WebDriverException:
... | login function |
def get_preference_type(self, type, user_id, address, notification):
path = {}
data = {}
params = {}
path["user_id"] = user_id
path["type"] = type
path["address"] = address
... | Get a preference.
Fetch the preference for the given notification for the given communicaiton channel |
def do_rmpostfix(self, arg):
altered = False
if arg in self.curargs["functions"]:
del self.curargs["functions"][arg]
altered = True
elif arg == "*":
for varname in list(self.curargs["functions"].keys()):
del self.curargs["functions"][v... | Removes a postfix function from a variable. See 'postfix'. |
def setExtraSelections(self, selections):
def _makeQtExtraSelection(startAbsolutePosition, length):
selection = QTextEdit.ExtraSelection()
cursor = QTextCursor(self.document())
cursor.setPosition(startAbsolutePosition)
cursor.setPosition(startAbsolutePosi... | Set list of extra selections.
Selections are list of tuples ``(startAbsolutePosition, length)``.
Extra selections are reset on any text modification.
This is reimplemented method of QPlainTextEdit, it has different signature. Do not use QPlainTextEdit method |
def setFilenames( self, filenames ):
mapped = []
for filename in filenames:
filename = nativestring(filename)
if ( not filename ):
continue
mapped.append(filename)
if ( len(mapped) == self.maximumLength() ):
... | Sets the list of filenames that will be used for this menu to the \
inputed list.
:param filenames | [<str>, ..] |
def _assign_database_backend(self, db):
no_trace = getattr(database, )
self._variables_to_tally = set()
for object in self.stochastics | self.deterministics:
if object.keep_trace:
self._variables_to_tally.add(object)
try:
... | Assign Trace instance to stochastics and deterministics and Database instance
to self.
:Parameters:
- `db` : string, Database instance
The name of the database module (see below), or a Database instance.
Available databases:
- `no_trace` : Traces are not stored ... |
def set_rotation_rate(self, val):
return self.write(request.SetRotationRate(self.seq, val)) | value ca be between 0x00 and 0xFF:
value is a multiplied with 0.784 degrees/s except for:
0 --> 1 degrees/s
255 --> jumps to 400 degrees/s |
def graph_nodes_sorted(self):
return sorted(self._graph.nodes(), key=lambda _: repr(_)) | Returns an (ascending) sorted list of graph's nodes (name is used as key).
Returns
-------
:any:`list`
Description #TODO check |
def course_is_open_to_user(self, course, username=None, lti=None):
if username is None:
username = self.session_username()
if lti == "auto":
lti = self.session_lti_info() is not None
if self.has_staff_rights_on_course(course, username):
return True
... | Checks if a user is can access a course
:param course: a Course object
:param username: The username of the user that we want to check. If None, uses self.session_username()
:param lti: indicates if the user is currently in a LTI session or not.
- None to ignore the check
... |
def editex(src, tar, cost=(0, 1, 2), local=False):
return Editex().dist_abs(src, tar, cost, local) | Return the Editex distance between two strings.
This is a wrapper for :py:meth:`Editex.dist_abs`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
cost : tuple
A 3-tuple representing the cost of the four possible edits:... |
def point_seg_sep(ar, br1, br2):
v = br2 - br1
w = ar - br1
c1 = np.dot(w, v)
if c1 <= 0.0:
return ar - br1
c2 = np.sum(np.square(v))
if c2 <= c1:
return ar - br2
b = c1 / c2
bc = br1 + b * v
return ar - bc | Return the minimum separation vector between a point and a line segment,
in 3 dimensions.
Parameters
----------
ar: array-like, shape (3,)
Coordinates of a point.
br1, br2: array-like, shape (3,)
Coordinates for the points of a line segment
Returns
-------
sep: float ar... |
async def main():
async with aiohttp.ClientSession() as session:
data = Glances(loop, session, version=VERSION)
await data.get_metrics()
print("Memory values:", data.values)
await data.get_metrics()
print("Disk values:", data.value... | The main part of the example script. |
def data(self, index, role=Qt.DisplayRole):
if not index.isValid():
return to_qvariant()
value = self.get_value(index)
if index.column() == 3 and self.remote:
value = value[]
if index.column() == 3:
display = value_to_display(value, mi... | Cell content |
def get_state_paths(cls, impl, working_dir):
return [config.get_db_filename(impl, working_dir), config.get_snapshots_filename(impl, working_dir)] | Get the set of state paths that point to the current chain and state info.
Returns a list of paths. |
def redirect_std():
stdin = sys.stdin
stdout = sys.stdout
if not sys.stdin.isatty():
sys.stdin = open_raw("/dev/tty", "r", 0)
if not sys.stdout.isatty():
sys.stdout = open_raw("/dev/tty", "w", 0)
return stdin, stdout | Connect stdin/stdout to controlling terminal even if the scripts input and output
were redirected. This is useful in utilities based on termenu. |
def update_user_type(self):
if self.rb_tutor.isChecked():
self.user_type =
elif self.rb_student.isChecked():
self.user_type =
self.accept() | Return either 'tutor' or 'student' based on which radio
button is selected. |
def disconnect():
post_save.disconnect(node_created_handler, sender=Node)
node_status_changed.disconnect(node_status_changed_handler)
pre_delete.disconnect(node_deleted_handler, sender=Node) | disconnect signals |
async def send_animation(self,
animation: typing.Union[base.InputFile, base.String],
duration: typing.Union[base.Integer, None] = None,
width: typing.Union[base.Integer, None] = None,
height: typing.Union... | Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound).
On success, the sent Message is returned.
Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.
Source https://core.telegram.org/bots/api#sendanimation
... |
def reset_stats_history(self):
if self.history_enable():
reset_list = [a[] for a in self.get_items_history_list()]
logger.debug("Reset history for plugin {} (items: {})".format(self.plugin_name, reset_list))
self.stats_history.reset() | Reset the stats history (dict of GlancesAttribute). |
def sg_lookup(tensor, opt):
r
assert opt.emb is not None,
return tf.nn.embedding_lookup(opt.emb, tensor, name=opt.name) | r"""Looks up the `tensor`, which is the embedding matrix.
Args:
tensor: A tensor ( automatically given by chain )
opt:
emb: A 2-D `Tensor`. An embedding matrix.
name: If provided, replace current tensor's name.
Returns:
A `Tensor`. |
def vinet_k_num(v, v0, k0, k0p, precision=1.e-5):
return -1. * v * vinet_dPdV(v, v0, k0, k0p, precision=precision) | calculate bulk modulus numerically from volume, not pressure
according to test this differs from analytical result by 1.e-5
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param k0: bulk modulus at reference conditions
:param k0p: pressure derivative of bulk modulus a... |
def get_child_ids(self, parent_alias):
self._cache_init()
return self._cache_get_entry(self.CACHE_NAME_PARENTS, parent_alias, []) | Returns child IDs of the given parent category
:param str parent_alias: Parent category alias
:rtype: list
:return: a list of child IDs |
def _variable(lexer):
names = _names(lexer)
tok = next(lexer)
if isinstance(tok, LBRACK):
indices = _indices(lexer)
_expect_token(lexer, {RBRACK})
else:
lexer.unpop_token(tok)
indices = tuple()
return (, names, indices) | Return a variable expression. |
def _process_container_metric(self, type, metric_name, metric, scraper_config):
if metric.type not in METRIC_TYPES:
self.log.error("Metric type %s unsupported for metric %s" % (metric.type, metric.name))
return
samples = self._sum_values_by_context(metric, self._get_ent... | Takes a simple metric about a container, reports it as a rate or gauge.
If several series are found for a given container, values are summed before submission. |
def open_in_composer(self):
impact_layer = self.impact_function.analysis_impacted
report_path = dirname(impact_layer.source())
impact_report = self.impact_function.impact_report
custom_map_report_metadata = impact_report.metadata
custom_map_report_product = (
... | Open in layout designer a given MapReport instance.
.. versionadded: 4.3.0 |
def replicated_dataset(dataset, weights, n=None):
"Copy dataset, replicating each example in proportion to its weight."
n = n or len(dataset.examples)
result = copy.copy(dataset)
result.examples = weighted_replicate(dataset.examples, weights, n)
return result | Copy dataset, replicating each example in proportion to its weight. |
def collect(self):
if str_to_bool(self.config[]):
if not os.access(self.config[], os.X_OK):
self.log.error("Cannot find or exec %s"
% self.config[])
return None
command = [self.config[], , self.MOUNTSTATS]
... | Collect statistics from /proc/self/mountstats.
Currently, we do fairly naive parsing and do not actually check
the statvers value returned by mountstats. |
def MFI(frame, n=14, high_col=, low_col=, close_col=, vol_col=):
return _frame_to_series(frame, [high_col, low_col, close_col, vol_col], talib.MFI, n) | money flow inedx |
def participate(self):
try:
logger.info("Entering participate method")
ready = WebDriverWait(self.driver, 10).until(
EC.element_to_be_clickable((By.ID, "finish-reading"))
)
stimulus = self.driver.find_element_by_id("stimulus")
... | Finish reading and send text |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.