text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def change_path_prefix(self, path, old_prefix, new_prefix, app_name):
"""Change path prefix and include app name."""
relative_path = os.path.relpath(path, old_prefix)
return os.path.join(new_prefix, app_name, relative_path) | 0.008097 |
def _extract_links_from_asset_tags_in_text(self, text):
"""
Scan the text and extract asset tags and links to corresponding
files.
@param text: Page text.
@type text: str
@return: @see CourseraOnDemand._extract_links_from_text
"""
# Extract asset tags fr... | 0.001534 |
def get_elements(self, dat, multiple=False, retry=1, **kwargs):
"""
映射 dat:dict => ``find_element_by_dat.key`` 来查找元素
:param dat: a dict like {'name': <the ele name>}
:type dat: dict
:param multiple:
:type multiple: bool
:param retry:
:type retry: int
... | 0.00333 |
def _generate_route_method_decl(
self, namespace, route, arg_data_type, request_binary_body,
method_name_suffix='', extra_args=None):
"""Generates the method prototype for a route."""
args = ['self']
if extra_args:
args += extra_args
if request_binary_... | 0.002192 |
def rows(self, table, cols):
'''
Fetches rows from the local cache or from the db if there's no cache.
:param table: table name to select
:cols: list of columns to select
:return: list of rows
:rtype: list
'''
if self.orng_tables:
... | 0.003839 |
def parseJSON(js):
"""
{
kv_type : "",
type : "",
actors : <Actors list>
[
{
actorName : <String>,
formula: <String>,
events: ["->b", "b->"],
tr... | 0.001923 |
def columns_classes(self):
'''returns columns count'''
md = 12 / self.objects_per_row
sm = None
if self.objects_per_row > 2:
sm = 12 / (self.objects_per_row / 2)
return md, (sm or md), 12 | 0.008368 |
def convert_relational(relational):
"""Convert all inequalities to >=0 form.
"""
rel = relational.rel_op
if rel in ['==', '>=', '>']:
return relational.lhs-relational.rhs
elif rel in ['<=', '<']:
return relational.rhs-relational.lhs
else:
raise Exception("The relational o... | 0.002571 |
def _genBgTerm_fromXX(self,vTot,vCommon,XX,a=None,c=None):
"""
generate background term from SNPs
Args:
vTot: variance of Yc+Yi
vCommon: variance of Yc
XX: kinship matrix
a: common scales, it can be set for debugging purposes
c: indipe... | 0.021407 |
def is_line_layer(layer):
"""Check if a QGIS layer is vector and its geometries are lines.
:param layer: A vector layer.
:type layer: QgsVectorLayer, QgsMapLayer
:returns: True if the layer contains lines, otherwise False.
:rtype: bool
"""
try:
return (layer.type() == QgsMapLayer.... | 0.002232 |
def add_request_type_view(request):
''' View to add a new request type. Restricted to presidents and superadmins. '''
form = RequestTypeForm(request.POST or None)
if form.is_valid():
rtype = form.save()
messages.add_message(request, messages.SUCCESS,
MESSAGES['R... | 0.004412 |
def _get_team_names(self, game):
"""
Find the names and abbreviations for both teams in a game.
Using the HTML contents in a boxscore, find the name and abbreviation
for both teams and determine wether or not this is a matchup between
two Division-I teams.
Parameters
... | 0.000904 |
def decrypt_file(self, filename):
'''
Decrypt File
Args:
filename: Pass the filename to encrypt.
Returns:
No return.
'''
if not os.path.exists(filename):
print "Invalid filename %s. Does not exist" % filename
return
... | 0.002959 |
def read(self, symbol, as_of=None, date_range=None, from_version=None, allow_secondary=None, **kwargs):
"""
Read data for the named symbol. Returns a VersionedItem object with
a data and metdata element (as passed into write).
Parameters
----------
symbol : `str`
... | 0.004677 |
def binary_dilation(x, radius=3):
"""Return fast binary morphological dilation of an image.
see `skimage.morphology.binary_dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_dilation>`__.
Parameters
-----------
x : 2D array
A binary image.
r... | 0.00381 |
def _make_dataset(cls, coords):
"""Construct a new dataset given the coordinates.
"""
class Slice(cls._SliceType):
extra_coords = coords
Slice.__name__ = '%s.slice(%s)' % (
cls.__name__,
', '.join('%s=%r' % item for item in coords.items()),
)
... | 0.005882 |
def readGraph(edgeList, nodeList = None, directed = False, idKey = 'ID', eSource = 'From', eDest = 'To'):
"""Reads the files given by _edgeList_ and _nodeList_ and creates a networkx graph for the files.
This is designed only for the files produced by metaknowledge and is meant to be the reverse of [writeGraph... | 0.006382 |
def _format_table(fmt, headers, rows, colwidths, colaligns):
"""Produce a plain-text representation of the table."""
lines = []
hidden = fmt.with_header_hide if headers else fmt.without_header_hide
pad = fmt.padding
headerrow = fmt.headerrow if fmt.headerrow else fmt.datarow
if fmt.lineabove an... | 0.000636 |
def draw_name(self, context, transparency, only_calculate_size=False):
"""Draws the name of the port
Offers the option to only calculate the size of the name.
:param context: The context to draw on
:param transparency: The transparency of the text
:param only_calculate_size: Wh... | 0.002942 |
def get_closest(self, sma):
"""
Return the `~photutils.isophote.Isophote` instance that has the
closest semimajor axis length to the input semimajor axis.
Parameters
----------
sma : float
The semimajor axis length.
Returns
-------
is... | 0.003788 |
def create_domain_smarthost(self, domainid, data):
"""Create a domain smarthost"""
return self.api_call(
ENDPOINTS['domainsmarthosts']['new'],
dict(domainid=domainid),
body=data) | 0.008696 |
def get(self, key):
"""
Get an entry from the cache by key.
@raise KeyError: if the given key is not present in the cache.
@raise CacheFault: (a L{KeyError} subclass) if the given key is present
in the cache, but the value it points to is gone.
"""
o = self.... | 0.001689 |
def get(self, request, bot_id, format=None):
"""
Get list of states
---
serializer: StateSerializer
responseMessages:
- code: 401
message: Not authenticated
"""
return super(StateList, self).get(request, bot_id, format) | 0.006645 |
def prepare_backend_environ(self, host, method, relative_url, headers, body,
source_ip, port):
"""Build an environ object for the backend to consume.
Args:
host: A string containing the host serving the request.
method: A string containing the HTTP method of the reques... | 0.002969 |
def add_word(self, word_id, url='https://api.shanbay.com/bdc/learning/'):
"""添加单词"""
data = {
'id': word_id
}
return self._request(url, method='post', data=data).json() | 0.009434 |
def get_mst(points):
"""
Parameters
----------
points : list of points (geometry.Point)
The first element of the list is the center of the bounding box of the
first stroke, the second one belongs to the seconds stroke, ...
Returns
-------
mst : square matrix
0 nodes ... | 0.001139 |
def shape_vecs(*args):
'''Reshape all ndarrays with ``shape==(n,)`` to ``shape==(n,1)``.
Recognizes ndarrays and ignores all others.'''
ret_args = []
flat_vecs = True
for arg in args:
if type(arg) is numpy.ndarray:
if len(arg.shape) == 1:
arg = shape_vec(arg)
... | 0.002336 |
def SetRowsCustomProperties(self, rows, custom_properties):
"""Sets the custom properties for given row(s).
Can accept a single row or an iterable of rows.
Sets the given custom properties for all specified rows.
Args:
rows: The row, or rows, to set the custom properties for.
custom_proper... | 0.005396 |
def fill_extents(self):
"""Computes a bounding box in user-space coordinates
covering the area that would be affected, (the "inked" area),
by a :meth:`fill` operation given the current path and fill parameters.
If the current path is empty,
returns an empty rectangle ``(0, 0, 0, ... | 0.001535 |
def _remove_existing(self):
"""
When a change is detected, remove keys that existed in the old file.
"""
for key in self._keys:
if key in os.environ:
LOG.debug('%r: removing old key %r', self, key)
del os.environ[key]
self._keys = [] | 0.006309 |
def has(self, decorated_function, *args, **kwargs):
""" Check if there is a result for given function
:param decorated_function: called function (original)
:param args: args with which function is called
:param kwargs: kwargs with which function is called
:return: None
"""
return self.get_cache(decorate... | 0.02514 |
def iter_files(self):
"""Iterate over files."""
# file_iter may be a callable or an iterator
if callable(self.file_iter):
return self.file_iter()
return iter(self.file_iter) | 0.009217 |
def get_packages(dname, pkgname=None, results=None, ignore=None, parent=None):
"""
Get all packages which are under dname. This is necessary for
Python 2.2's distutils. Pretty similar arguments to getDataFiles,
including 'parent'.
"""
parent = parent or ""
prefix = []
if parent:
... | 0.00303 |
def find_by_user(user_id, _connection=None, page_size=100, page_number=0,
sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER):
"""
List all videos uploaded by a certain user.
"""
return connection.ItemResultSet('find_videos_by_user_id',
Video, _connect... | 0.012563 |
def localize(date_time, time_zone):
"""Returns a datetime adjusted to a timezone:
* If dateTime is a naive datetime (datetime with no timezone information), timezone information is added but date
and time remains the same.
* If dateTime is not a naive datetime, a datetime object with new tzinfo att... | 0.005208 |
def _item_attributes_match(crypto_config, plaintext_item, encrypted_item):
# type: (CryptoConfig, Dict, Dict) -> Bool
"""Determines whether the unencrypted values in the plaintext items attributes are the same as those in the
encrypted item. Essentially this uses brute force to cover when we don't know the ... | 0.006122 |
def _connect_control(self, event, param, arg):
"""
Is the actual callback function for :meth:`init_hw_connect_control_ex`.
:param event:
Event (:data:`CbEvent.EVENT_CONNECT`, :data:`CbEvent.EVENT_DISCONNECT` or
:data:`CbEvent.EVENT_FATALDISCON`).
:param param: Ad... | 0.004128 |
def prepare(session_data={}, #pylint: disable=dangerous-default-value
passphrase=None):
"""
Returns *session_dict* as a base64 encrypted json string.
The full encrypted text is special crafted to be compatible
with openssl. It can be decrypted with:
$ echo _fu... | 0.004129 |
def get_sync_info(self, name, key=None):
"""Get mtime/size when this target's current dir was last synchronized with remote."""
peer_target = self.peer
if self.is_local():
info = self.cur_dir_meta.dir["peer_sync"].get(peer_target.get_id())
else:
info = peer_target... | 0.005682 |
def find_shows_by_category(self, category, genre=None, area=None,
release_year=None, paid=None,
orderby='view-today-count',
streamtypes=None, person=None,
page=1, count=20):
"""doc: http:/... | 0.006342 |
def current_resp_rate(self):
"""Return current respiratory rate for in-progress session."""
try:
rates = self.intervals[0]['timeseries']['respiratoryRate']
num_rates = len(rates)
if num_rates == 0:
return None
rate = rates[num_rates-1][1]... | 0.005141 |
def _parse_results(self, results, cached_records):
"""
Parses the given results (in MARCXML format).
The given "cached_records" list is a pool of
already existing parsed records (in order to
avoid keeping several times the same records in memory)
"""
parser = xml... | 0.004082 |
def _RemoveForemanRule(self):
"""Removes the foreman rule corresponding to this hunt."""
if data_store.RelationalDBEnabled():
data_store.REL_DB.RemoveForemanRule(hunt_id=self.session_id.Basename())
return
with aff4.FACTORY.Open(
"aff4:/foreman", mode="rw", token=self.token) as foreman:
... | 0.012281 |
def reset(self):
"""Reset the view."""
self.pan = (0., 0.)
self.zoom = self._default_zoom
self.update() | 0.014815 |
def resize(self, size):
""" Grow this array to specified length. This array can't be shrinked
:param size: new length
:return: None
"""
if size < len(self):
raise ValueError("Value is out of bound. Array can't be shrinked")
current_size = self.__size
for i in range(size - current_size):
self.__arra... | 0.030848 |
def cdk_module_matches_env(env_name, env_config, env_vars):
"""Return bool on whether cdk command should continue in current env."""
if env_config.get(env_name):
current_env_config = env_config[env_name]
if isinstance(current_env_config, type(True)) and current_env_config:
return Tru... | 0.001049 |
def fix_repeating_arguments(self):
"""Fix elements that should accumulate/increment values."""
either = [list(child.children) for child in transform(self).children]
for case in either:
for e in [child for child in case if case.count(child) > 1]:
if type(e) is Argument... | 0.002994 |
def install(pkg=None,
pkgs=None,
dir=None,
runas=None,
registry=None,
env=None,
dry_run=False,
silent=True):
'''
Install an NPM package.
If no directory is specified, the package will be installed globally. If
no packag... | 0.000349 |
def values_are_equivalent(self, val1, val2):
'''Check whether 2 values are equivalent (meaning they
are in the same bucket/range)
Returns:
true if the 2 values are equivalent
'''
return self.get_lowest_equivalent_value(val1) == self.get_lowest_equivalent_value(val2) | 0.009404 |
def wrap(self, text, width=None, indent=None):
"""Return ``text`` wrapped to ``width`` and indented with ``indent``.
By default:
* ``width`` is ``self.options.wrap_length``
* ``indent`` is ``self.indentation``.
"""
width = width if width is not None else self.options.w... | 0.003273 |
def plot_power_factor_mu(self, temp=600, output='eig',
relaxation_time=1e-14, xlim=None):
"""
Plot the power factor in function of Fermi level. Semi-log plot
Args:
temp: the temperature
xlim: a list of min and max fermi energy by default (0, ... | 0.00228 |
def cli_aliases(self):
r"""Developer script aliases.
"""
scripting_groups = []
aliases = {}
for cli_class in self.cli_classes:
instance = cli_class()
if getattr(instance, "alias", None):
scripting_group = getattr(instance, "scripting_group"... | 0.002298 |
def erase_all_breakpoints(self):
"""
Erases all breakpoints in all processes.
@see:
erase_code_breakpoint,
erase_page_breakpoint,
erase_hardware_breakpoint
"""
# This should be faster but let's not trust the GC so much :P
# self.disab... | 0.004363 |
def openOrder(self, orderId, contract, order, orderState):
"""
This wrapper is called to:
* feed in open orders at startup;
* feed in open orders or order updates from other clients and TWS
if clientId=master id;
* feed in manual orders and order updates from TWS if cl... | 0.001403 |
def verboselogs_class_transform(cls):
"""Make Pylint aware of our custom logger methods."""
if cls.name == 'RootLogger':
for meth in ['notice', 'spam', 'success', 'verbose']:
cls.locals[meth] = [scoped_nodes.Function(meth, None)] | 0.003891 |
def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, use_decimal=True,
namedtuple_as_object=True, tuple_as_array=True,
bigint_as_string=False, sort_keys=False, item_sort_key=... | 0.000362 |
def _generate_notebooks_by_category(notebook_object, dict_by_tag):
"""
Internal function that is used for generation of the page "Notebooks by Category".
----------
Parameters
----------
notebook_object : notebook object
Object of "notebook" class where the body will be created.
di... | 0.004172 |
def state(self, statespec=None):
"""
Modify or inquire widget state.
:param statespec: Widget state is returned if `statespec` is None,
otherwise it is set according to the statespec
flags and then a new state spec is returned
... | 0.007335 |
def update_allelic_expression(self, model=3):
"""
A single EM step: Update probability at read level and then re-estimate allelic specific expression
:param model: Normalization model (1: Gene->Allele->Isoform, 2: Gene->Isoform->Allele, 3: Gene->Isoform*Allele, 4: Gene*Isoform*Allele)
:... | 0.007692 |
def package(env, target, source, PACKAGEROOT, NAME, VERSION, DESCRIPTION,
SUMMARY, X_IPK_PRIORITY, X_IPK_SECTION, SOURCE_URL,
X_IPK_MAINTAINER, X_IPK_DEPENDS, **kw):
""" This function prepares the packageroot directory for packaging with the
ipkg builder.
"""
SCons.Tool.Tool('ipk... | 0.006837 |
def get_extreme_poe(array, imtls):
"""
:param array: array of shape (L, G) with L=num_levels, G=num_gsims
:param imtls: DictArray imt -> levels
:returns:
the maximum PoE corresponding to the maximum level for IMTs and GSIMs
"""
return max(array[imtls(imt).stop - 1].max() for imt in imtls... | 0.003115 |
def main():
"""
Commandline interface for building/inspecting top-k lexicons using during decoding.
"""
params = argparse.ArgumentParser(description="Create or inspect a top-k lexicon for use during decoding.")
subparams = params.add_subparsers(title="Commands")
params_create = subparams.add_pa... | 0.00579 |
def get_object_or_this(model, this=None, *args, **kwargs):
"""
Uses get() to return an object or the value of <this> argument
if object does not exist.
If the <this> argument if not provided None would be returned.
<model> can be either a QuerySet instance or a class.
"""
return get_object... | 0.002778 |
def _update_step2(self, layers):
"""Each layer has it's own ranges_grid computed now, unless something went wrong
But all layers are shown with the same ranges (self.state.ranges_viewport)
If any of the ranges is None, take the min/max of each layer
"""
logger.info("done with ran... | 0.007199 |
def persist_upstream_structure(self):
"""Persist json file with the upstream steps structure, that is step names and their connections."""
persist_dir = os.path.join(self.experiment_directory, '{}_upstream_structure.json'.format(self.name))
logger.info('Step {}, saving upstream pipeline structur... | 0.011962 |
def from_bytes(SproutTx, byte_string):
'''
byte-like -> SproutTx
'''
version = byte_string[0:4]
tx_ins = []
tx_ins_num = shared.VarInt.from_bytes(byte_string[4:])
current = 4 + len(tx_ins_num)
for _ in range(tx_ins_num.number):
tx_in = TxIn.fr... | 0.001136 |
def twoline2rv(longstr1, longstr2, whichconst, afspc_mode=False):
"""Return a Satellite imported from two lines of TLE data.
Provide the two TLE lines as strings `longstr1` and `longstr2`,
and select which standard set of gravitational constants you want
by providing `gravity_constants`:
`sgp4.ear... | 0.011974 |
def set_hemisphere(self, hemi_str):
'''
Given a hemisphere identifier, set the sign of the coordinate to match that hemisphere
'''
if hemi_str == 'W':
self.degree = abs(self.degree)*-1
self.minute = abs(self.minute)*-1
self.second = abs(self.second)*-1... | 0.006339 |
def _add_new_init_method(cls):
"""
Replace the existing cls.__init__() method with a new one
which calls the original one and in addition performs the
following actions:
(1) Finds all instances of tohu.BaseGenerator in the namespace
and collects them in the dictionary `self.field_gens`.
... | 0.00312 |
def get_engine(name):
"""
get an engine from string (engine class without Engine)
"""
name = name.capitalize() + 'Engine'
if name in globals():
return globals()[name]
raise KeyError("engine '%s' does not exist" % name) | 0.003968 |
def check_block_spacing(
self,
first_block_type: LineType,
second_block_type: LineType,
error_message: str,
) -> typing.Generator[AAAError, None, None]:
"""
Checks there is a clear single line between ``first_block_type`` and
``second_block_type``.
No... | 0.003472 |
def verification_digit(numbers):
"""
Returns the verification digit for a given numbre.
The verification digit is calculated as follows:
* A = sum of all even-positioned numbers
* B = A * 3
* C = sum of all odd-positioned numbers
* D = B + C
* The result... | 0.002404 |
def _read_http_ping(self, size, kind, flag):
"""Read HTTP/2 PING frames.
Structure of HTTP/2 PING frame [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+---------------+
... | 0.002023 |
def _delete(self, url, data, scope):
"""
Make a DELETE request using the session object to a Degreed endpoint.
Args:
url (str): The url to send a DELETE request to.
data (str): The json encoded payload to DELETE.
scope (str): Must be one of the scopes Degreed... | 0.003401 |
def clean_upload(self, query='/content/uploads/'):
"""
pulp leaves droppings if you don't specifically tell it
to clean up after itself. use this to do so.
"""
query = query + self.uid + '/'
_r = self.connector.delete(query)
if _r.status_code == Constants.PULP_DE... | 0.004444 |
def can_transfer(self, block_identifier: BlockSpecification) -> bool:
""" Returns True if the channel is opened and the node has deposit in it. """
return self.token_network.can_transfer(
participant1=self.participant1,
participant2=self.participant2,
block_identifier... | 0.007426 |
def sample_measurement_ops(
self,
measurement_ops: List[ops.GateOperation],
repetitions: int = 1) -> Dict[str, np.ndarray]:
"""Samples from the system at this point in the computation.
Note that this does not collapse the wave function.
In contrast to `sampl... | 0.001331 |
def get_single_external_tool_courses(self, course_id, external_tool_id):
"""
Get a single external tool.
Returns the specified external tool.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["cou... | 0.004926 |
def SignedVarintEncode(value):
"""Encode a signed integer as a zigzag encoded signed integer."""
result = b""
if value < 0:
value += (1 << 64)
bits = value & 0x7f
value >>= 7
while value:
result += HIGH_CHR_MAP[bits]
bits = value & 0x7f
value >>= 7
result += CHR_MAP[bits]
return result | 0.028125 |
def proportion_merge(brands, exemplars):
""" Return the proportion of a brand's followers who also follower an
exemplar. We merge all exemplar followers into one big pseudo-account."""
scores = {}
exemplar_followers = set()
for followers in exemplars.values():
exemplar_followers |= followers... | 0.002262 |
def get_message(self, transport, http_version: str, method: bytes,
url: bytes, headers: List[List[bytes]]) -> Dict[str, Any]:
'''
http://channels.readthedocs.io/en/stable/asgi/www.html#request
'''
url_obj = parse_url(url)
if url_obj.schema is None:
... | 0.002593 |
def _detail_participant(
self,
channel_identifier: ChannelID,
participant: Address,
partner: Address,
block_identifier: BlockSpecification,
) -> ParticipantDetails:
""" Returns a dictionary with the channel participant information. """
dat... | 0.002747 |
def view(self, viewer=None, use_curr_dir=False):
"""View your molecule.
.. note:: This function writes a temporary file and opens it with
an external viewer.
If you modify your molecule afterwards you have to recall view
in order to see the changes.
Args:
... | 0.001203 |
def dump_private_keys_or_addrs_chooser(wallet_obj):
'''
Offline-enabled mechanism to dump everything
'''
if wallet_obj.private_key:
puts('Which private keys and addresses do you want?')
else:
puts('Which addresses do you want?')
with indent(2):
puts(colored.cyan('1: Acti... | 0.00494 |
def from_transform(cls, matrix):
r"""
:param matrix: 4x4 3d affine transform matrix
:type matrix: :class:`FreeCAD.Matrix`
:return: a unit, zero offset coordinate system transformed by the given matrix
:rtype: :class:`CoordSystem`
Individual rotation & translation matrici... | 0.00307 |
def make_library(self, diffuse_yaml, catalog_yaml, binning_yaml):
""" Build up the library of all the components
Parameters
----------
diffuse_yaml : str
Name of the yaml file with the library of diffuse component definitions
catalog_yaml : str
Name of t... | 0.006928 |
def other_object_webhook_handler(event):
"""Handle updates to transfer, charge, invoice, invoiceitem, plan, product and source objects.
Docs for:
- charge: https://stripe.com/docs/api#charges
- coupon: https://stripe.com/docs/api#coupons
- invoice: https://stripe.com/docs/api#invoices
- invoiceitem: https://stri... | 0.027695 |
def find_malformed_single_file_project(self): # type: () -> List[str]
"""
Take first non-setup.py python file. What a mess.
:return:
"""
files = [f for f in os.listdir(".") if os.path.isfile(f)]
candidates = []
# project misnamed & not in setup.py
for f... | 0.003003 |
def _raw_open(self, flags, mode=0o777):
"""
Open the file pointed by this path and return a file descriptor,
as os.open() does.
"""
if self._closed:
self._raise_closed()
return self._accessor.open(self, flags, mode) | 0.007273 |
def load_or_create_config(self, filename, config=None):
"""Loads a config from disk. Defaults to a random config if none is specified"""
os.makedirs(os.path.dirname(os.path.expanduser(filename)), exist_ok=True)
if os.path.exists(filename):
return self.load(filename)
if(conf... | 0.011547 |
def create(cls, api_context, public_key_string):
"""
:type api_context: bunq.sdk.context.ApiContext
:type public_key_string: str
:rtype: client.BunqResponse[Installation]
"""
api_client = client.ApiClient(api_context)
body_bytes = cls.generate_request_body_bytes... | 0.004016 |
def ssa(scatterer, h_pol=True):
"""Single-scattering albedo for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The single-scattering albedo... | 0.004405 |
def main(argv):
"""This function sets up a command-line option parser and then calls match_and_print
to do all of the real work.
"""
import argparse
description = 'Uses Open Tree of Life web services to try to find a taxon ID for each name supplied. ' \
'Using a --context-name=NAME... | 0.006006 |
def get_weights(self):
"""Returns a dictionary containing the weights of the network.
Returns:
Dictionary mapping variable names to their weights.
"""
self._check_sess()
return {
k: v.eval(session=self.sess)
for k, v in self.variables.items()
... | 0.006079 |
def blog_months(*args):
"""
Put a list of dates for blog posts into the template context.
"""
dates = BlogPost.objects.published().values_list("publish_date", flat=True)
date_dicts = [{"date": datetime(d.year, d.month, 1)} for d in dates]
month_dicts = []
for date_dict in date_dicts:
... | 0.001876 |
def create_scrolled_window(self, layout_manager, horizontal=Gtk.PolicyType.NEVER, vertical=Gtk.PolicyType.ALWAYS):
"""
Function creates a scrolled window with layout manager
"""
scrolled_window = Gtk.ScrolledWindow()
scrolled_window.add(layout_manager)
scrolled_window.set... | 0.007895 |
def main():
"""
Print lines of input along with output.
"""
source_lines = (line.rstrip() for line in sys.stdin)
console = InteractiveInterpreter()
console.runsource('import turicreate')
source = ''
try:
while True:
source = source_lines.next()
more = cons... | 0.001506 |
def delete(queue_id):
'''
Delete message(s) from the mail queue
CLI Example:
.. code-block:: bash
salt '*' postfix.delete 5C33CA0DEA
salt '*' postfix.delete ALL
'''
ret = {'message': '',
'result': True
}
if not queue_id:
log.error('Require... | 0.002379 |
def glyph_order(keys, draw_order=[]):
"""
Orders a set of glyph handles using regular sort and an explicit
sort order. The explicit draw order must take the form of a list
of glyph names while the keys should be glyph names with a custom
suffix. The draw order may only match subset of the keys and a... | 0.002994 |
def search_normalize(self, results):
"""Append user id to search results to be able to initialize found
:class:`User` successfully
"""
for sshkey in results:
sshkey[u'user_id'] = self.user.id # pylint:disable=no-member
return super(SSHKey, self).search_normalize(resu... | 0.006173 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.