code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def status(self, message, *args, **kwargs):
if self.isEnabledFor(GNUPG_STATUS_LEVEL):
self._log(GNUPG_STATUS_LEVEL, message, args, **kwargs) | LogRecord for GnuPG internal status messages. |
def refund_reward(event, agreement_id, did, service_agreement, price, consumer_account,
publisher_address, condition_ids):
logger.debug(f"trigger refund after event {event}.")
access_id, lock_id = condition_ids[:2]
name_to_parameter = {param.name: param for param in
... | Refund the reward to the publisher address.
:param event: AttributeDict with the event data.
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param service_agreement: ServiceAgreement instance
:param price: Asset price, int
:param consumer_account: Account instance of the... |
def _validate_header(self, hed):
if not bool(hed):
return False
length = -1
for row in hed:
if not bool(row):
return False
elif length == -1:
length = len(row)
elif len(row) != length:
return False
... | Validate the list that represents the table header.
:param hed: The list that represents the table header.
:type hed: list(list(hatemile.util.html.htmldomelement.HTMLDOMElement))
:return: True if the table header is valid or False if the table header
is not valid.
:rtyp... |
def pkg_config_header_strings(pkg_libraries):
_, _, header_dirs = pkg_config(pkg_libraries)
header_strings = []
for header_dir in header_dirs:
header_strings.append("-I" + header_dir)
return header_strings | Returns a list of header strings that could be passed to a compiler |
def find_mapping(
self,
other_lattice: "Lattice",
ltol: float = 1e-5,
atol: float = 1,
skip_rotation_matrix: bool = False,
) -> Optional[Tuple["Lattice", Optional[np.ndarray], np.ndarray]]:
for x in self.find_all_mappings(
other_lattice, ltol, atol, skip_r... | Finds a mapping between current lattice and another lattice. There
are an infinite number of choices of basis vectors for two entirely
equivalent lattices. This method returns a mapping that maps
other_lattice to this lattice.
Args:
other_lattice (Lattice): Another lattice t... |
def set_color(self, rgb):
target = ','.join([str(c) for c in rgb])
self.set_service_value(
self.color_service,
'ColorRGB',
'newColorRGBTarget',
target)
rgbi = self.get_color_index(['R', 'G', 'B'])
if rgbi is None:
return
... | Set dimmer color. |
def _get_type_name(target_thing):
thing = target_thing
if hasattr(thing, 'im_class'):
return thing.im_class.__name__
if inspect.ismethod(thing):
for cls in inspect.getmro(thing.__self__.__class__):
if cls.__dict__.get(thing.__name__) is thing:
return cls.__name__
... | Functions, bound methods and unbound methods change significantly in Python 3.
For instance:
class SomeObject(object):
def method():
pass
In Python 2:
- Unbound method inspect.ismethod(SomeObject.method) returns True
- Unbound inspect.isfunction(SomeObject.method) returns Fals... |
def get_all_lines(self):
output = []
line = []
lineno = 1
for char in self.string:
line.append(char)
if char == '\n':
output.append(SourceLine(''.join(line), lineno))
line = []
lineno += 1
if line:
... | Return all lines of the SourceString as a list of SourceLine's. |
def fetch_by_refresh_token(self, refresh_token):
row = self.fetchone(self.fetch_by_refresh_token_query, refresh_token)
if row is None:
raise AccessTokenNotFound
scopes = self._fetch_scopes(access_token_id=row[0])
data = self._fetch_data(access_token_id=row[0])
return ... | Retrieves an access token by its refresh token.
:param refresh_token: The refresh token of an access token as a `str`.
:return: An instance of :class:`oauth2.datatype.AccessToken`.
:raises: :class:`oauth2.error.AccessTokenNotFound` if not access token
could be retrieved. |
def rename_fmapm(bids_base, basename):
files = dict()
for ext in ['nii.gz', 'json']:
for echo in [1, 2]:
fname = '{0}_e{1}.{2}'.format(basename, echo, ext)
src = os.path.join(bids_base, 'fmap', fname)
if os.path.exists(src):
dst = src.replace(
... | Rename magnitude fieldmap file to BIDS specification |
def after(parents, func=None):
if func is None:
return lambda f: after(parents, f)
dep = Dependent(parents, func)
for parent in parents:
if parent.complete:
dep._incoming(parent, parent.value)
else:
parent._children.append(weakref.ref(dep))
return dep | Create a new Future whose completion depends on parent futures
The new future will have a function that it calls once all its parents
have completed, the return value of which will be its final value.
There is a special case, however, in which the dependent future's
callback returns a future or list of... |
def _get_destcache(self, graph, orig, branch, turn, tick, *, forward):
destcache, destcache_lru, get_keycachelike, successors, adds_dels_sucpred = self._get_destcache_stuff
lru_append(destcache, destcache_lru, ((graph, orig, branch), turn, tick), KEYCACHE_MAXSIZE)
return get_keycachelike(
... | Return a set of destination nodes succeeding ``orig`` |
def parse_skypipe_data_stream(msg, for_pipe):
header = str(msg.pop(0))
command = str(msg.pop(0))
pipe_name = str(msg.pop(0))
data = str(msg.pop(0))
if header != SP_HEADER: return
if pipe_name != for_pipe: return
if command != SP_CMD_DATA: return
if data == SP_DATA_EOF:
raise EOFE... | May return data from skypipe message or raises EOFError |
def weighted_std(values, weights):
average = np.average(values, weights=weights)
variance = np.average((values-average)**2, weights=weights)
return np.sqrt(variance) | Calculate standard deviation weighted by errors |
def create_default_profiles(apps, schema_editor):
Profile = apps.get_model("edxval", "Profile")
for profile in DEFAULT_PROFILES:
Profile.objects.get_or_create(profile_name=profile) | Add default profiles |
def get_order_container(self, quote_id):
quote = self.client['Billing_Order_Quote']
container = quote.getRecalculatedOrderContainer(id=quote_id)
return container | Generate an order container from a quote object.
:param quote_id: ID number of target quote |
def PrintTags(self, file):
print >>file, '/* Tag definition for %s */' % self._name
print >>file, 'enum %s_ {' % self._name.lower()
for entry in self._entries:
print >>file, ' %s=%d,' % (self.EntryTagName(entry),
entry.Tag())
print >>f... | Prints the tag definitions for a structure. |
def get(self, name):
if not self.get_block(r'route-map\s%s\s\w+\s\d+' % name):
return None
return self._parse_entries(name) | Provides a method to retrieve all routemap configuration
related to the name attribute.
Args:
name (string): The name of the routemap.
Returns:
None if the specified routemap does not exists. If the routermap
exists a dictionary will be provided as follows::... |
def add_arguments(self, parser):
parser.add_argument('--length', default=self.length,
type=int, help=_('SECRET_KEY length default=%d' % self.length))
parser.add_argument('--alphabet', default=self.allowed_chars,
type=str, help=_('alphabet to use de... | Define optional arguments with default values |
def apply_purging(self, catalogue, flag_vector, magnitude_table):
output_catalogue = deepcopy(catalogue)
if magnitude_table is not None:
if flag_vector is not None:
output_catalogue.catalogue_mt_filter(
magnitude_table, flag_vector)
return ... | Apply all the various purging conditions, if specified.
:param catalogue:
Earthquake catalogue as instance of :class:`openquake.hmtk.seismicity.catalogue.Catalogue`
:param numpy.array flag_vector:
Boolean vector specifying whether each event is valid (therefore
writt... |
def _generate_genesis_block(self):
genesis_header = block_pb2.BlockHeader(
block_num=0,
previous_block_id=NULL_BLOCK_IDENTIFIER,
signer_public_key=self._identity_signer.get_public_key().as_hex())
return BlockBuilder(genesis_header) | Returns a blocker wrapper with the basics of the block header in place |
def requests_for_variant(self, request, variant_id=None):
requests = ProductRequest.objects.filter(variant__id=variant_id)
serializer = self.serializer_class(requests, many=True)
return Response(data=serializer.data, status=status.HTTP_200_OK) | Get all the requests for a single variant |
def to_string(node):
with io.BytesIO() as f:
write([node], f)
return f.getvalue().decode('utf-8') | Convert a node into a string in NRML format |
def create(symbol, X, y=None, ctx=None,
num_epoch=None, epoch_size=None, optimizer='sgd', initializer=Uniform(0.01),
eval_data=None, eval_metric='acc',
epoch_end_callback=None, batch_end_callback=None,
kvstore='local', logger=None, work_load_list=None,
... | Functional style to create a model.
This function is more consistent with functional
languages such as R, where mutation is not allowed.
Parameters
----------
symbol : Symbol
The symbol configuration of a computation network.
X : DataIter
Training... |
async def get_default_min_hwe_kernel(cls) -> typing.Optional[str]:
data = await cls.get_config("default_min_hwe_kernel")
return None if data is None or data == "" else data | Default minimum kernel version.
The minimum kernel version used on new and commissioned nodes. |
def http_context(self, worker_ctx):
http = {}
if isinstance(worker_ctx.entrypoint, HttpRequestHandler):
try:
request = worker_ctx.args[0]
try:
if request.mimetype == 'application/json':
data = request.data
... | Attempt to extract HTTP context if an HTTP entrypoint was used. |
def _decade_ranges_in_date_range(self, begin_date, end_date):
begin_dated = begin_date.year / 10
end_dated = end_date.year / 10
decades = []
for d in range(begin_dated, end_dated + 1):
decades.append('{}-{}'.format(d * 10, d * 10 + 9))
return decades | Return a list of decades which is covered by date range. |
def split_phylogeny(p, level="s"):
level = level+"__"
result = p.split(level)
return result[0]+level+result[1].split(";")[0] | Return either the full or truncated version of a QIIME-formatted taxonomy string.
:type p: str
:param p: A QIIME-formatted taxonomy string: k__Foo; p__Bar; ...
:type level: str
:param level: The different level of identification are kingdom (k), phylum (p),
class (c),order (o), famil... |
def _check_trim(data):
trim = data["algorithm"].get("trim_reads")
if trim:
if trim == "fastp" and data["algorithm"].get("align_split_size") is not False:
raise ValueError("In sample %s, `trim_reads: fastp` currently requires `align_split_size: false`" %
(dd.get_s... | Check for valid values for trim_reads. |
def touch_member(config, dcs):
p = Postgresql(config['postgresql'])
p.set_state('running')
p.set_role('master')
def restapi_connection_string(config):
protocol = 'https' if config.get('certfile') else 'http'
connect_address = config.get('connect_address')
listen = config['listen'... | Rip-off of the ha.touch_member without inter-class dependencies |
def repeat(coro, times=1, step=1, limit=1, loop=None):
assert_corofunction(coro=coro)
times = max(int(times), 1)
iterable = range(1, times + 1, step)
return (yield from map(coro, iterable, limit=limit, loop=loop)) | Executes the coroutine function ``x`` number of times,
and accumulates results in order as you would use with ``map``.
Execution concurrency is configurable using ``limit`` param.
This function is a coroutine.
Arguments:
coro (coroutinefunction): coroutine function to schedule.
times... |
def generate_lars_path(weighted_data, weighted_labels):
x_vector = weighted_data
alphas, _, coefs = lars_path(x_vector,
weighted_labels,
method='lasso',
verbose=False)
return alphas, co... | Generates the lars path for weighted data.
Args:
weighted_data: data that has been weighted by kernel
weighted_label: labels, weighted by kernel
Returns:
(alphas, coefs), both are arrays corresponding to the
regularization parameter and coefficients, res... |
def list_security_groups(call=None):
if call == 'action':
raise SaltCloudSystemExit(
'The list_security_groups function must be called with -f or --function.'
)
server, user, password = _get_xml_rpc()
auth = ':'.join([user, password])
secgroup_pool = server.one.secgrouppool.i... | Lists all security groups available to the user and the user's groups.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt-cloud -f list_security_groups opennebula |
def NOT(fn):
@chainable
def validator(v):
try:
fn(v)
except ValueError:
return v
raise ValueError('invalid')
return validator | Reverse the effect of a chainable validator function |
def terms_iterator_for_elasticsearch(fo: IO, index_name: str):
species_list = config["bel_resources"].get("species_list", [])
fo.seek(0)
with gzip.open(fo, "rt") as f:
for line in f:
term = json.loads(line)
if "term" not in term:
continue
term = te... | Add index_name to term documents for bulk load |
def batch_iter(data, batch_size, num_epochs):
data = np.array(data)
data_size = len(data)
num_batches_per_epoch = int(len(data)/batch_size) + 1
for epoch in range(num_epochs):
shuffle_indices = np.random.permutation(np.arange(data_size))
shuffled_data = data[shuffle_indices]
for ... | Generates a batch iterator for a dataset. |
def to_safe(self, word):
regex = "[^A-Za-z0-9\_"
if not self.replace_dash_in_groups:
regex += "\-"
return re.sub(regex + "]", "_", word) | Converts 'bad' characters in a string to underscores so they can be used as Ansible groups |
def _begin_write(session: UpdateSession,
loop: asyncio.AbstractEventLoop,
rootfs_file_path: str):
session.set_progress(0)
session.set_stage(Stages.WRITING)
write_future = asyncio.ensure_future(loop.run_in_executor(
None, file_actions.write_update, rootfs_file_path,
... | Start the write process. |
def record(self):
if not self._initialized:
raise pycdlibexception.PyCdlibInternalError('UDF Logical Volume Integrity Descriptor not initialized')
rec = struct.pack(self.FMT, b'\x00' * 16,
self.recording_date.record(), 1, 0, 0,
self.logical... | A method to generate the string representing this UDF Logical Volume
Integrity Descriptor.
Parameters:
None.
Returns:
A string representing this UDF Logical Volume Integrity Descriptor. |
def parse_http_accept_header(header):
components = [item.strip() for item in header.split(',')]
l = []
for component in components:
if ';' in component:
subcomponents = [item.strip() for item in component.split(';')]
l.append(
(
subcomponen... | Return a list of content types listed in the HTTP Accept header
ordered by quality.
:param header: A string describing the contents of the HTTP Accept header. |
def generic_modis5kmto1km(*data5km):
cols5km = np.arange(2, 1354, 5)
cols1km = np.arange(1354)
lines = data5km[0].shape[0] * 5
rows5km = np.arange(2, lines, 5)
rows1km = np.arange(lines)
along_track_order = 1
cross_track_order = 3
satint = Interpolator(list(data5km),
... | Getting 1km data for modis from 5km tiepoints. |
def daterange(self, datecol, date_start, op, **args):
df = self._daterange(datecol, date_start, op, **args)
if df is None:
self.err("Can not select date range data")
self.df = df | Returns rows in a date range |
def set_primary_contact(self, email):
params = {"email": email}
response = self._put(self.uri_for('primarycontact'), params=params)
return json_to_py(response) | assigns the primary contact for this client |
def get_content_descendants_by_type(self, content_id, child_type, expand=None, start=None, limit=None,
callback=None):
params = {}
if expand:
params["expand"] = expand
if start is not None:
params["start"] = int(start)
if li... | Returns the direct descendants of a piece of Content, limited to a single descendant type.
The {@link ContentType}(s) of the descendants returned is specified by the "type" path parameter in the request.
Currently the only supported descendants are comment descendants of non-comment Content.
:... |
def filterGraph(graph, node_fnc):
nodes = filter(lambda l: node_fnc(l), graph.nodes())
edges = {}
gedges = graph.edges()
for u in gedges:
if u not in nodes:
continue
for v in gedges[u]:
if v not in nodes:
continue
try:
edges[u].append(v)
except KeyError:
edges[u] = [v]
ret... | Remove all nodes for with node_fnc does not hold |
def angprofile(self, **kwargs):
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
self._replace_none(kwargs_copy)
localpath = NameFactory.angprofile_format.format(**kwargs_copy)
if kwargs.get('fullpath', False):
return self.fullpath(localpath=lo... | return the file name for sun or moon angular profiles |
def get_config(config_file):
config = {}
tobool = lambda s: True if s.lower() == 'true' else False
if config_file:
try:
f = open(config_file, 'r')
except:
print ("Unable to open configuration file '{0}'".format(config_file))
else:
for line in f.rea... | Get the configuration from a file.
@param config_file: the configuration file
@return: the configuration
@rtype: dict |
def _encode_params(**kw):
def _encode(L, k, v):
if isinstance(v, unicode):
L.append('%s=%s' % (k, urllib.quote(v.encode('utf-8'))))
elif isinstance(v, str):
L.append('%s=%s' % (k, urllib.quote(v)))
elif isinstance(v, collections.Iterable):
for x in v:
... | Do url-encode parameters
>>> _encode_params(a=1, b='R&D')
'a=1&b=R%26D'
>>> _encode_params(a=u'\u4e2d\u6587', b=['A', 'B', 123])
'a=%E4%B8%AD%E6%96%87&b=A&b=B&b=123' |
def sconsign_dir(node):
if not node._sconsign:
import SCons.SConsign
node._sconsign = SCons.SConsign.ForDirectory(node)
return node._sconsign | Return the .sconsign file info for this directory,
creating it first if necessary. |
def mapPriority(levelno):
if levelno <= _logging.DEBUG:
return LOG_DEBUG
elif levelno <= _logging.INFO:
return LOG_INFO
elif levelno <= _logging.WARNING:
return LOG_WARNING
elif levelno <= _logging.ERROR:
return LOG_ERR
elif levelno... | Map logging levels to journald priorities.
Since Python log level numbers are "sparse", we have
to map numbers in between the standard levels too. |
def line(self, x_0, y_0, x_1, y_1, color):
d_x = abs(x_1 - x_0)
d_y = abs(y_1 - y_0)
x, y = x_0, y_0
s_x = -1 if x_0 > x_1 else 1
s_y = -1 if y_0 > y_1 else 1
if d_x > d_y:
err = d_x / 2.0
while x != x_1:
self.pixel(x, y, color)
... | Bresenham's line algorithm |
def flush_profile_data(self):
with self.lock:
events = self.events
self.events = []
if self.worker.mode == ray.WORKER_MODE:
component_type = "worker"
else:
component_type = "driver"
self.worker.raylet_client.push_profile_events(
... | Push the logged profiling data to the global control store. |
def get_thumbnail_format(self):
if self.field.thumbnail_format:
return self.field.thumbnail_format.lower()
else:
filename_split = self.name.rsplit('.', 1)
return filename_split[-1] | Determines the target thumbnail type either by looking for a format
override specified at the model level, or by using the format the
user uploaded. |
def savings_score(y_true, y_pred, cost_mat):
y_true = column_or_1d(y_true)
y_pred = column_or_1d(y_pred)
n_samples = len(y_true)
cost_base = min(cost_loss(y_true, np.zeros(n_samples), cost_mat),
cost_loss(y_true, np.ones(n_samples), cost_mat))
cost = cost_loss(y_true, y_pred, cos... | Savings score.
This function calculates the savings cost of using y_pred on y_true with
cost-matrix cost-mat, as the difference of y_pred and the cost_loss of a naive
classification model.
Parameters
----------
y_true : array-like or label indicator matrix
Ground truth (correct) labels... |
def dice(self, n, d):
for i in range(0, n):
yield self.roll_die(d) | Roll ``n`` dice with ``d`` faces, and yield the results.
This is an iterator. You'll get the result of each die in
successon. |
def cleanup(self, release):
log.info("Performing cleanup.")
return execute_actioncollection(release._releasefile, actioncollection=release._cleanup, confirm=True) | Perform cleanup actions on the releasefile of the given release
This is inteded to be used in a action unit.
:param release: the release with the releasefile and cleanup actions
:type release: :class:`Release`
:returns: the action status of the cleanup actions
:rtype: :class:`A... |
def _get_action(trans):
mark_action = {
'^': (_Action.ADD_MARK, Mark.HAT),
'+': (_Action.ADD_MARK, Mark.BREVE),
'*': (_Action.ADD_MARK, Mark.HORN),
'-': (_Action.ADD_MARK, Mark.BAR),
}
accent_action = {
'\\': (_Action.ADD_ACCENT, Accent.GRAVE),
'/': (_Action.A... | Return the action inferred from the transformation `trans`.
and the parameter going with this action
An _Action.ADD_MARK goes with a Mark
while an _Action.ADD_ACCENT goes with an Accent |
def form_upload_valid(self, form):
self.current_step = self.STEP_LINES
lines = form.cleaned_data['file']
initial_lines = [dict(zip(self.get_columns(), line)) for line in lines]
inner_form = self.get_form(self.get_form_class(),
data=None,
files=None,
in... | Handle a valid upload form. |
def CAPM(self, benchmark, has_const=False, use_const=True):
return ols.OLS(
y=self, x=benchmark, has_const=has_const, use_const=use_const
) | Interface to OLS regression against `benchmark`.
`self.alpha()`, `self.beta()` and several other methods
stem from here. For the full method set, see
`pyfinance.ols.OLS`.
Parameters
----------
benchmark : {pd.Series, TSeries, pd.DataFrame, np.ndarray}
The b... |
def errint(marker, number):
marker = stypes.stringToCharP(marker)
number = ctypes.c_int(number)
libspice.errint_c(marker, number) | Substitute an integer for the first occurrence of a marker found
in the current long error message.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/errint_c.html
:param marker: A substring of the error message to be replaced.
:type marker: str
:param number: The integer to substitute for m... |
def dumb_css_parser(data):
data += ';'
importIndex = data.find('@import')
while importIndex != -1:
data = data[0:importIndex] + data[data.find(';', importIndex) + 1:]
importIndex = data.find('@import')
elements = [x.split('{') for x in data.split('}') if '{' in x.strip()]
try:
... | returns a hash of css selectors, each of which contains a hash of css attributes |
def send_sticker(self, chat_id=None, sticker=None, reply_to_message_id=None, reply_markup=None):
payload = dict(chat_id=chat_id,
reply_to_message_id=reply_to_message_id,
reply_markup=reply_markup)
files = dict(sticker=open(sticker, 'rb'))
return Mess... | Use this method to send .webp stickers. On success, the sent Message is returned. |
def wait_until_running(self, callback=None):
status = self.machine.scheduler.wait_until_running(
self.job, self.worker_config.time_out)
if status.running:
self.online = True
if callback:
callback(self)
else:
raise TimeoutError("... | Waits until the remote worker is running, then calls the callback.
Usually, this method is passed to a different thread; the callback
is then a function patching results through to the result queue. |
def get_tgt_for(user):
if not settings.CAS_PROXY_CALLBACK:
raise CasConfigException("No proxy callback set in settings")
try:
return Tgt.objects.get(username=user.username)
except ObjectDoesNotExist:
logger.warning('No ticket found for user {user}'.format(
user=user.usern... | Fetch a ticket granting ticket for a given user.
:param user: UserObj
:return: TGT or Exepction |
def pvals(cls, slice_, axis=0, weighted=True):
return cls._factory(slice_, axis, weighted).pvals | Wishart CDF values for slice columns as square ndarray.
Wishart CDF (Cumulative Distribution Function) is calculated to determine
statistical significance of slice columns, in relation to all other columns.
These values represent the answer to the question "How much is a particular
colu... |
def add_version(f):
doc = f.__doc__
f.__doc__ = "Version: " + __version__ + "\n\n" + doc
return f | Add the version of wily to the help heading.
:param f: function to decorate
:return: decorated function |
def get_urls(self):
urls = super(DashboardSite, self).get_urls()
custom_urls = [
url(r'^$',
self.admin_view(HomeView.as_view()),
name='index'),
url(r'^logs/', include(logs_urlpatterns(self.admin_view))),
]
custom_urls += get_realtim... | Get urls method.
Returns:
list: the list of url objects. |
def update_appt(self, complex: str, house: str, price: str, square: str, id: str, **kwargs):
self.check_house(complex, house)
kwargs['price'] = self._format_decimal(price)
kwargs['square'] = self._format_decimal(square)
self.put('developers/{developer}/complexes/{complex}/houses/{house}/... | Update existing appartment |
def cmd_ok(cmd):
try:
sp.check_call(cmd, stderr=sp.PIPE, stdout=sp.PIPE)
except sp.CalledProcessError:
pass
except:
sys.stderr.write("{} not found, skipping\n".format(cmd))
return False
return True | Returns True if cmd can be run. |
def custom_decode(encoding):
encoding = encoding.lower()
alternates = {
'big5': 'big5hkscs',
'gb2312': 'gb18030',
'ascii': 'utf-8',
'MacCyrillic': 'cp1251',
}
if encoding in alternates:
return alternates[encoding]
else:
return encoding | Overrides encoding when charset declaration
or charset determination is a subset of a larger
charset. Created because of issues with Chinese websites |
def update(self, *args):
Logger.debug("Board: updating")
self.remove_absent_pawns()
self.remove_absent_spots()
self.remove_absent_arrows()
self.add_new_spots()
if self.arrow_cls:
self.add_new_arrows()
self.add_new_pawns()
self.spotlayout.finali... | Force an update to match the current state of my character.
This polls every element of the character, and therefore
causes me to sync with the LiSE core for a long time. Avoid
when possible. |
def SetDefaultAgency(self, agency, validate=True):
assert isinstance(agency, self._gtfs_factory.Agency)
self._default_agency = agency
if agency.agency_id not in self._agencies:
self.AddAgencyObject(agency, validate=validate) | Make agency the default and add it to the schedule if not already added |
def reset() -> None:
from wdom.document import get_new_document, set_document
from wdom.element import Element
from wdom.server import _tornado
from wdom.window import customElements
set_document(get_new_document())
_tornado.connections.clear()
_tornado.set_application(_tornado.Application()... | Reset all wdom objects.
This function clear all connections, elements, and resistered custom
elements. This function also makes new document/application and set them. |
def project_activity(index, start, end):
results = {
"metrics": [SubmittedPRs(index, start, end),
ClosedPRs(index, start, end)]
}
return results | Compute the metrics for the project activity section of the enriched
github pull requests index.
Returns a dictionary containing a "metric" key. This key contains the
metrics for this section.
:param index: index object
:param start: start date to get the data from
:param end: end date to get ... |
def in_degree(self, nbunch=None, t=None):
if nbunch in self:
return next(self.in_degree_iter(nbunch, t))[1]
else:
return dict(self.in_degree_iter(nbunch, t)) | Return the in degree of a node or nodes at time t.
The node in degree is the number of incoming interaction to that node in a given time frame.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be itera... |
async def filterindex(source, func):
source = transform.enumerate.raw(source)
async with streamcontext(source) as streamer:
async for i, item in streamer:
if func(i):
yield item | Filter an asynchronous sequence using the index of the elements.
The given function is synchronous, takes the index as an argument,
and returns ``True`` if the corresponding should be forwarded,
``False`` otherwise. |
def _build_response(self, resp):
self.response.content = resp.content
self.response.status_code = resp.status_code
self.response.headers = resp.headers | Build internal Response object from given response. |
def build_dump_order(orm_class, orm_classes):
if orm_class in orm_classes: return
for field_name, field_val in orm_class.schema.fields.items():
if field_val.is_ref():
build_dump_order(field_val.schema.orm_class, orm_classes)
if orm_class not in orm_classes:
orm_classes.append(orm... | pass in an array, when you encounter a ref, call this method again with the array
when something has no more refs, then it gets appended to the array and returns, each
time something gets through the list they are added, but before they are added to the
list it is checked to see if it is already in the list... |
def configure_uploadfor(self, ns, definition):
upload_for = self.create_upload_func(ns, definition, ns.relation_path, Operation.UploadFor)
upload_for.__doc__ = "Upload a {} for a {}".format(ns.subject_name, ns.object_name) | Register an upload-for relation endpoint.
The definition's func should be an upload function, which must:
- accept kwargs for path data and query string parameters
- accept a list of tuples of the form (formname, tempfilepath, filename)
- optionall return a resource
:param ns: ... |
def _to_graph(self, contexts):
prev = None
for context in contexts:
if prev is None:
prev = context
continue
yield prev[0], context[1], context[0]
prev = context | This is an iterator that returns each edge of our graph
with its two nodes |
def exists(self):
if '_id' not in self or self['_id'] is None:
return False
resp = self.r_session.head(self.document_url)
if resp.status_code not in [200, 404]:
resp.raise_for_status()
return resp.status_code == 200 | Retrieves whether the document exists in the remote database or not.
:returns: True if the document exists in the remote database,
otherwise False |
def _sanity_check_construct_result_block(ir_blocks):
if not isinstance(ir_blocks[-1], ConstructResult):
raise AssertionError(u'The last block was not ConstructResult: {}'.format(ir_blocks))
for block in ir_blocks[:-1]:
if isinstance(block, ConstructResult):
raise AssertionError(u'Fou... | Assert that ConstructResult is always the last block, and only the last block. |
def filenames(directory, tag='', sorted=False, recursive=False):
if recursive:
f = [os.path.join(directory, f) for directory, _, filename in os.walk(directory) for f in filename if f.find(tag) > -1]
else:
f = [os.path.join(directory, f) for f in os.listdir(directory) if f.find(tag) > -1]
if... | Reads in all filenames from a directory that contain a specified substring.
Parameters
----------
directory : :obj:`str`
the directory to read from
tag : :obj:`str`
optional tag to match in the filenames
sorted : bool
whether or not to sort the filenames
recursive : bool... |
def _read_body_until_close(self, response, file):
_logger.debug('Reading body until close.')
file_is_async = hasattr(file, 'drain')
while True:
data = yield from self._connection.read(self._read_size)
if not data:
break
self._data_event_dispatc... | Read the response until the connection closes.
Coroutine. |
def parse(binary, **params):
binary = io.BytesIO(binary)
collection = list()
with zipfile.ZipFile(binary, 'r') as zip_:
for zip_info in zip_.infolist():
content_type, encoding = mimetypes.guess_type(zip_info.filename)
content = zip_.read(zip_info)
content = conten... | Turns a ZIP file into a frozen sample. |
def get_contents(self):
childsigs = [n.get_csig() for n in self.children()]
return ''.join(childsigs) | The contents of an alias is the concatenation
of the content signatures of all its sources. |
def parse_field(cls: Type[DocumentType], field_name: str, line: str) -> Any:
try:
match = cls.fields_parsers[field_name].match(line)
if match is None:
raise AttributeError
value = match.group(1)
except AttributeError:
raise MalformedDocumen... | Parse a document field with regular expression and return the value
:param field_name: Name of the field
:param line: Line string to parse
:return: |
def supported_types_for_region(region_code):
if not _is_valid_region_code(region_code):
return set()
metadata = PhoneMetadata.metadata_for_region(region_code.upper())
return _supported_types_for_metadata(metadata) | Returns the types for a given region which the library has metadata for.
Will not include FIXED_LINE_OR_MOBILE (if numbers in this region could
be classified as FIXED_LINE_OR_MOBILE, both FIXED_LINE and MOBILE would
be present) and UNKNOWN.
No types will be returned for invalid or unknown region codes... |
def access_request(self, realm, exclusive=False,
passive=False, active=False, write=False, read=False):
args = AMQPWriter()
args.write_shortstr(realm)
args.write_bit(exclusive)
args.write_bit(passive)
args.write_bit(active)
args.write_bit(write)
args.write... | request an access ticket
This method requests an access ticket for an access realm. The
server responds by granting the access ticket. If the client
does not have access rights to the requested realm this causes
a connection exception. Access tickets are a per-channel
resource... |
def list_external_jar_dependencies(self, binary):
classpath_products = self.context.products.get_data('runtime_classpath')
classpath_entries = classpath_products.get_artifact_classpath_entries_for_targets(
binary.closure(bfs=True, include_scopes=Scopes.JVM_RUNTIME_SCOPES,
respect_... | Returns the external jar dependencies of the given binary.
:param binary: The jvm binary target to list transitive external dependencies for.
:type binary: :class:`pants.backend.jvm.targets.jvm_binary.JvmBinary`
:returns: A list of (jar path, coordinate) tuples.
:rtype: list of (string, :class:`pants.j... |
def _get_dns_info():
dns_list = []
try:
with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info:
lines = dns_info.readlines()
for line in lines:
if 'nameserver' in line:
dns = line.split()[1].strip()
if dns not in ... | return dns list |
def body(self):
body, _, is_markdown = self._entry_content
return TrueCallableProxy(
self._get_markup,
body,
is_markdown) if body else CallableProxy(None) | Get the above-the-fold entry body text |
def load_json_body(handler):
@wraps(handler)
def wrapper(event, context):
if isinstance(event.get('body'), str):
try:
event['body'] = json.loads(event['body'])
except:
return {'statusCode': 400, 'body': 'BAD REQUEST'}
return handler(event, ... | Automatically deserialize event bodies with json.loads.
Automatically returns a 400 BAD REQUEST if there is an error while parsing.
Usage::
>>> from lambda_decorators import load_json_body
>>> @load_json_body
... def handler(event, context):
... return event['body']['foo']
>... |
async def rollback(self):
if not self._parent._is_active:
return
await self._do_rollback()
self._is_active = False | Roll back this transaction. |
def _discarded_reads1_out_file_name(self):
if self.Parameters['-3'].isOn():
discarded_reads1 = self._absolute(str(self.Parameters['-3'].Value))
else:
raise ValueError(
"No discarded-reads1 (flag -3) output path specified")
return discarded_reads1 | Checks if file name is set for discarded reads1 output.
Returns absolute path. |
def return_file_objects(connection, container, prefix='database'):
options = []
meta_data = objectstore.get_full_container_list(
connection, container, prefix='database')
env = ENV.upper()
for o_info in meta_data:
expected_file = f'database.{ENV}'
if o_info['name'].startswith(exp... | Given connecton and container find database dumps |
def reindex(self, force=False, background=True):
if background:
indexingStrategy = 'background'
else:
indexingStrategy = 'stoptheworld'
url = self._options['server'] + '/secure/admin/jira/IndexReIndex.jspa'
r = self._session.get(url, headers=self._options['headers... | Start jira re-indexing. Returns True if reindexing is in progress or not needed, or False.
If you call reindex() without any parameters it will perform a background reindex only if JIRA thinks it should do it.
:param force: reindex even if JIRA doesn't say this is needed, False by default.
:pa... |
def getComplexFileData(self, fileInfo, data):
result = fileInfo[fileInfo.find(data + "</td>") + len(data + "</td>"):]
result = result[:result.find("</td>")]
result = result[result.rfind(">") + 1:]
return result | Function to initialize the slightly more complicated data for file info |
def load_kb_mappings_file(kbname, kbfile, separator):
num_added = 0
with open(kbfile) as kb_fd:
for line in kb_fd:
if not line.strip():
continue
try:
key, value = line.split(separator)
except ValueError:
current_app.logg... | Add KB values from file to given KB returning rows added. |
def flag_time_err(phase_err, time_thresh=0.02):
time_err = []
for stamp in phase_err:
if abs(stamp[1]) > time_thresh:
time_err.append(stamp[0])
return time_err | Find large time errors in list.
Scan through a list of tuples of time stamps and phase errors
and return a list of time stamps with timing errors above a threshold.
.. note::
This becomes important for networks cross-correlations, where
if timing information is uncertain at one site, the r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.