text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _create_image_url(self, file_path, type_, target_size):
"""The the closest available size for specified image type.
Arguments:
file_path (:py:class:`str`): The image file path.
type_ (:py:class:`str`): The type of image to create a URL
for, (``'poster'`` or ``'profil... | 0.002656 |
def round_linestring_coords(ls, precision):
"""
Round the coordinates of a shapely LineString to some decimal precision.
Parameters
----------
ls : shapely LineString
the LineString to round the coordinates of
precision : int
decimal precision to round coordinates to
Return... | 0.004566 |
def clear(self):
"""
Clears out all the items from this tab bar.
"""
self.blockSignals(True)
items = list(self.items())
for item in items:
item.close()
self.blockSignals(False)
self._currentIndex = -1
self.currentIndexChanged.emit(self... | 0.00597 |
def progress(rest):
"Display the progress of something: start|end|percent"
if rest:
left, right, amount = [piece.strip() for piece in rest.split('|')]
ticks = min(int(round(float(amount) / 10)), 10)
bar = "=" * ticks
return "%s [%-10s] %s" % (left, bar, right) | 0.025926 |
def iter_links(self):
# type: () -> Iterable[Link]
"""Yields all links in the page"""
document = html5lib.parse(
self.content,
transport_encoding=_get_encoding_from_headers(self.headers),
namespaceHTMLElements=False,
)
base_url = _determine_bas... | 0.004027 |
def get_updates(self, offset=None, limit=None, timeout=None):
"""
Use this method to receive incoming updates using long polling (wiki).
An Array of Update objects is returned.
"""
payload = dict(offset=offset, limit=limit, timeout=timeout)
return self._get('getUp... | 0.008929 |
def disconnect_layer_listener(self):
"""Destroy the signal/slot to listen for layers loaded in QGIS.
..seealso:: connect_layer_listener
"""
project = QgsProject.instance()
project.layersWillBeRemoved.disconnect(self.get_layers)
project.layersAdded.disconnect(self.get_lay... | 0.003802 |
def encrypt_assertion(self, statement, enc_key, template, key_type='des-192', node_xpath=None, node_id=None):
"""
Will encrypt an assertion
:param statement: A XML document that contains the assertion to encrypt
:param enc_key: File name of a file containing the encryption key
:... | 0.002085 |
def unset_state(self):
"""
Resets the state required for this actor to the default state.
Currently only disables the target of the texture of the material, it may still be bound.
"""
glDisable(self.region.material.target)
self.region.bone.unsetRotate(self.data) | 0.012539 |
def concatechain(*generators: types.FrameGenerator, separator: str = ''):
"""Return a generator that in each iteration takes one value from each of the
supplied generators, joins them together with the specified separator and
yields the result. Stops as soon as any iterator raises StopIteration and
retu... | 0.001938 |
def _update_limits_from_api(self):
"""
Query DynamoDB's DescribeLimits API action, and update limits
with the quotas returned. Updates ``self.limits``.
"""
self.connect()
logger.info("Querying DynamoDB DescribeLimits for limits")
# no need to paginate
lims... | 0.002186 |
def authenticate_nova_user(self, keystone, user, password, tenant):
"""Authenticates a regular user with nova-api."""
self.log.debug('Authenticating nova user ({})...'.format(user))
ep = keystone.service_catalog.url_for(service_type='identity',
inter... | 0.001992 |
def fast_combine_pairs(files, force_single, full_name, separators):
"""
assume files that need to be paired are within 10 entries of each other, once the list is sorted
"""
files = sort_filenames(files)
chunks = tz.sliding_window(10, files)
pairs = [combine_pairs(chunk, force_single, full_name, ... | 0.003722 |
def init(*, threshold_lvl=1, quiet_stdout=False, log_file):
"""
Initiate the log module
:param threshold_lvl: messages under this level won't be issued/logged
:param to_stdout: activate stdout log stream
"""
global _logger, _log_lvl
# translate lvl to those used by 'logging' module
_lo... | 0.001135 |
def belu(x):
"""Bipolar ELU as in https://arxiv.org/abs/1709.04054."""
x_shape = shape_list(x)
x1, x2 = tf.split(tf.reshape(x, x_shape[:-1] + [-1, 2]), 2, axis=-1)
y1 = tf.nn.elu(x1)
y2 = -tf.nn.elu(-x2)
return tf.reshape(tf.concat([y1, y2], axis=-1), x_shape) | 0.025735 |
def ExecuteQuery(self, query, args=None):
"""Get connection from pool and execute query."""
def Action(connection):
connection.cursor.execute(query, args)
rowcount = connection.cursor.rowcount
results = connection.cursor.fetchall()
return results, rowcount
return self._RetryWrapper... | 0.015244 |
def IntegerDifference(left: vertex_constructor_param_types, right: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
Subtracts one vertex from another
:param left: the vertex to be subtracted from
:param right: the vertex to subtract
"""
return Integer(context.jvm_vi... | 0.014388 |
def mime(self):
'''
Retrieves mime metadata if available
:return:
'''
return self.metadata['ContentType'] if 'ContentType' in self.metadata else BaseEngine.get_mimetype(self.buffer) | 0.013575 |
async def get_counts(self):
"""
see :class:`datasketch.MinHashLSH`.
"""
fs = (hashtable.itemcounts() for hashtable in self.hashtables)
return await asyncio.gather(*fs) | 0.009662 |
def killJobs(self, jobsToKill):
"""
Kills the given set of jobs and then sends them for processing
"""
if len(jobsToKill) > 0:
self.batchSystem.killBatchJobs(jobsToKill)
for jobBatchSystemID in jobsToKill:
self.processFinishedJob(jobBatchSystemID, ... | 0.006211 |
def partial_steps_data(self, start=0):
"""
Iterates 5 steps from start position and
provides tuple for packing into buffer.
returns (0, 0) if stpe doesn't exist.
:param start: Position to start from (typically 0 or 5)
:yield: (setting, duration)
"""
cnt ... | 0.003311 |
def max_rigid_id(self):
"""Returns the maximum rigid body ID contained in the Compound.
This is usually used by compound.root to determine the maximum
rigid_id in the containment hierarchy.
Returns
-------
int or None
The maximum rigid body ID contained in t... | 0.003339 |
def generate_private_key(key_type):
"""
Generate a random private key using sensible parameters.
:param str key_type: The type of key to generate. One of: ``rsa``.
"""
if key_type == u'rsa':
return rsa.generate_private_key(
public_exponent=65537, key_size=2048, backend=default_b... | 0.002778 |
def errors(self):
"""
Get the errors of the tag.
If invalid then the list will consist of errors containing each a code and message explaining the error.
Each error also refers to the respective (sub)tag(s).
:return: list of errors of the tag. If the tag is valid, it returns an ... | 0.002865 |
def set_client_params(
self, start_unsubscribed=None, clear_on_exit=None, unsubscribe_on_reload=None,
announce_interval=None):
"""Sets subscribers related params.
:param bool start_unsubscribed: Configure subscriptions but do not send them.
.. note:: Useful with mast... | 0.008264 |
def Execute(self, message):
"""This function parses the RDFValue from the server.
The Run method will be called with the specified RDFValue.
Args:
message: The GrrMessage that we are called to process.
Returns:
Upon return a callback will be called on the server to register
th... | 0.007035 |
def instruction_BVS(self, opcode, ea):
"""
Tests the state of the V (overflow) bit and causes a branch if it is
set. That is, branch if the twos complement result was invalid. When
used after an operation on twos complement binary values, this
instruction will branch if there was... | 0.007657 |
def thumbnail(self):
"""
Returns a thumbnail image in PIL.Image. When the file does not
contain an embedded thumbnail image, returns None.
"""
if 'THUMBNAIL_RESOURCE' in self.image_resources:
return pil_io.convert_thumbnail_to_pil(
self.image_resources... | 0.003373 |
def MPTfileCSV(file_or_path):
"""Simple function to open MPT files as csv.DictReader objects
Checks for the correct headings, skips any comments and returns a
csv.DictReader object and a list of comments
"""
if isinstance(file_or_path, str):
mpt_file = open(file_or_path, 'r')
else:
... | 0.0027 |
def demultiplex_samples(fastq, out_dir, nedit, barcodes):
''' Demultiplex a fastqtransformed FASTQ file into a FASTQ file for
each sample.
'''
annotations = detect_fastq_annotations(fastq)
re_string = construct_transformed_regex(annotations)
parser_re = re.compile(re_string)
if barcodes:
... | 0.000553 |
def _call(self, x):
"""Apply the functional to the given point."""
return (self.functional(x) +
self.quadratic_coeff * x.inner(x) +
x.inner(self.linear_term) + self.constant) | 0.009009 |
def calc_pvalue(self, study_count, study_n, pop_count, pop_n):
"""pvalues are calculated in derived classes."""
fnc_call = "calc_pvalue({SCNT}, {STOT}, {PCNT} {PTOT})".format(
SCNT=study_count, STOT=study_n, PCNT=pop_count, PTOT=pop_n)
raise Exception("NOT IMPLEMENTED: {FNC_CALL} usi... | 0.005141 |
def infer(msg, mrar=False):
"""Estimate the most likely BDS code of an message.
Args:
msg (String): 28 bytes hexadecimal message string
mrar (bool): Also infer MRAR (BDS 44) and MHR (BDS 45). Defaults to False.
Returns:
String or None: BDS version, or possible versions, or None if ... | 0.001568 |
def count_multiplicities(times, tmax=20):
"""Calculate an array of multiplicities and corresponding coincidence IDs
Note that this algorithm does not take care about DOM IDs, so it has to
be fed with DOM hits.
Parameters
----------
times: array[float], shape=(n,)
Hit times for n hits
... | 0.00099 |
def stop_if(expr, msg='', no_output=False):
'''Abort the execution of the current step or loop and yield
an warning message `msg` if `expr` is False '''
if expr:
raise StopInputGroup(msg=msg, keep_output=not no_output)
return 0 | 0.003984 |
def segment_tripoints(self, ratio=0.33333):
"""
Identify the trisection points of every line segment in the triangulation
"""
segments = self.identify_segments()
points = self.points
mids1 = ratio * points[segments[:,0]] + (1.0-ratio) * points[segments[:,1]]
mid... | 0.024922 |
def delete_project_actors(self, project_key, role_id, actor, actor_type=None):
"""
Deletes actors (users or groups) from a project role.
Delete a user from the role: /rest/api/2/project/{projectIdOrKey}/role/{roleId}?user={username}
Delete a group from the role: /rest/api/2/project/{proj... | 0.006764 |
def snapshots(self):
"""
Get all Volumes of type Snapshot. Updates every time - no caching.
:return: a `list` of all the `ScaleIO_Volume` that have a are of type Snapshot.
:rtype: list
"""
self.connection._check_login()
response = self.connection._do_get("{}/{}".... | 0.007776 |
def realtimeBar(self, reqId, time, open, high, low, close, volume, wap, count):
"""realtimeBar(EWrapper self, TickerId reqId, long time, double open, double high, double low, double close, long volume, double wap, int count)"""
return _swigibpy.EWrapper_realtimeBar(self, reqId, time, open, high, low, cl... | 0.011628 |
def format_trigger(self, stream):
"""Create a user understandable string like count(stream) >= X.
Args:
stream (DataStream): The stream to use to format ourselves.
Returns:
str: The formatted string
"""
src = u'value'
if self.use_count:
... | 0.007075 |
def _wrapNavFrag(self, frag, useAthena):
"""
Wrap the given L{INavigableFragment} in an appropriate
L{_FragmentWrapperMixin} subclass.
"""
username = self._privateApplication._getUsername()
cf = getattr(frag, 'customizeFor', None)
if cf is not None:
fr... | 0.003155 |
def dist_percentile_threshold(dist_matrix, perc_thr=0.05, k=1):
"""Thresholds a distance matrix and returns the result.
Parameters
----------
dist_matrix: array_like
Input array or object that can be converted to an array.
perc_thr: float in range of [0,100]
Pe... | 0.003576 |
def _add_new_spawn_method(cls):
"""
TODO
"""
def new_spawn_method(self, dependency_mapping):
# TODO/FIXME: Check that this does the right thing:
# (i) the spawned generator is independent of the original one (i.e. they can be reset independently without altering the other's behaviour)
... | 0.009091 |
def _other_to_dict(self, other):
"""When serializing models, this allows attached models (children, parents, etc.) to also be
serialized.
"""
if isinstance(other, ModelBase):
return other.to_dict()
elif isinstance(other, list):
# TODO: what if it's not a list?
return [self._other_t... | 0.016043 |
def SqueezeNet(include_top=True, weights='imagenet',
input_tensor=None, input_shape=None,
pooling=None,
classes=1000):
"""Instantiates the SqueezeNet architecture.
"""
if weights not in {'imagenet', None}:
raise ValueError('The `weights` argument... | 0.00349 |
def get_float(prompt=None):
"""
Read a line of text from standard input and return the equivalent float
as precisely as possible; if text does not represent a double, user is
prompted to retry. If line can't be read, return None.
"""
while True:
s = get_string(prompt)
if s is Non... | 0.001582 |
def running_apps(self):
"""Return a list of running user applications."""
ps = self.adb_shell(RUNNING_APPS_CMD)
if ps:
return [line.strip().rsplit(' ', 1)[-1] for line in ps.splitlines() if line.strip()]
return [] | 0.011673 |
def case_report_content(store, institute_obj, case_obj):
"""Gather contents to be visualized in a case report
Args:
store(adapter.MongoAdapter)
institute_obj(models.Institute)
case_obj(models.Case)
Returns:
data(dict)
"""
variant_types = {
'causatives_detai... | 0.002545 |
def get_rounded(self, digits):
""" Return a vector with the elements rounded to the given number of digits. """
result = self.copy()
result.round(digits)
return result | 0.015075 |
def request(input, representation, resolvers=None, get3d=False, tautomers=False, **kwargs):
"""Make a request to CIR and return the XML response.
:param string input: Chemical identifier to resolve
:param string representation: Desired output representation
:param list(string) resolvers: (Optional) Ord... | 0.004535 |
def callproc(self, procname, parameters=()):
"""
Call a stored procedure with the given name.
:param procname: The name of the procedure to call
:type procname: str
:keyword parameters: The optional parameters for the procedure
:type parameters: sequence
"""
... | 0.005063 |
def get_scenarios(network_id,**kwargs):
"""
Get all the scenarios in a given network.
"""
user_id = kwargs.get('user_id')
try:
net_i = db.DBSession.query(Network).filter(Network.id == network_id).one()
net_i.check_read_permission(user_id=user_id)
except NoResultFound:
... | 0.009662 |
def shrink(self):
"""
Calculate the Constant-Correlation covariance matrix.
:return: shrunk sample covariance matrix
:rtype: np.ndarray
"""
x = np.nan_to_num(self.X.values)
# de-mean returns
t, n = np.shape(x)
meanx = x.mean(axis=0)
x = x... | 0.001444 |
def get_sortkey(table):
"""Get a field to sort by
"""
# Just pick the first column in the table in alphabetical order.
# Ideally we would get the primary key from bcdc api, but it doesn't
# seem to be available
wfs = WebFeatureService(url=bcdata.OWS_URL, version="2.0.0")
return sorted(wfs.ge... | 0.00271 |
def check_rollout(edits_service, package_name, days):
"""Check if package_name has a release on staged rollout for too long"""
edit = edits_service.insert(body={}, packageName=package_name).execute()
response = edits_service.tracks().get(editId=edit['id'], track='production', packageName=package_name).execu... | 0.006148 |
def get_color_mode(mode):
"""Convert PIL mode to ColorMode."""
name = mode.upper()
name = name.rstrip('A') # Trim alpha.
name = {'1': 'BITMAP', 'L': 'GRAYSCALE'}.get(name, name)
return getattr(ColorMode, name) | 0.004348 |
def word2vec(
train,
output,
size=100,
window=5,
sample="1e-3",
hs=0,
negative=5,
threads=12,
iter_=5,
min_count=5,
alpha=0.025,
debug=2,
binary=1,
cbow=1,
save_vocab=None,
read_vocab=None,
... | 0.000341 |
def t_OPTION_AND_VALUE(self, t):
r'[^ \n\r\t=#]+[ \t=]+[^\r\n#]+' # TODO(etingof) escape hash
if t.value.endswith('\\'):
t.lexer.multiline_newline_seen = False
t.lexer.code_start = t.lexer.lexpos - len(t.value)
t.lexer.begin('multiline')
return
l... | 0.002315 |
def retire_subjects(self, subjects, reason='other'):
"""
Retires subjects in this workflow.
- **subjects** can be a list of :py:class:`Subject` instances, a list
of subject IDs, a single :py:class:`Subject` instance, or a single
subject ID.
- **reason** gives the rea... | 0.004283 |
def _create_storage_folder(self):
'''
Creates a storage folder using the query name by replacing
spaces in the query with '_' (underscore)
'''
try:
print(colored('\nCreating Storage Folder...', 'yellow'))
self._storageFolder = os.path.join(
... | 0.002558 |
def prepare_params(modeline, fileconfig, options):
"""Prepare and merge a params from modelines and configs.
:return dict:
"""
params = dict(skip=False, ignore=[], select=[], linters=[])
if options:
params['ignore'] = list(options.ignore)
params['select'] = list(options.select)
... | 0.001316 |
def add_to_path(p):
'''
Adds a path to python paths and removes it after the 'with' block ends
'''
old_path = sys.path
if p not in sys.path:
sys.path = sys.path[:]
sys.path.insert(0, p)
try:
yield
finally:
sys.path = old_path | 0.00346 |
def delete_observation(observation_id: int, access_token: str) -> List[Dict[str, Any]]:
"""
Delete an observation.
:param observation_id:
:param access_token:
:return:
"""
headers = _build_auth_header(access_token)
headers['Content-type'] = 'application/json'
response = requests.d... | 0.006873 |
def slugify(value, allow_unicode=False):
"""
Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.
Remove characters that aren't alphanumerics, underscores, or hyphens.
Convert to lowercase. Also strip leading and trailing whitespace.
Copyright: https://docs.djangoproject.com/en/1... | 0.010369 |
def _folder_item_remarks(self, analysis_brain, item):
"""Renders the Remarks field for the passed in analysis
If the edition of the analysis is permitted, adds the field into the
list of editable fields.
:param analysis_brain: Brain that represents an analysis
:param item: anal... | 0.003356 |
def getAddressBinding(self):
"""A convenience method to obtain the extension element used
as the address binding for the port."""
for item in self.extensions:
if isinstance(item, SoapAddressBinding) or \
isinstance(item, HttpAddressBinding):
return i... | 0.004878 |
def order_by(self, *colnames):
"""
orders the result set.
ordering can only use clustering columns.
Default order is ascending, prepend a '-' to the column name for descending
"""
if len(colnames) == 0:
clone = copy.deepcopy(self)
clone._order = [... | 0.00678 |
def set_images(self, images):
"""
Set the images in this album.
:param images: A list of the images we want the album to contain.
Can be Image objects, ids or a combination of the two. Images that
images that you cannot set (non-existing or not owned by you) will
... | 0.003077 |
def STEL(CASRN, AvailableMethods=False, Method=None): # pragma: no cover
'''This function handles the retrieval of Short-term Exposure Limit on
worker exposure to dangerous chemicals.
This API is considered experimental, and is expected to be removed in a
future release in favor of a more complete obj... | 0.001443 |
def format(self, message_format):
"""
Set the message format
:param message_format: The format to set
:type message_format: str
"""
if message_format not in self.formats:
self._log.error('Invalid Message format specified: {format}'.format(format=message_forma... | 0.008457 |
def extract_gzip (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a GZIP archive with the gzip Python module."""
targetname = util.get_single_outfile(outdir, archive)
try:
with gzip.GzipFile(archive) as gzipfile:
with open(targetname, 'wb') as targetfile:
... | 0.003082 |
def rectwidth(self, wavelengths=None):
"""Calculate :ref:`bandpass rectangular width <synphot-formula-rectw>`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed... | 0.002484 |
def snr_ratio(in1, in2):
"""
The following function simply calculates the signal to noise ratio between two signals.
INPUTS:
in1 (no default): Array containing values for signal 1.
in2 (no default): Array containing values for signal 2.
OUTPUTS:
out1 ... | 0.006316 |
def delete(self):
"""Del or Backspace pressed. Delete selection"""
with self._qpart:
for cursor in self.cursors():
if cursor.hasSelection():
cursor.deleteChar() | 0.008929 |
def get_code(self, *args, **kwargs):
"""
get the python source code from callback
"""
# FIXME: Honestly should allow multiple commands
callback = self._commands[args[0]]
# TODO: syntax color would be nice
source = _inspect.getsourcelines(callback)[0]
"""
source_len = len(source)
... | 0.002222 |
def get_mim_phenotypes(genemap_lines):
"""Get a dictionary with phenotypes
Use the mim numbers for phenotypes as keys and phenotype information as
values.
Args:
genemap_lines(iterable(str))
Returns:
phenotypes_found(dict): A dictionary with mim_numbers as keys and
... | 0.004673 |
def digit(m: Union[int, pd.Series], n: int) -> Union[int, pd.Series]:
"""Returns the nth digit of each number in m."""
return (m // (10 ** n)) % 10 | 0.01227 |
def get_model(name, dataset_name='wikitext-2', **kwargs):
"""Returns a pre-defined model by name.
Parameters
----------
name : str
Name of the model.
dataset_name : str or None, default 'wikitext-2'.
The dataset name on which the pre-trained model is trained.
For language mo... | 0.004315 |
def intercom_user_hash(data):
"""
Return a SHA-256 HMAC `user_hash` as expected by Intercom, if configured.
Return None if the `INTERCOM_HMAC_SECRET_KEY` setting is not configured.
"""
if getattr(settings, 'INTERCOM_HMAC_SECRET_KEY', None):
return hmac.new(
key=_hashable_bytes(s... | 0.00207 |
def check_grandparents(self, mother = None, father = None):
"""
Check if there are any grand parents.
Set the grandparents id:s
Arguments:
mother (Individual): An Individual object that represents the mother
father (Individual): An Individual obj... | 0.017435 |
def flag(name=None):
"""
Creates the grammar for a Flag (F) field, accepting only 'Y', 'N' or 'U'.
:param name: name for the field
:return: grammar for the flag field
"""
if name is None:
name = 'Flag Field'
# Basic field
field = pp.Regex('[YNU]')
# Name
field.setName... | 0.002681 |
def initial_validation(request, prefix):
"""
Returns the related model instance and post data to use in the
comment/rating views below.
Both comments and ratings have a ``prefix_ACCOUNT_REQUIRED``
setting. If this is ``True`` and the user is unauthenticated, we
store their post data in their se... | 0.000498 |
def chunks(iterable, chunksize, cast=tuple):
# type: (Iterable, int, Callable) -> Iterable
"""
Yields items from an iterator in iterable chunks.
"""
it = iter(iterable)
while True:
yield cast(itertools.chain([next(it)],
itertools.islice(it, chunksize - 1))) | 0.003205 |
def list_consumers(self, publisher_id=None):
"""ListConsumers.
Get a list of available service hook consumer services. Optionally filter by consumers that support at least one event type from the specific publisher.
:param str publisher_id:
:rtype: [Consumer]
"""
query_pa... | 0.007519 |
def stop(self):
"""Stop the underlying :class:`SparkContext`.
"""
self._sc.stop()
# We should clean the default session up. See SPARK-23228.
self._jvm.SparkSession.clearDefaultSession()
self._jvm.SparkSession.clearActiveSession()
SparkSession._instantiatedSession ... | 0.00542 |
def match(ctx, features, profile, gps_precision):
"""Mapbox Map Matching API lets you use snap your GPS traces
to the OpenStreetMap road and path network.
$ mapbox mapmatching trace.geojson
An access token is required, see `mapbox --help`.
"""
access_token = (ctx.obj and ctx.obj.get('access_token'))... | 0.001056 |
def setValue( self, value ):
"""
Moves the line to the given value and rebuilds it
:param value | <variant>
"""
scene = self.scene()
point = scene.mapFromChart(value, None)
self.setPos(point.x(), self.pos().y())
self.rebuil... | 0.017699 |
def getPositionFromState(pState):
"""Return the position of a particle given its state dict.
Parameters:
--------------------------------------------------------------
retval: dict() of particle position, keys are the variable names,
values are their positions
"""
result =... | 0.004454 |
def add_camera_make_model(self, make, model):
''' Add camera make and model.'''
self._ef['0th'][piexif.ImageIFD.Make] = make
self._ef['0th'][piexif.ImageIFD.Model] = model | 0.010256 |
def _post_init(self):
"""Call the find devices method for the relevant platform."""
if WIN:
self._find_devices_win()
elif MAC:
self._find_devices_mac()
else:
self._find_devices()
self._update_all_devices()
if NIX:
self._find... | 0.006116 |
def _divide_heigths(self, cli, write_position):
"""
Return the heights for all rows.
Or None when there is not enough space.
"""
if not self.children:
return []
# Calculate heights.
given_dimensions = self.get_dimensions(cli) if self.get_dimensions el... | 0.003579 |
def make_three_color(data, time, step, config, shape=(1280, 1280), lower_val=(0, 0, 0), upper_val=(2.5, 2.5, 2.5)):
"""
create a three color image according to the config file
:param data: a dictionary of fetched data where keys correspond to products
:param config: a config object
:param shape: the... | 0.004878 |
def reject(self, pn_condition=None):
"""See Link Reject, AMQP1.0 spec."""
self._pn_link.source.type = proton.Terminus.UNSPECIFIED
super(SenderLink, self).reject(pn_condition) | 0.010101 |
def expire_hit(self, hitid):
''' Expire HIT '''
if not self.connect_to_turk():
return False
try:
self.mtc.update_expiration_for_hit(
HITId=hitid,
ExpireAt=datetime.datetime.now()
)
return True
except Exceptio... | 0.004454 |
def busmap_from_psql(network, session, scn_name):
""" Retrieves busmap from `model_draft.ego_grid_pf_hv_busmap` on the
<OpenEnergyPlatform>[www.openenergy-platform.org] by a given scenario
name. If this busmap does not exist, it is created with default values.
Parameters
----------
network : py... | 0.000789 |
def draw_rect(self, pos, size, color, fillcolor=None):
"""
Draw a rectangle with the given color on the screen and optionally fill it with fillcolor.
:param pos: Top left corner of the rectangle
:param size: Sieze of the rectangle
:param color: Color for borders
:param f... | 0.00273 |
def get_users_for_sis_course_id(self, sis_course_id, params={}):
"""
Returns a list of users for the given sis course id.
"""
return self.get_users_for_course(
self._sis_id(sis_course_id, sis_field="course"), params) | 0.007692 |
def transform(self, X, lenscale=None):
"""
Apply the Fast Food RBF basis to X.
Parameters
----------
X: ndarray
(N, d) array of observations where N is the number of samples, and
d is the dimensionality of X.
lenscale: scalar or ndarray, optional
... | 0.002247 |
def check_oversized_pickle(pickled, name, obj_type, worker):
"""Send a warning message if the pickled object is too large.
Args:
pickled: the pickled object.
name: name of the pickled object.
obj_type: type of the pickled object, can be 'function',
'remote function', 'actor'... | 0.001073 |
def FailoverInstance(r, instance, iallocator=None, ignore_consistency=False,
target_node=None):
"""Does a failover of an instance.
@type instance: string
@param instance: Instance name
@type iallocator: string
@param iallocator: Iallocator for deciding the target node for
... | 0.002198 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.