code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def _update_version(connection, version):
if connection.engine.name == 'sqlite':
connection.execute('PRAGMA user_version = {}'.format(version))
elif connection.engine.name == 'postgresql':
connection.execute(DDL('CREATE SCHEMA IF NOT EXISTS {};'.format(POSTGRES_SCHEMA_NAME)))
connection.... | Updates version in the db to the given version.
Args:
connection (sqlalchemy connection): sqlalchemy session where to update version.
version (int): version of the migration. |
def create_criteria(cls, query):
criteria = []
for name, value in query.items():
if isinstance(value, list):
for inner_value in value:
criteria += cls.create_criteria({name: inner_value})
else:
criteria.append({
... | Return a criteria from a dictionary containing a query.
Query should be a dictionary, keyed by field name. If the value is
a list, it will be divided into multiple criteria as required. |
def score(self, periods=None):
periods = np.asarray(periods)
return self._score(periods.ravel()).reshape(periods.shape) | Compute the periodogram for the given period or periods
Parameters
----------
periods : float or array_like
Array of periods at which to compute the periodogram.
Returns
-------
scores : np.ndarray
Array of normalized powers (between 0 and 1) for... |
def to_data_rows(self, brains):
fields = self.get_field_names()
return map(lambda brain: self.get_data_record(brain, fields), brains) | Returns a list of dictionaries representing the values of each brain |
def _most_restrictive(date_elems):
most_index = len(DATE_ELEMENTS)
for date_elem in date_elems:
if date_elem in DATE_ELEMENTS and DATE_ELEMENTS.index(date_elem) < most_index:
most_index = DATE_ELEMENTS.index(date_elem)
if most_index < len(DATE_ELEMENTS):
return DATE_ELEMENTS[most... | Return the date_elem that has the most restrictive range from date_elems |
def sensor(self, name, config=None,
inactive_sensor_expiration_time_seconds=sys.maxsize,
parents=None):
sensor = self.get_sensor(name)
if sensor:
return sensor
with self._lock:
sensor = self.get_sensor(name)
if not sensor:
... | Get or create a sensor with the given unique name and zero or
more parent sensors. All parent sensors will receive every value
recorded with this sensor.
Arguments:
name (str): The name of the sensor
config (MetricConfig, optional): A default configuration to use
... |
def polls_slug_get(self, slug, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.polls_slug_get_with_http_info(slug, **kwargs)
else:
(data) = self.polls_slug_get_with_http_info(slug, **kwargs)
return data | Poll
A Poll on Pollster is a collection of questions and responses published by a reputable survey house. This endpoint provides raw data from the survey house, plus Pollster-provided metadata about each question. Pollster editors don't include every question when they enter Polls, and they don't necessarily e... |
def encrypt(self, plaintext_data_key, encryption_context):
if self.wrapping_algorithm.encryption_type is EncryptionType.ASYMMETRIC:
if self.wrapping_key_type is EncryptionKeyType.PRIVATE:
encrypted_key = self._wrapping_key.public_key().encrypt(
plaintext=plaintext... | Encrypts a data key using a direct wrapping key.
:param bytes plaintext_data_key: Data key to encrypt
:param dict encryption_context: Encryption context to use in encryption
:returns: Deserialized object containing encrypted key
:rtype: aws_encryption_sdk.internal.structures.EncryptedDa... |
def post(self, request, *args, **kwargs):
self.object = self.get_object()
self.object.content = request.POST['content']
self.object.title = request.POST['title']
self.object = self._mark_html_fields_as_safe(self.object)
context = self.get_context_data(object=self.object)
... | Accepts POST requests, and substitute the data in for the page's attributes. |
def update_application_metadata(template, application_id, sar_client=None):
if not template or not application_id:
raise ValueError('Require SAM template and application ID to update application metadata')
if not sar_client:
sar_client = boto3.client('serverlessrepo')
template_dict = _get_te... | Update the application metadata.
:param template: Content of a packaged YAML or JSON SAM template
:type template: str_or_dict
:param application_id: The Amazon Resource Name (ARN) of the application
:type application_id: str
:param sar_client: The boto3 client used to access SAR
:type sar_clien... |
def _create_logger(name='did', level=None):
logger = logging.getLogger(name)
handler = logging.StreamHandler()
handler.setFormatter(Logging.ColoredFormatter())
logger.addHandler(handler)
for level in Logging.LEVELS:
setattr(logger, level, getattr(logging, level))
... | Create did logger |
def by_user_and_perm(cls, user_id, perm_name, db_session=None):
db_session = get_db_session(db_session)
query = db_session.query(cls.model).filter(cls.model.user_id == user_id)
query = query.filter(cls.model.perm_name == perm_name)
return query.first() | return by user and permission name
:param user_id:
:param perm_name:
:param db_session:
:return: |
def ensure_header(self, header: BlockHeader=None) -> BlockHeader:
if header is None:
head = self.get_canonical_head()
return self.create_header_from_parent(head)
else:
return header | Return ``header`` if it is not ``None``, otherwise return the header
of the canonical head. |
def set_agent(self, agent):
self.agent = agent
self.queue = asyncio.Queue(loop=self.agent.loop)
self.presence = agent.presence
self.web = agent.web | Links behaviour with its owner agent
Args:
agent (spade.agent.Agent): the agent who owns the behaviour |
def change_db_user_password(username, password):
sql = "ALTER USER %s WITH PASSWORD '%s'" % (username, password)
excute_query(sql, use_sudo=True) | Change a db user's password. |
def project_dev_requirements():
from peltak.core import conf
from peltak.core import shell
for dep in sorted(conf.requirements):
shell.cprint(dep) | List requirements for peltak commands configured for the project.
This list is dynamic and depends on the commands you have configured in
your project's pelconf.yaml. This will be the combined list of packages
needed to be installed in order for all the configured commands to work. |
def setup_function(self):
log.options.LogOptions.set_stderr_log_level('google:INFO')
if app.get_options().debug:
log.options.LogOptions.set_stderr_log_level('google:DEBUG')
if not app.get_options().build_root:
app.set_option('build_root', os.path.join(
app... | Runs prior to the global main function. |
def fwd_chunk(self):
raise NotImplementedError("%s not implemented for %s" % (self.fwd_chunk.__func__.__name__,
self.__class__.__name__)) | Returns the chunk following this chunk in the list of free chunks. |
def relabel(self, qubits: Qubits) -> 'Channel':
chan = copy(self)
chan.vec = chan.vec.relabel(qubits)
return chan | Return a copy of this channel with new qubits |
def _filter_headers(self):
headers = {}
for user in self.usernames:
headers["fedora_messaging_user_{}".format(user)] = True
for package in self.packages:
headers["fedora_messaging_rpm_{}".format(package)] = True
for container in self.containers:
header... | Add headers designed for filtering messages based on objects.
Returns:
dict: Filter-related headers to be combined with the existing headers |
def getShape3D(self, includeJunctions=False):
if includeJunctions and not self._edge.isSpecial():
if self._shapeWithJunctions3D is None:
self._shapeWithJunctions3D = addJunctionPos(self._shape3D,
self._edge.getFromNode(
... | Returns the shape of the lane in 3d.
This function returns the shape of the lane, as defined in the net.xml
file. The returned shape is a list containing numerical
3-tuples representing the x,y,z coordinates of the shape points
where z defaults to zero.
For includeJunction=True... |
def offline(f):
@click.pass_context
@verbose
def new_func(ctx, *args, **kwargs):
ctx.obj["offline"] = True
ctx.bitshares = BitShares(**ctx.obj)
ctx.blockchain = ctx.bitshares
ctx.bitshares.set_shared_instance()
return ctx.invoke(f, *args, **kwargs)
return update_w... | This decorator allows you to access ``ctx.bitshares`` which is
an instance of BitShares with ``offline=True``. |
def managepy(cmd, extra=None):
extra = extra.split() if extra else []
run_django_cli(['invoke', cmd] + extra) | Run manage.py using this component's specific Django settings |
def _format_extname(self, ext):
if ext is None:
outs = ext
else:
outs = '{0},{1}'.format(ext[0], ext[1])
return outs | Pretty print given extension name and number tuple. |
def main(argv):
_, black_model, white_model = argv
utils.ensure_dir_exists(FLAGS.eval_sgf_dir)
play_match(black_model, white_model, FLAGS.num_evaluation_games, FLAGS.eval_sgf_dir) | Play matches between two neural nets. |
def from_blob(cls, s):
atom_str, edge_str = s.split()
numbers = np.array([int(s) for s in atom_str.split(",")])
edges = []
orders = []
for s in edge_str.split(","):
i, j, o = (int(w) for w in s.split("_"))
edges.append((i, j))
orders.append(o)
... | Construct a molecular graph from the blob representation |
def _can_be_double(x):
return ((np.issubdtype(x.dtype, np.floating) and
x.dtype.itemsize <= np.dtype(float).itemsize) or
(np.issubdtype(x.dtype, np.signedinteger) and
np.can_cast(x, float))) | Return if the array can be safely converted to double.
That happens when the dtype is a float with the same size of
a double or narrower, or when is an integer that can be safely
converted to double (if the roundtrip conversion works). |
def _collect_layer_output_min_max(mod, data, include_layer=None,
max_num_examples=None, logger=None):
collector = _LayerOutputMinMaxCollector(include_layer=include_layer, logger=logger)
num_examples = _collect_layer_statistics(mod, data, collector, max_num_examples, logger)
... | Collect min and max values from layer outputs and save them in
a dictionary mapped by layer names. |
def cors(*args, **kwargs):
def decorator(fn):
cors_fn = flask_cors.cross_origin(automatic_options=False, *args, **kwargs)
if inspect.isclass(fn):
apply_function_to_members(fn, cors_fn)
else:
return cors_fn(fn)
return fn
return decorator | A wrapper around flask-cors cross_origin, to also act on classes
**An extra note about cors, a response must be available before the
cors is applied. Dynamic return is applied after the fact, so use the
decorators, json, xml, or return self.render() for txt/html
ie:
@cors()
class Index(Mocha):
... |
def _file_local_or_remote(f, get_retriever):
if os.path.exists(f):
return f
integration, config = get_retriever.integration_and_config(f)
if integration:
return integration.file_exists(f, config) | Check for presence of a local or remote file. |
def convert_to_shape(x):
if x is None:
return None
if isinstance(x, Shape):
return x
if isinstance(x, str):
x = _parse_string_to_list_of_pairs(x, seconds_to_int=True)
return Shape(x) | Converts input to a Shape.
Args:
x: Shape, str, or None.
Returns:
Shape or None.
Raises:
ValueError: If x cannot be converted to a Shape. |
def recov_date(self, return_date=False):
dd = self.drawdown_idx()
mask = nancumprod(dd != nanmin(dd)).astype(bool)
res = dd.mask(mask) == 0
if not res.any():
recov = pd.NaT
else:
recov = res.idxmax()
if return_date:
return recov.date()
... | Drawdown recovery date.
Date at which `self` recovered to previous high-water mark.
Parameters
----------
return_date : bool, default False
If True, return a `datetime.date` object.
If False, return a Pandas Timestamp object.
Returns
-------
... |
def from_tushare(dataframe, dtype='day'):
if dtype in ['day']:
return QA_DataStruct_Stock_day(
dataframe.assign(date=pd.to_datetime(dataframe.date)
).set_index(['date',
'code'],
drop=Fals... | dataframe from tushare
Arguments:
dataframe {[type]} -- [description]
Returns:
[type] -- [description] |
def translate_connect_args(self, names=[], **kw):
translated = {}
attribute_names = ["host", "database", "username", "password", "port"]
for sname in attribute_names:
if names:
name = names.pop(0)
elif sname in kw:
name = kw[sname]
... | Translate url attributes into a dictionary of connection arguments.
Returns attributes of this url (`host`, `database`, `username`,
`password`, `port`) as a plain dictionary. The attribute names are
used as the keys by default. Unset or false attributes are omitted
from the final dict... |
def _init_user_stub(self, **stub_kwargs):
task_args = stub_kwargs.copy()
self.testbed.setup_env(overwrite=True,
USER_ID=task_args.pop('USER_ID', 'testuser'),
USER_EMAIL=task_args.pop('USER_EMAIL', 'testuser@example.org'),
... | Initializes the user stub using nosegae config magic |
def cast(self, dtype):
for child in self._children.values():
child.cast(dtype)
for _, param in self.params.items():
param.cast(dtype) | Cast this Block to use another data type.
Parameters
----------
dtype : str or numpy.dtype
The new data type. |
def update_cluster(cluster_ref, cluster_spec):
cluster_name = get_managed_object_name(cluster_ref)
log.trace('Updating cluster \'%s\'', cluster_name)
try:
task = cluster_ref.ReconfigureComputeResource_Task(cluster_spec,
modify=True)
exce... | Updates a cluster in a datacenter.
cluster_ref
The cluster reference.
cluster_spec
The cluster spec (vim.ClusterConfigSpecEx).
Defaults to None. |
def parse_yaml(self, y):
super(Preceding, self).parse_yaml(y)
c = y['condition']['preceding']
if 'timeout' in c:
self.timeout = int(c['timeout'])
else:
self.timeout = 0
if 'sendingTiming' in c:
self.sending_timing = c['sendingTiming']
e... | Parse a YAML specification of a preceding condition into this
object. |
def cli(env, billing_id, datacenter):
mgr = SoftLayer.LoadBalancerManager(env.client)
if not formatting.confirm("This action will incur charges on your "
"account. Continue?"):
raise exceptions.CLIAbort('Aborted.')
mgr.add_local_lb(billing_id, datacenter=datacenter)
... | Adds a load balancer given the id returned from create-options. |
def _make_postfixes_1( analysis ):
assert FORM in analysis, '(!) The input analysis does not contain "'+FORM+'" key.'
if 'neg' in analysis[FORM]:
analysis[FORM] = re.sub( '^\s*neg ([^,]*)$', '\\1 Neg', analysis[FORM] )
analysis[FORM] = re.sub( ' Neg Neg$', ' Neg', analysis[FORM] )
analysis[F... | Provides some post-fixes. |
def setTxPower(self, tx_power, peername=None):
if peername:
protocols = [p for p in self.protocols
if p.peername[0] == peername]
else:
protocols = self.protocols
for proto in protocols:
proto.setTxPower(tx_power) | Set the transmit power on one or all readers
If peername is None, set the transmit power for all readers.
Otherwise, set it for that specific reader. |
def __auth_descriptor(self, api_info):
if api_info.auth is None:
return None
auth_descriptor = {}
if api_info.auth.allow_cookie_auth is not None:
auth_descriptor['allowCookieAuth'] = api_info.auth.allow_cookie_auth
if api_info.auth.blocked_regions:
auth_descriptor['blockedRegions'] = a... | Builds an auth descriptor from API info.
Args:
api_info: An _ApiInfo object.
Returns:
A dictionary with 'allowCookieAuth' and/or 'blockedRegions' keys. |
def addService(self, service, parentService=None):
if parentService is not None:
def check(services):
for jS in services:
if jS.service == parentService or check(jS.service._childServices):
return True
return False
... | Add a service.
The :func:`toil.job.Job.Service.start` method of the service will be called
after the run method has completed but before any successors are run.
The service's :func:`toil.job.Job.Service.stop` method will be called once
the successors of the job have been run.
S... |
def valueRepr(self):
v = self.value
if self.behavior:
v = self.behavior.valueRepr(self)
return v | Transform the representation of the value
according to the behavior, if any. |
def _CheckPacketSize(cursor):
cur_packet_size = int(_ReadVariable("max_allowed_packet", cursor))
if cur_packet_size < MAX_PACKET_SIZE:
raise Error(
"MySQL max_allowed_packet of {0} is required, got {1}. "
"Please set max_allowed_packet={0} in your MySQL config.".format(
MAX_PACKET_SI... | Checks that MySQL packet size is big enough for expected query size. |
def remove(self, label):
if label.id in self._labels:
self._labels[label.id] = None
self._dirty = True | Remove a label.
Args:
label (gkeepapi.node.Label): The Label object. |
def predict_encoding(file_path, n_lines=20):
import chardet
with open(file_path, 'rb') as f:
rawdata = b''.join([f.readline() for _ in range(n_lines)])
return chardet.detect(rawdata)['encoding'] | Get file encoding of a text file |
def save(self, url, storage_options=None):
from dask.bytes import open_files
with open_files([url], **(storage_options or {}), mode='wt')[0] as f:
f.write(self.serialize()) | Output this catalog to a file as YAML
Parameters
----------
url : str
Location to save to, perhaps remote
storage_options : dict
Extra arguments for the file-system |
def add_section(self, id_, parent_id, section_type, points):
assert id_ not in self.sections, 'id %s already exists in sections' % id_
self.sections[id_] = BlockNeuronBuilder.BlockSection(parent_id, section_type, points) | add a section
Args:
id_(int): identifying number of the section
parent_id(int): identifying number of the parent of this section
section_type(int): the section type as defined by POINT_TYPE
points is an array of [X, Y, Z, R] |
def get_value(self):
if self.value is not_computed:
self.value = self.value_provider()
if self.value is not_computed:
return None
return self.value | Returns the value of the constant. |
def sentinels(self, name):
fut = self.execute(b'SENTINELS', name, encoding='utf-8')
return wait_convert(fut, parse_sentinel_slaves_and_sentinels) | Returns a list of sentinels for ``name``. |
def _exclude_ipv4_networks(self, networks, networks_to_exclude):
for network_to_exclude in networks_to_exclude:
def _exclude_ipv4_network(network):
try:
return list(network.address_exclude(network_to_exclude))
except ValueError:
... | Exclude the list of networks from another list of networks
and return a flat list of new networks.
:param networks: List of IPv4 networks to exclude from
:param networks_to_exclude: List of IPv4 networks to exclude
:returns: Flat list of IPv4 networks |
def start_cmd(cmd, descr, data):
if data and "provenance" in data:
entity_id = tz.get_in(["provenance", "entity"], data) | Retain details about starting a command, returning a command identifier. |
def _start(self):
last_call = 42
while self._focus:
sleep(1 / 100)
mouse = pygame.mouse.get_pos()
last_value = self.get()
self.value_px = mouse[0]
if self.get() == last_value:
continue
if last_call + self.interval / ... | Starts checking if the SB is shifted |
def _eval_variables(self):
for k, v in listitems(self._variables):
self._variables[k] = v() if hasattr(v, '__call__') else v | evaluates callable _variables |
def post_ticket(self, title, body):
ticket = {'subject': title,
'message': body }
response = self.client.post("/api/v1/tickets.json", {
'email': self.email,
'ticket': ticket })['ticket']
bot.info(response['... | post_ticket will post a ticket to the uservoice helpdesk
Parameters
==========
title: the title (subject) of the issue
body: the message to send |
def enable(self, size, block_size=None, store=None, store_sync_interval=None):
self._set('queue', size)
self._set('queue-blocksize', block_size)
self._set('queue-store', store)
self._set('queue-store-sync', store_sync_interval)
return self._section | Enables shared queue of the given size.
:param int size: Queue size.
:param int block_size: Block size in bytes. Default: 8 KiB.
:param str|unicode store: Persist the queue into file.
:param int store_sync_interval: Store sync interval in master cycles (usually seconds). |
def cross_variance(self, x, z, sigmas_f, sigmas_h):
Pxz = zeros((sigmas_f.shape[1], sigmas_h.shape[1]))
N = sigmas_f.shape[0]
for i in range(N):
dx = self.residual_x(sigmas_f[i], x)
dz = self.residual_z(sigmas_h[i], z)
Pxz += self.Wc[i] * outer(dx, dz)
... | Compute cross variance of the state `x` and measurement `z`. |
def rot13_app(parser, cmd, args):
parser.add_argument('value', help='the value to rot13, read from stdin if omitted', nargs='?')
args = parser.parse_args(args)
return rot13(pwnypack.main.string_value_or_stdin(args.value)) | rot13 encrypt a value. |
def authorize_client_credentials(
self, client_id, client_secret=None, scope="private_agent"
):
self.auth_data = {
"grant_type": "client_credentials",
"scope": [ scope ],
"client_id": client_id,
"client_secret": client_secret
}
self._do... | Authorize to platform with client credentials
This should be used if you posses client_id/client_secret pair
generated by platform. |
def _findLocation(self, reference_name, start, end):
try:
return self._locationMap['hg19'][reference_name][start][end]
except:
return None | return a location key form the locationMap |
def fermion_avg(efermi, norm_hopping, func):
if func == 'ekin':
func = bethe_ekin_zeroT
elif func == 'ocupation':
func = bethe_filling_zeroT
return np.asarray([func(ef, tz) for ef, tz in zip(efermi, norm_hopping)]) | calcules for every slave it's average over the desired observable |
def connect(uri, factory=pymongo.MongoClient):
warnings.warn(
"do not use. Just call MongoClient directly.", DeprecationWarning)
return factory(uri) | Use the factory to establish a connection to uri. |
def bandwidth(self):
return np.abs(np.diff(self.pairs(), axis=1)).max() | Computes the 'bandwidth' of a graph. |
def getFileName(self, suffix=None, extension="jar"):
assert (self._artifactId is not None)
assert (self._version is not None)
return "{0}-{1}{2}{3}".format(
self._artifactId,
self._version.getRawString(),
"-" + suffix.lstrip("-") if suffix is not None else "",... | Returns the basename of the artifact's file, using Maven's conventions.
In particular, it will be:
<artifactId>-<version>[-<suffix>][.<extension>] |
def responderForName(self, instance, commandName):
method = super(_AMPExposer, self).get(instance, commandName)
return method | When resolving a command to a method from the wire, the information
available is the command's name; look up a command.
@param instance: an instance of a class who has methods exposed via
this exposer's L{_AMPExposer.expose} method.
@param commandName: the C{commandName} attribute of a... |
def _one_diagonal_capture_square(self, capture_square, position):
if self.contains_opposite_color_piece(capture_square, position):
if self.would_move_be_promotion():
for move in self.create_promotion_moves(status=notation_const.CAPTURE_AND_PROMOTE,
... | Adds specified diagonal as a capture move if it is one |
def acgt_match(string):
search = re.compile(r'[^ACGT]').search
return not bool(search(string)) | returns True if sting consist of only "A "C" "G" "T" |
def delete_organization(session, organization):
last_modified = datetime.datetime.utcnow()
for enrollment in organization.enrollments:
enrollment.uidentity.last_modified = last_modified
session.delete(organization)
session.flush() | Remove an organization from the session.
Function that removes from the session the organization
given in `organization`. Data related such as domains
or enrollments are also removed.
:param session: database session
:param organization: organization to remove |
def classify_single_recording(raw_data_json, model_folder, verbose=False):
evaluation_file = evaluate_model(raw_data_json, model_folder, verbose)
with open(os.path.join(model_folder, "info.yml")) as ymlfile:
model_description = yaml.load(ymlfile)
index2latex = get_index2latex(model_description)
... | Get the classification as a list of tuples. The first value is the LaTeX
code, the second value is the probability. |
def getScriptLocation():
location = os.path.abspath("./")
if __file__.rfind("/") != -1:
location = __file__[:__file__.rfind("/")]
return location | Helper function to get the location of a Python file. |
def combine_keys(pks: Iterable[Ed25519PublicPoint]) -> Ed25519PublicPoint:
P = [_ed25519.decodepoint(pk) for pk in pks]
combine = reduce(_ed25519.edwards_add, P)
return Ed25519PublicPoint(_ed25519.encodepoint(combine)) | Combine a list of Ed25519 points into a "global" CoSi key. |
def write_path(self, path_value):
parent_dir = os.path.dirname(self.path)
try:
os.makedirs(parent_dir)
except OSError:
pass
with open(self.path, "w") as fph:
fph.write(path_value.value) | this will overwrite dst path - be careful |
def get_environ(self, key, default=None, cast=None):
key = key.upper()
data = self.environ.get(key, default)
if data:
if cast in converters:
data = converters.get(cast)(data)
if cast is True:
data = parse_conf_data(data, tomlfy=True)
... | Get value from environment variable using os.environ.get
:param key: The name of the setting value, will always be upper case
:param default: In case of not found it will be returned
:param cast: Should cast in to @int, @float, @bool or @json ?
or cast must be true to use cast inferenc... |
def _add_res(line):
global resource
fields = line.strip().split()
if resource:
ret.append(resource)
resource = {}
resource["resource name"] = fields[0]
resource["local role"] = fields[1].split(":")[1]
resource["local volumes"] = []
resource["peer nodes"] = [] | Analyse the line of local resource of ``drbdadm status`` |
def get_projected_fields(self, req):
try:
args = getattr(req, 'args', {})
return ','.join(json.loads(args.get('projections')))
except (AttributeError, TypeError):
return None | Returns the projected fields from request. |
def decode_json(cls, dct):
if not ('event_name' in dct and 'event_values' in dct):
return dct
event_name = dct['event_name']
if event_name not in _CONCRETE_EVENT_CLASSES:
raise ValueError("Could not find appropriate Event class for event_name: %r" % event_name)
ev... | Custom JSON decoder for Events.
Can be used as the ``object_hook`` argument of ``json.load`` or
``json.loads``.
Args:
dct (dict) : a JSON dictionary to decode
The dictionary should have keys ``event_name`` and ``event_values``
Raises:
ValueError... |
def _ordered_node_addrs(self, function_address):
try:
function = self.kb.functions[function_address]
except KeyError:
return [ ]
if function_address not in self._function_node_addrs:
sorted_nodes = CFGUtils.quasi_topological_sort_nodes(function.graph)
... | For a given function, return all nodes in an optimal traversal order. If the function does not exist, return an
empty list.
:param int function_address: Address of the function.
:return: A ordered list of the nodes.
:rtype: list |
def payload_register(ptype, klass, pid):
cmd = ['payload-register']
for x in [ptype, klass, pid]:
cmd.append(x)
subprocess.check_call(cmd) | is used while a hook is running to let Juju know that a
payload has been started. |
def format_response(self, response):
conversion = self.shell_ctx.config.BOOLEAN_STATES
if response in conversion:
if conversion[response]:
return 'yes'
return 'no'
raise ValueError('Invalid response: input should equate to true or false') | formats a response in a binary |
def asyncStarCmap(asyncCallable, iterable):
results = []
yield coopStar(asyncCallable, results.append, iterable)
returnValue(results) | itertools.starmap for deferred callables using cooperative multitasking |
def _Comparator(self, operator):
if operator == "=":
return lambda x, y: x == y
elif operator == ">=":
return lambda x, y: x >= y
elif operator == ">":
return lambda x, y: x > y
elif operator == "<=":
return lambda x, y: x <= y
elif operator == "<":
return lambda x, y: ... | Generate lambdas for uid and gid comparison. |
def wr_xlsx(self, fout_xlsx, goea_results, **kws):
objprt = PrtFmt()
prt_flds = kws.get('prt_flds', self.get_prtflds_default(goea_results))
xlsx_data = MgrNtGOEAs(goea_results).get_goea_nts_prt(prt_flds, **kws)
if 'fld2col_widths' not in kws:
kws['fld2col_widths'] = {f:objprt... | Write a xlsx file. |
def _attach_fields(obj):
for attr in base_fields.__all__:
if not hasattr(obj, attr):
setattr(obj, attr, getattr(base_fields, attr))
for attr in fields.__all__:
setattr(obj, attr, getattr(fields, attr)) | Attach all the marshmallow fields classes to ``obj``, including
Flask-Marshmallow's custom fields. |
def cipher(self):
cipher = Cipher(*self.mode().aes_args(), **self.mode().aes_kwargs())
return WAES.WAESCipher(cipher) | Generate AES-cipher
:return: Crypto.Cipher.AES.AESCipher |
def get_object_or_none(model, *args, **kwargs):
try:
return model._default_manager.get(*args, **kwargs)
except model.DoesNotExist:
return None | Like get_object_or_404, but doesn't throw an exception.
Allows querying for an object that might not exist without triggering
an exception. |
def date(self, year: Number, month: Number, day: Number) -> Date:
return Date(year, month, day) | Takes three numbers and returns a ``Date`` object whose year, month, and day are the three
numbers in that order. |
def workflow_states_column(self, obj):
workflow_states = models.WorkflowState.objects.filter(
content_type=self._get_obj_ct(obj),
object_id=obj.pk,
)
return ', '.join([unicode(wfs) for wfs in workflow_states]) | Return text description of workflow states assigned to object |
def project_create(auth=None, **kwargs):
cloud = get_openstack_cloud(auth)
kwargs = _clean_kwargs(keep_name=True, **kwargs)
return cloud.create_project(**kwargs) | Create a project
CLI Example:
.. code-block:: bash
salt '*' keystoneng.project_create name=project1
salt '*' keystoneng.project_create name=project2 domain_id=b62e76fbeeff4e8fb77073f591cf211e
salt '*' keystoneng.project_create name=project3 enabled=False description='my project3' |
def is_symmetric(self, symprec=0.1):
sg = SpacegroupAnalyzer(self, symprec=symprec)
return sg.is_laue() | Checks if slab is symmetric, i.e., contains inversion symmetry.
Args:
symprec (float): Symmetry precision used for SpaceGroup analyzer.
Returns:
(bool) Whether slab contains inversion symmetry. |
def TimeField(formatter=types.DEFAULT_TIME_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, time)
converter = converters.to_time_field(formatter)
return att... | Create new time field on a model.
:param formatter: time formatter string (default: "%H:%M:%S")
:param default: any time or string that can be converted to a time 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 rename(self, new_name, *args, **kwargs):
new = self.reddit_session.rename_multireddit(self.name, new_name,
*args, **kwargs)
self.__dict__ = new.__dict__
return self | Rename this multireddit.
This function is a handy shortcut to
:meth:`rename_multireddit` of the reddit_session. |
def parse_authority(cls, authority):
userinfo, sep, host = authority.partition('@')
if not sep:
return '', userinfo
else:
return userinfo, host | Parse the authority part and return userinfo and host. |
def set_seat_logical_name(self, seat):
rc = self._libinput.libinput_device_set_seat_logical_name(
self._handle, seat.encode())
assert rc == 0, 'Cannot assign device to {}'.format(seat) | Change the logical seat associated with this device by removing
the device and adding it to the new seat.
This command is identical to physically unplugging the device, then
re-plugging it as a member of the new seat. libinput will generate
a :attr:`~libinput.constant.EventType.DEVICE_REMOVED` event and this
... |
def kwds(self):
return _kwds(base=self.base, item=self.item,
leng=self.leng, refs=self.refs,
both=self.both, kind=self.kind, type=self.type) | Return all attributes as keywords dict. |
def _downloaded_filename(self):
link = self._link() or self._finder.find_requirement(self._req, upgrade=False)
if link:
lower_scheme = link.scheme.lower()
if lower_scheme == 'http' or lower_scheme == 'https':
file_path = self._download(link)
return... | Download the package's archive if necessary, and return its
filename.
--no-deps is implied, as we have reimplemented the bits that would
ordinarily do dependency resolution. |
def rndbytes(size=16, alphabet=""):
x = rndstr(size, alphabet)
if isinstance(x, six.string_types):
return x.encode('utf-8')
return x | Returns rndstr always as a binary type |
def _on_login(self, user):
self._bot = bool(user.bot)
self._self_input_peer = utils.get_input_peer(user, allow_self=False)
self._authorized = True
return user | Callback called whenever the login or sign up process completes.
Returns the input user parameter. |
def collect_github_config():
github_config = {}
for field in ["user", "token"]:
try:
github_config[field] = subprocess.check_output(["git", "config", "github.{}".format(field)]).decode('utf-8').strip()
except (OSError, subprocess.CalledProcessError):
pass
return github_config | Try load Github configuration such as usernames from the local or global git config |
def addPolylineAnnot(self, points):
CheckParent(self)
val = _fitz.Page_addPolylineAnnot(self, points)
if not val: return
val.thisown = True
val.parent = weakref.proxy(self)
self._annot_refs[id(val)] = val
return val | Add a 'Polyline' annotation for a sequence of points. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.