code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def check_video(video, languages=None, age=None, undefined=False):
if languages and not (languages - video.subtitle_languages):
logger.debug('All languages %r exist', languages)
return False
if age and video.age > age:
logger.debug('Video is older than %r', age)
return False
... | Perform some checks on the `video`.
All the checks are optional. Return `False` if any of this check fails:
* `languages` already exist in `video`'s :attr:`~subliminal.video.Video.subtitle_languages`.
* `video` is older than `age`.
* `video` has an `undefined` language in :attr:`~sublimina... |
def getTotalPrice(self):
price = self.getPrice()
vat = self.getVAT()
price = price and price or 0
vat = vat and vat or 0
return float(price) + (float(price) * float(vat)) / 100 | Compute total price including VAT |
def _check_delay(self):
if self._previous_request_at:
dif = round(time.time() - self._previous_request_at,
2) * 1000
if dif < self.requests_delay:
time.sleep(
(self.requests_delay - dif) / 1000)
self._previous_request_at... | Checks if a delay is needed between requests and sleeps if True |
def get_selinux_status():
getenforce_command_exists()
o = run_cmd(["getenforce"], return_output=True).strip()
logger.debug("SELinux is %r", o)
return o | get SELinux status of host
:return: string, one of Enforced, Permissive, Disabled |
def finish(self, value):
if self._done.is_set():
raise errors.AlreadyComplete()
self._value = value
for cb in self._cbacks:
backend.schedule(cb, args=(value,))
self._cbacks = None
for wait in list(self._waits):
wait.finish(self)
self._w... | Give the future it's value and trigger any associated callbacks
:param value: the new value for the future
:raises:
:class:`AlreadyComplete <junction.errors.AlreadyComplete>` if
already complete |
def find_safe_starting_point(self):
y = random.randint(2,self.grid_height-4)
x = random.randint(2,self.grid_width-4)
return y, x | finds a place on the grid which is clear on all sides
to avoid starting in the middle of a blockage |
def get_principal_credit_string_metadata(self):
metadata = dict(self._mdata['principal_credit_string'])
metadata.update({'existing_string_values': self._my_map['principalCreditString']})
return Metadata(**metadata) | Gets the metadata for the principal credit string.
return: (osid.Metadata) - metadata for the credit string
*compliance: mandatory -- This method must be implemented.* |
def cluster(list_of_texts, num_clusters=3):
pipeline = Pipeline([
("vect", CountVectorizer()),
("tfidf", TfidfTransformer()),
("clust", KMeans(n_clusters=num_clusters))
])
try:
clusters = pipeline.fit_predict(list_of_texts)
except ValueError:
clusters = list(range... | Cluster a list of texts into a predefined number of clusters.
:param list_of_texts: a list of untokenized texts
:param num_clusters: the predefined number of clusters
:return: a list with the cluster id for each text, e.g. [0,1,0,0,2,2,1] |
def read(self, fileobj):
fileobj.seek(self._dataoffset, 0)
data = fileobj.read(self.datalength)
return len(data) == self.datalength, data | Return if all data could be read and the atom payload |
def _parseupload(self, node):
if not isinstance(node,ElementTree._Element):
try:
node = clam.common.data.parsexmlstring(node)
except:
raise Exception(node)
if node.tag != 'clamupload':
raise Exception("Not a valid CLAM upload response")... | Parse CLAM Upload XML Responses. For internal use |
def _mem(self):
value = int(psutil.virtual_memory().percent)
set_metric("memory", value, category=self.category)
gauge("memory", value) | Record Memory usage. |
def last_available_business_date(self, asset_manager_id, asset_ids, page_no=None, page_size=None):
self.logger.info('Retrieving last available business dates for assets')
url = '%s/last-available-business-date' % self.endpoint
params = {'asset_manager_ids': [asset_manager_id],
... | Returns the last available business date for the assets so we know the
starting date for new data which needs to be downloaded from data providers.
This method can only be invoked by system user |
def append(self, items):
resp = self.client.add_to_item_list(items, self.url())
self.refresh()
return resp | Add some items to this ItemList and save the changes to the server
:param items: the items to add, either as a List of Item objects, an
ItemList, a List of item URLs as Strings, a single item URL as a
String, or a single Item object
:rtype: String
:returns: the server s... |
def addClass(self, cn):
if cn:
if isinstance(cn, (tuple, list, set, frozenset)):
add = self.addClass
for c in cn:
add(c)
else:
classes = self._classes
if classes is None:
self._extra['... | Add the specific class names to the class set and return ``self``. |
def compare(self, dn, attr, value):
return self.connection.compare_s(dn, attr, value) == 1 | Compare the ``attr`` of the entry ``dn`` with given ``value``.
This is a convenience wrapper for the ldap library's ``compare``
function that returns a boolean value instead of 1 or 0. |
def destroy(self, folder=None):
ameans = [(0, 0, 0) for _ in range(3)]
ret = [self.save_info(folder, ameans)]
aiomas.run(until=self.stop_slaves(folder))
self._pool.close()
self._pool.terminate()
self._pool.join()
self._env.shutdown()
return ret | Destroy the environment and the subprocesses. |
def check_secret(self, secret):
try:
return hmac.compare_digest(secret, self.secret)
except AttributeError:
return secret == self.secret | Checks if the secret string used in the authentication attempt
matches the "known" secret string. Some mechanisms will override this
method to control how this comparison is made.
Args:
secret: The secret string to compare against what was used in the
authentication ... |
def usable_cpu_count():
try:
result = len(os.sched_getaffinity(0))
except AttributeError:
try:
result = len(psutil.Process().cpu_affinity())
except AttributeError:
result = os.cpu_count()
return result | Get number of CPUs usable by the current process.
Takes into consideration cpusets restrictions.
Returns
-------
int |
def scroll_down (self):
s = self.scroll_row_start - 1
e = self.scroll_row_end - 1
self.w[s+1:e+1] = copy.deepcopy(self.w[s:e]) | Scroll display down one line. |
def loads(self, src):
assert isinstance(src, (unicode_, bytes_))
nodes = self.scan(src.strip())
self.parse(nodes)
return ''.join(map(str, nodes)) | Compile css from scss string. |
def waitForAllConnectionsToClose(self):
if not self._connections:
return self._stop()
return self._allConnectionsClosed.deferred().addBoth(self._stop) | Wait for all currently-open connections to enter the 'CLOSED' state.
Currently this is only usable from test fixtures. |
def statistical_distances(samples1, samples2, earth_mover_dist=True,
energy_dist=True):
out = []
temp = scipy.stats.ks_2samp(samples1, samples2)
out.append(temp.pvalue)
out.append(temp.statistic)
if earth_mover_dist:
out.append(scipy.stats.wasserstein_distance(sampl... | Compute measures of the statistical distance between samples.
Parameters
----------
samples1: 1d array
samples2: 1d array
earth_mover_dist: bool, optional
Whether or not to compute the Earth mover's distance between the
samples.
energy_dist: bool, optional
Whether or not... |
def check(self):
try:
si, uninterp = self.interpolate()
except (Object.CoercionError, MustacheParser.Uninterpolatable) as e:
return TypeCheck(False, "Unable to interpolate: %s" % e)
return self.checker(si) | Type check this object. |
def init_region_config(self, region):
self.regions[region] = self.region_config_class(region_name = region, resource_types = self.resource_types) | Initialize the region's configuration
:param region: Name of the region |
def _forward(self, x_dot_parameters):
return forward(self._lattice, x_dot_parameters,
self.state_machine.n_states) | Helper to calculate the forward weights. |
def should_display_warnings_for(to_type):
if not hasattr(to_type, '__module__'):
return True
elif to_type.__module__ in {'builtins'} or to_type.__module__.startswith('parsyfiles') \
or to_type.__name__ in {'DataFrame'}:
return False
elif issubclass(to_type, int) or issubclass(to_... | Central method where we control whether warnings should be displayed |
def max_length_discard(records, max_length):
logging.info('Applying _max_length_discard generator: '
'discarding records longer than '
'.')
for record in records:
if len(record) > max_length:
logging.debug('Discarding long sequence: %s, length=%d',
... | Discard any records that are longer than max_length. |
def put(self, ndef_message, timeout=1.0):
if not self.socket:
try:
self.connect('urn:nfc:sn:snep')
except nfc.llcp.ConnectRefused:
return False
else:
self.release_connection = True
else:
self.release_connecti... | Send an NDEF message to the server. Temporarily connects to
the default SNEP server if the client is not yet connected.
.. deprecated:: 0.13
Use :meth:`put_records` or :meth:`put_octets`. |
def check_for_lane_permission(self):
if self.current.lane_permission:
log.debug("HAS LANE PERM: %s" % self.current.lane_permission)
perm = self.current.lane_permission
if not self.current.has_permission(perm):
raise HTTPError(403, "You don't have required lane... | One or more permissions can be associated with a lane
of a workflow. In a similar way, a lane can be
restricted with relation to other lanes of the workflow.
This method called on lane changes and checks user has
required permissions and relations.
Raises:
HTTPForb... |
def _operator(self, op, close_group=False):
op = op.upper().strip()
if op not in OP_LIST:
raise ValueError("Error: '{}' is not a valid operator.".format(op))
else:
if close_group:
op = ") " + op + " ("
else:
op = " " + op + " "
... | Add an operator between terms.
There must be a term added before using this method.
All operators have helpers, so this method is usually not necessary to directly invoke.
Arguments:
op (str): The operator to add. Must be in the OP_LIST.
close_group (bool): If ``True``, ... |
def update_subnet(self, subnet, body=None):
return self.put(self.subnet_path % (subnet), body=body) | Updates a subnet. |
def price(self, from_=None, **kwargs):
if from_:
kwargs["from"] = from_
uri = "%s/%s" % (self.uri, "price")
response, instance = self.request("GET", uri, params=kwargs)
return instance | Check pricing for a new outbound message.
An useful synonym for "message" command with "dummy" parameters set to true.
:Example:
message = client.messages.price(from_="447624800500", phones="999000001", text="Hello!", lists="1909100")
:param str from: One of allowed Sender ID ... |
def intersection(self,other):
if self.everything:
if other.everything:
return DiscreteSet()
else:
return DiscreteSet(other.elements)
else:
if other.everything:
return DiscreteSet(self.elements)
else:
... | Return a new DiscreteSet with the intersection of the two sets, i.e.
all elements that are in both self and other.
:param DiscreteSet other: Set to intersect with
:rtype: DiscreteSet |
def write_nochr_reads(in_file, out_file, config):
if not file_exists(out_file):
with file_transaction(config, out_file) as tx_out_file:
samtools = config_utils.get_program("samtools", config)
cmd = "{samtools} view -b -f 4 {in_file} > {tx_out_file}"
do.run(cmd.format(**lo... | Write a BAM file of reads that are not mapped on a reference chromosome.
This is useful for maintaining non-mapped reads in parallel processes
that split processing by chromosome. |
def load_images(url, format='auto', with_path=True, recursive=True, ignore_failure=True, random_order=False):
from ... import extensions as _extensions
from ...util import _make_internal_url
return _extensions.load_images(url, format, with_path,
recursive, ignore_failure... | Loads images from a directory. JPEG and PNG images are supported.
Parameters
----------
url : str
The string of the path where all the images are stored.
format : {'PNG' | 'JPG' | 'auto'}, optional
The format of the images in the directory. The default 'auto' parameter
value tr... |
def Header(self):
_ = [option.OnGetValue() for option in self.options]
return self.name | Fetch the header name of this Value. |
def publish(self, topic, *args, **kwargs):
return self._async_session.publish(topic, *args, **kwargs) | Publish an event to a topic.
Replace :meth:`autobahn.wamp.interface.IApplicationSession.publish` |
def convert_tensor(input_, device=None, non_blocking=False):
def _func(tensor):
return tensor.to(device=device, non_blocking=non_blocking) if device else tensor
return apply_to_tensor(input_, _func) | Move tensors to relevant device. |
def make_empty(self, axes=None):
if axes is None:
axes = [ensure_index([])] + [ensure_index(a)
for a in self.axes[1:]]
if self.ndim == 1:
blocks = np.array([], dtype=self.array_dtype)
else:
blocks = []
return se... | return an empty BlockManager with the items axis of len 0 |
def _match(filtered, matcher):
def match_filtered_identities(x, ids, matcher):
for y in ids:
if x.uuid == y.uuid:
return True
if matcher.match_filtered_identities(x, y):
return True
return False
matched = []
while filtered:
cand... | Old method to find matches in a set of filtered identities. |
def _kick(self):
xyz_init = self.xyz
for particle in self.particles():
particle.pos += (np.random.rand(3,) - 0.5) / 100
self._update_port_locations(xyz_init) | Slightly adjust all coordinates in a Compound
Provides a slight adjustment to coordinates to kick them out of local
energy minima. |
def _cal_color(self, value, color_index):
range_min_p = self._domain[color_index]
range_p = self._domain[color_index + 1] - range_min_p
try:
factor = (value - range_min_p) / range_p
except ZeroDivisionError:
factor = 0
min_color = self.colors[color_index]
... | Blend between two colors based on input value. |
def add_node(self, binary_descriptor):
try:
node_string = parse_binary_descriptor(binary_descriptor)
except:
self._logger.exception("Error parsing binary node descriptor: %s", binary_descriptor)
return _pack_sgerror(SensorGraphError.INVALID_NODE_STREAM)
try:
... | Add a node to the sensor_graph using a binary node descriptor.
Args:
binary_descriptor (bytes): An encoded binary node descriptor.
Returns:
int: A packed error code. |
def main():
windows_libraries = list(pylink.Library.find_library_windows())
latest_library = None
for lib in windows_libraries:
if os.path.dirname(lib).endswith('JLinkARM'):
latest_library = lib
break
elif latest_library is None:
latest_library = lib
... | Upgrades the firmware of the J-Links connected to a Windows device.
Returns:
None.
Raises:
OSError: if there are no J-Link software packages. |
def _get_graphics(dom):
out = {'autoport': 'None',
'keymap': 'None',
'listen': 'None',
'port': 'None',
'type': 'None'}
doc = ElementTree.fromstring(dom.XMLDesc(0))
for g_node in doc.findall('devices/graphics'):
for key, value in six.iteritems(g_node.attrib... | Get domain graphics from a libvirt domain object. |
def init_with_context(self, context):
site_name = get_admin_site_name(context)
self.children += [
items.MenuItem(_('Dashboard'), reverse('{0}:index'.format(site_name))),
items.Bookmarks(),
]
for title, kwargs in get_application_groups():
if kwargs.get(... | Initialize the menu items. |
def make_random_gaussians_table(n_sources, param_ranges, random_state=None):
sources = make_random_models_table(n_sources, param_ranges,
random_state=random_state)
if 'flux' in param_ranges and 'amplitude' not in param_ranges:
model = Gaussian2D(x_stddev=1, y_stdde... | Make a `~astropy.table.Table` containing randomly generated
parameters for 2D Gaussian sources.
Each row of the table corresponds to a Gaussian source whose
parameters are defined by the column names. The parameters are
drawn from a uniform distribution over the specified input ranges.
The output... |
def verify_url_path(url_path, query_args, secret_key, salt_arg='_', max_expiry=None, digest=None):
try:
supplied_signature = query_args.pop('signature')
except KeyError:
raise SigningError("Signature missing.")
if salt_arg is not None and salt_arg not in query_args:
raise SigningErro... | Verify a URL path is correctly signed.
:param url_path: URL path
:param secret_key: Signing key
:param query_args: Arguments that make up the query string
:param salt_arg: Argument required for salt (set to None to disable)
:param max_expiry: Maximum length of time an expiry value can be for (set t... |
def query_records_no_auth(self, name, query=''):
req = requests.get(self.api_server + '/api/' + name + "/" + query)
return req | Query records without authorization |
def reset_all(self, suppress_logging=False):
pool_names = list(self.pools)
for name in pool_names:
self.reset(name, suppress_logging) | iterates thru the list of established connections and resets them by disconnecting and reconnecting |
def debug(self):
url = '{}/debug/status'.format(self.url)
data = self._get(url)
return data.json() | Retrieve the debug information from the charmstore. |
def _to_dict(objects):
try:
if isinstance(objects, six.string_types):
objects = salt.utils.json.loads(objects)
except ValueError as err:
log.error("Could not parse objects: %s", err)
raise err
return objects | Potentially interprets a string as JSON for usage with mongo |
def _set_id_field(new_class):
if new_class.meta_.declared_fields:
try:
new_class.meta_.id_field = next(
field for _, field in new_class.meta_.declared_fields.items()
if field.identifier)
except StopIteration:
new_cla... | Lookup the id field for this entity and assign |
def _cmpFormatRanges(a, b):
if a.format == b.format and \
a.start == b.start and \
a.length == b.length:
return 0
else:
return cmp(id(a), id(b)) | PyQt does not define proper comparison for QTextLayout.FormatRange
Define it to check correctly, if formats has changed.
It is important for the performance |
def _check_compatible_with(
self,
other: Union[Period, Timestamp, Timedelta, NaTType],
) -> None:
raise AbstractMethodError(self) | Verify that `self` and `other` are compatible.
* DatetimeArray verifies that the timezones (if any) match
* PeriodArray verifies that the freq matches
* Timedelta has no verification
In each case, NaT is considered compatible.
Parameters
----------
other
... |
def _ParseTimestamp(self, parser_mediator, row):
timestamp = row.get('timestamp', None)
if timestamp is not None:
try:
timestamp = int(timestamp, 10)
except (ValueError, TypeError):
parser_mediator.ProduceExtractionWarning(
'Unable to parse timestamp value: {0!s}'.format(... | Provides a timestamp for the given row.
If the Trend Micro log comes from a version that provides a POSIX timestamp,
use that directly; it provides the advantages of UTC and of second
precision. Otherwise fall back onto the local-timezone date and time.
Args:
parser_mediator (ParserMediator): me... |
def range(self, value):
self._buffer.append(abs(value))
mean = sum(self._buffer) / len(self._buffer)
estimate = next(
(r for r in self.ranges if mean < self.scale * r),
self.ranges[-1]
)
if self._mapping:
return self._mapping[estimate]
... | Estimates an appropriate sensitivity range. |
def wildcards_overlap(name1, name2):
if not name1 and not name2:
return True
if not name1 or not name2:
return False
for matched1, matched2 in _character_matches(name1, name2):
if wildcards_overlap(name1[matched1:], name2[matched2:]):
return True
return False | Return true if two wildcard patterns can match the same string. |
def get_fetch_response(self, res):
res.code = res.status_code
res.headers = Headers(res.headers)
res._body = None
res.body = ''
body = res.content
if body:
if self.is_json(res.headers):
res._body = res.json()
else:
r... | the goal of this method is to make the requests object more endpoints like
res -- requests Response -- the native requests response instance, we manipulate
it a bit to make it look a bit more like the internal endpoints.Response object |
def get_custom_fields(self):
return CustomField.objects.filter(
content_type=ContentType.objects.get_for_model(self)) | Return a list of custom fields for this model |
def evpn_prefix_del(self, route_type, route_dist, esi=0,
ethernet_tag_id=None, mac_addr=None, ip_addr=None,
ip_prefix=None):
func_name = 'evpn_prefix.delete_local'
kwargs = {EVPN_ROUTE_TYPE: route_type,
ROUTE_DISTINGUISHER: route_dist}
... | This method deletes an advertised EVPN route.
``route_type`` specifies one of the EVPN route type name.
``route_dist`` specifies a route distinguisher value.
``esi`` is an value to specify the Ethernet Segment Identifier.
``ethernet_tag_id`` specifies the Ethernet Tag ID.
``... |
def hashable(val):
if val is None:
return val
try:
hash(val)
except TypeError:
return repr(val)
else:
return val | Test if `val` is hashable and if not, get it's string representation
Parameters
----------
val: object
Any (possibly not hashable) python object
Returns
-------
val or string
The given `val` if it is hashable or it's string representation |
def _render_resource(self, resource):
if not resource:
return None
if not isinstance(resource, self.model):
raise TypeError(
'Resource(s) type must be the same as the serializer model type.')
top_level_members = {}
try:
top_level_member... | Renders a resource's top level members based on json-api spec.
Top level members include:
'id', 'type', 'attributes', 'relationships' |
def matching_line(freq, data, tref, bin_size=1):
template_line = line_model(freq, data, tref=tref)
_, amp, phi = avg_inner_product(data, template_line,
bin_size=bin_size)
return line_model(freq, data, tref=tref, amp=amp, phi=phi) | Find the parameter of the line with frequency 'freq' in the data.
Parameters
----------
freq: float
Frequency of the line to find in the data.
data: pycbc.types.TimeSeries
Data from which the line wants to be measured.
tref: float
Reference time for the frequency line.
b... |
def safe_mkdir(folder_name, force_perm=None):
if os.path.exists(folder_name):
return
intermediary_folders = folder_name.split(os.path.sep)
if intermediary_folders[-1] == "":
intermediary_folders = intermediary_folders[:-1]
if force_perm:
force_perm_path = folder_name.split(os.pat... | Create the specified folder.
If the parent folders do not exist, they are also created.
If the folder already exists, nothing is done.
Parameters
----------
folder_name : str
Name of the folder to create.
force_perm : str
Mode to use for folder creation. |
def apply(self, model):
model.medium = {row.exchange: row.uptake
for row in self.data.itertuples(index=False)} | Set the defined medium on the given model. |
def _pair_exp_cov(X, Y, span=180):
covariation = (X - X.mean()) * (Y - Y.mean())
if span < 10:
warnings.warn("it is recommended to use a higher span, e.g 30 days")
return covariation.ewm(span=span).mean()[-1] | Calculate the exponential covariance between two timeseries of returns.
:param X: first time series of returns
:type X: pd.Series
:param Y: second time series of returns
:type Y: pd.Series
:param span: the span of the exponential weighting function, defaults to 180
:type span: int, optional
... |
async def execute_command(
self, *args: bytes, timeout: DefaultNumType = _default
) -> SMTPResponse:
if timeout is _default:
timeout = self.timeout
self._raise_error_if_disconnected()
try:
response = await self.protocol.execute_command(
*args, ... | Check that we're connected, if we got a timeout value, and then
pass the command to the protocol.
:raises SMTPServerDisconnected: connection lost |
def checkout_task(current_target):
try:
scm = _make_scm(current_target)
src_dir = current_target.config.get("dp.src_dir")
shared_dir = current_target.config.get("dp.src_dir_shared")
scm.checkout(repo_dir=src_dir, shared_dir=shared_dir)
scm.update(repo_dir=src_dir)
except ... | Update or a local checkout.
Arguments
target - The target to operate on. |
def initialize_fields(self):
for name, field in self.instance._meta.fields.items():
if getattr(field, 'primary_key', False):
continue
self._meta.fields[name] = self.convert_field(name, field)
for name in dir(type(self.instance)):
field = getattr(type(s... | Convert all model fields to validator fields.
Then call the parent so that overwrites can happen if necessary for manually defined fields.
:return: None |
def plot_iso(axis, step, var):
xmesh, ymesh, fld = get_meshes_fld(step, var)
if conf.field.shift:
fld = np.roll(fld, conf.field.shift, axis=0)
axis.contour(xmesh, ymesh, fld, linewidths=1) | Plot isocontours of scalar field.
Args:
axis (:class:`matplotlib.axes.Axes`): the axis handler of an
existing matplotlib figure where the isocontours should
be plotted.
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
var (str): ... |
def _ensure_env(self, env: Union[jinja2.Environment, None]):
if not env:
env = jinja2.Environment()
if not env.loader:
env.loader = jinja2.FunctionLoader(lambda filename: self._cache[filename])
if 'faker' not in env.globals:
faker = Faker()
faker.s... | Make sure the jinja environment is minimally configured. |
def blocks_to_mark_complete_on_view(self, blocks):
blocks = {block for block in blocks if self.can_mark_block_complete_on_view(block)}
completions = self.get_completions({block.location for block in blocks})
return {block for block in blocks if completions.get(block.location, 0) < 1.0} | Returns a set of blocks which should be marked complete on view and haven't been yet. |
def exponential_terms(order, variables, data):
variables_exp = OrderedDict()
data_exp = OrderedDict()
if 1 in order:
data_exp[1] = data[variables]
variables_exp[1] = variables
order = set(order) - set([1])
for o in order:
variables_exp[o] = ['{}_power{}'.format(v, o) for ... | Compute exponential expansions.
Parameters
----------
order: range or list(int)
A list of exponential terms to include. For instance, [1, 2]
indicates that the first and second exponential terms should be added.
To retain the original terms, 1 *must* be included in the list.
var... |
def locations(self):
req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/locations')
locations = req.get().json()
return locations | Available locations to be used when creating a new machine.
:returns: A list of available locations. |
def do_session(self, args):
filename = 'Not specified' if self.__session.filename is None \
else self.__session.filename
print('{0: <30}: {1}'.format('Filename', filename)) | Print current session information |
def encode_jwt_token(
self, user,
override_access_lifespan=None, override_refresh_lifespan=None,
**custom_claims
):
ClaimCollisionError.require_condition(
set(custom_claims.keys()).isdisjoint(RESERVED_CLAIMS),
"The custom claims collide with requir... | Encodes user data into a jwt token that can be used for authorization
at protected endpoints
:param: override_access_lifespan: Override's the instance's access
lifespan to set a custom duration
after which the new to... |
def remove_callback(instance, prop, callback):
p = getattr(type(instance), prop)
if not isinstance(p, CallbackProperty):
raise TypeError("%s is not a CallbackProperty" % prop)
p.remove_callback(instance, callback) | Remove a callback function from a property in an instance
Parameters
----------
instance
The instance to detach the callback from
prop : str
Name of callback property in `instance`
callback : func
The callback function to remove |
def bounter(size_mb=None, need_iteration=True, need_counts=True, log_counting=None):
if not need_counts:
return CardinalityEstimator()
if size_mb is None:
raise ValueError("Max size in MB must be provided.")
if need_iteration:
if log_counting:
raise ValueError("Log counti... | Factory method for bounter implementation.
Args:
size_mb (int): Desired memory footprint of the counter.
need_iteration (Bool): With `True`, create a `HashTable` implementation which can
iterate over inserted key/value pairs.
With `False`, create a `CountMinS... |
def change_in_longitude(lat, miles):
r = earth_radius * math.cos(lat * degrees_to_radians)
return (miles / r) * radians_to_degrees | Given a latitude and a distance west, return the change in longitude. |
def process_tokens(self, tokens):
for tok_type, token, (start_row, start_col), _, _ in tokens:
if tok_type == tokenize.STRING:
self._process_string_token(token, start_row, start_col) | Process the token stream.
This is required to override the parent class' implementation.
Args:
tokens: the tokens from the token stream to process. |
def set_location(self, time, latitude, longitude):
if isinstance(time, datetime.datetime):
tzinfo = time.tzinfo
else:
tzinfo = time.tz
if tzinfo is None:
self.location = Location(latitude, longitude)
else:
self.location = Location(latitude,... | Sets the location for the query.
Parameters
----------
time: datetime or DatetimeIndex
Time range of the query. |
def get_properties(self):
variables = self.model.nodes()
property_tag = {}
for variable in sorted(variables):
properties = self.model.node[variable]
properties = collections.OrderedDict(sorted(properties.items()))
property_tag[variable] = []
for pr... | Add property to variables in BIF
Returns
-------
dict: dict of type {variable: list of properties }
Example
-------
>>> from pgmpy.readwrite import BIFReader, BIFWriter
>>> model = BIFReader('dog-problem.bif').get_model()
>>> writer = BIFWriter(model)
... |
def set_model(self, m):
self._model = m
self.new_root.emit(QtCore.QModelIndex())
self.model_changed(m) | Set the model for the level
:param m: the model that the level should use
:type m: QtCore.QAbstractItemModel
:returns: None
:rtype: None
:raises: None |
def join_pretty_tensors(tensors, output, join_function=None, name='join'):
if not tensors:
raise ValueError('pretty_tensors must be a non-empty sequence.')
with output.g.name_scope(name):
if join_function is None:
last_dim = len(tensors[0].shape) - 1
return output.with_tensor(tf.concat(tensors, ... | Joins the list of pretty_tensors and sets head of output_pretty_tensor.
Args:
tensors: A sequence of Layers or SequentialLayerBuilders to join.
output: A pretty_tensor to set the head with the result.
join_function: A function to join the tensors, defaults to concat on the
last dimension.
name:... |
def getSymbols(self):
symbollist = []
for rule in self.productions:
for symbol in rule.leftside + rule.rightside:
if symbol not in symbollist:
symbollist.append(symbol)
symbollist += self.terminal_symbols
return symbollist | Returns every symbol |
def reset(self):
status = self.m_objPCANBasic.Reset(self.m_PcanHandle)
return status == PCAN_ERROR_OK | Command the PCAN driver to reset the bus after an error. |
def selected_canvas_hazlayer(self):
if self.lstCanvasHazLayers.selectedItems():
item = self.lstCanvasHazLayers.currentItem()
else:
return None
try:
layer_id = item.data(Qt.UserRole)
except (AttributeError, NameError):
layer_id = None
... | Obtain the canvas layer selected by user.
:returns: The currently selected map layer in the list.
:rtype: QgsMapLayer |
def runtime_error(self, msg, method):
if self.testing:
self._py3_wrapper.report_exception(msg)
raise KeyboardInterrupt
if self.error_hide:
self.hide_errors()
return
msg = msg.splitlines()[0]
errors = [self.module_nice_name, u"{}: {}".format... | Show the error in the bar |
def _get_serializer(self, _type):
if _type in _serializers:
return _serializers[_type]
elif _type == 'array':
return self._get_array_serializer()
elif _type == 'object':
return self._get_object_serializer()
raise ValueError('Unknown type: {}'.format(_t... | Gets a serializer for a particular type. For primitives, returns the
serializer from the module-level serializers.
For arrays and objects, uses the special _get_T_serializer methods to
build the encoders and decoders. |
def login(username, password, development_mode=False):
retval = None
try:
user = User.fetch_by(username=username)
if user and (development_mode or user.verify_password(password)):
retval = user
except OperationalError:
pass
return retva... | Return the user if successful, None otherwise |
async def migrate_redis1_to_redis2(storage1: RedisStorage, storage2: RedisStorage2):
if not isinstance(storage1, RedisStorage):
raise TypeError(f"{type(storage1)} is not RedisStorage instance.")
if not isinstance(storage2, RedisStorage):
raise TypeError(f"{type(storage2)} is not RedisStorage ins... | Helper for migrating from RedisStorage to RedisStorage2
:param storage1: instance of RedisStorage
:param storage2: instance of RedisStorage2
:return: |
def load_object(target, namespace=None):
if namespace and ':' not in target:
allowable = dict((i.name, i) for i in pkg_resources.iter_entry_points(namespace))
if target not in allowable:
raise ValueError('Unknown plugin "' + target + '"; found: ' + ', '.join(allowable))
return a... | This helper function loads an object identified by a dotted-notation string.
For example:
# Load class Foo from example.objects
load_object('example.objects:Foo')
If a plugin namespace is provided simple name references are allowed. For example:
# Load the plugin named 'routing' fro... |
def update_metadata(self):
if self._data_directory is None:
raise Exception('Need to call `api.set_data_directory` first.')
metadata_url = 'https://repo.continuum.io/pkgs/metadata.json'
filepath = os.sep.join([self._data_directory, 'metadata.json'])
worker = self.download_req... | Update the metadata available for packages in repo.continuum.io.
Returns a download worker. |
def create(self, request, *args, **kwargs):
bulk_payload = self._get_bulk_payload(request)
if bulk_payload:
return self._create_many(bulk_payload)
return super(DynamicModelViewSet, self).create(
request, *args, **kwargs) | Either create a single or many model instances in bulk
using the Serializer's many=True ability from Django REST >= 2.2.5.
The data can be represented by the serializer name (single or plural
forms), dict or list.
Examples:
POST /dogs/
{
"name": "Fido",
... |
def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True,
group_keys=True, squeeze=False):
from sparklingpandas.groupby import GroupBy
return GroupBy(self, by=by, axis=axis, level=level, as_index=as_index,
sort=sort, group_keys=group_keys, squeeze=sq... | Returns a groupby on the schema rdd. This returns a GroupBy object.
Note that grouping by a column name will be faster than most other
options due to implementation. |
def _rem(self, command, *args, **kwargs):
if self.indexable:
self.deindex(args)
return self._traverse_command(command, *args, **kwargs) | Shortcut for commands that only remove values from the field.
Removed values will be deindexed. |
def get_filter_item(name: str, operation: bytes, value: bytes) -> bytes:
assert isinstance(name, str)
assert isinstance(value, bytes)
if operation is None:
return filter_format(b"(%s=%s)", [name, value])
elif operation == "contains":
assert value != ""
return filter_format(b"(%s=... | A field could be found for this term, try to get filter string for it. |
def make_mesh( coor, ngroups, conns, mesh_in ):
mat_ids = []
for ii, conn in enumerate( conns ):
mat_id = nm.empty( (conn.shape[0],), dtype = nm.int32 )
mat_id.fill( mesh_in.mat_ids[ii][0] )
mat_ids.append( mat_id )
mesh_out = Mesh.from_data( 'merged mesh', coor, ngroups, conns,
... | Create a mesh reusing mat_ids and descs of mesh_in. |
def label_subplot(ax=None, x=0.5, y=-0.25, text="(a)", **kwargs):
if ax is None:
ax = plt.gca()
ax.text(x=x, y=y, s=text, transform=ax.transAxes,
horizontalalignment="center", verticalalignment="top", **kwargs) | Create a subplot label. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.