positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def has_permissions_batch(self, eval_batch):
"""HasPermissionsBatch.
Evaluates multiple permissions for the calling user. Note: This method does not aggregate the results, nor does it short-circuit if one of the permissions evaluates to false.
:param :class:`<PermissionEvaluationBatch> <azure.d... | HasPermissionsBatch.
Evaluates multiple permissions for the calling user. Note: This method does not aggregate the results, nor does it short-circuit if one of the permissions evaluates to false.
:param :class:`<PermissionEvaluationBatch> <azure.devops.v5_0.security.models.PermissionEvaluationBatch>` e... |
def getColorMapAsContinuousSLD(self, nodata=-9999):
"""
Return the mapped color ramp as a
:rtype: str
"""
colorMap = ET.Element('ColorMap', type='interval')
# Add a line for the no-data values (nv)
ET.SubElement(colorMap, 'ColorMapEntry', color='#000000', quantit... | Return the mapped color ramp as a
:rtype: str |
def getCameraParams(self):
'''
value positions based on
http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html#cv.InitUndistortRectifyMap
'''
c = self.coeffs['cameraMatrix']
fx = c[0][0]
fy = c[1][1]
cx = c[0][2]
cy = c... | value positions based on
http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html#cv.InitUndistortRectifyMap |
def segments(self):
"""A dictionary of lists of contours keyed by z-index"""
segments = dict()
for i in xrange(len(self)):
image = self[i]
for z, contour in image.as_segments.iteritems():
for byte_value, contour_set in contour.iteritems():
... | A dictionary of lists of contours keyed by z-index |
def dump_yaml(data, clean_up=False, long_form=False):
"""
Output some YAML
"""
return yaml.dump(
data,
Dumper=get_dumper(clean_up, long_form),
default_flow_style=False,
allow_unicode=True
) | Output some YAML |
def sanity_check(
state: MediatorTransferState,
channelidentifiers_to_channels: ChannelMap,
) -> None:
""" Check invariants that must hold. """
# if a transfer is paid we must know the secret
all_transfers_states = itertools.chain(
(pair.payee_state for pair in state.transfers_pair)... | Check invariants that must hold. |
def append(self, option):
"""
Appends a new `option` to the end of the ButtonGroup.
:param string/List option:
The option to append to the ButtonGroup. If a 2D list is specified,
the first element is the text, the second is the value.
"""
self._options.ap... | Appends a new `option` to the end of the ButtonGroup.
:param string/List option:
The option to append to the ButtonGroup. If a 2D list is specified,
the first element is the text, the second is the value. |
def write_fundamental(self, keyTimeValueDict):
''' write fundamental '''
if self.first:
Base.metadata.create_all(self.__getEngine(), checkfirst=True)
self.first=False
sqls=self._fundamentalToSqls(keyTimeValueDict)
session=self.Session()
try:
... | write fundamental |
def get_ladder_metadata(session, url):
"""Get ladder metadata."""
parsed = make_scrape_request(session, url)
tag = parsed.find('a', href=re.compile(LADDER_ID_REGEX))
return {
'id': int(tag['href'].split('/')[-1]),
'slug': url.split('/')[-1],
'url': url
} | Get ladder metadata. |
def nvmlDeviceGetPcieThroughput(device, counter):
r"""
/**
* Retrieve PCIe utilization information.
* This function is querying a byte counter over a 20ms interval and thus is the
* PCIe throughput over that interval.
*
* For Maxwell &tm; or newer fully supported devices.
*
... | r"""
/**
* Retrieve PCIe utilization information.
* This function is querying a byte counter over a 20ms interval and thus is the
* PCIe throughput over that interval.
*
* For Maxwell &tm; or newer fully supported devices.
*
* This method is not supported in virtual machines run... |
def run(config: dict, output_root: str, restore_from: str=None, eval: Optional[str]=None) -> None:
"""
Run **cxflow** training configured by the passed `config`.
Unique ``output_dir`` for this training is created under the given ``output_root`` dir
wherein all the training outputs are saved. The output... | Run **cxflow** training configured by the passed `config`.
Unique ``output_dir`` for this training is created under the given ``output_root`` dir
wherein all the training outputs are saved. The output dir name will be roughly ``[model.name]_[time]``.
The training procedure consists of the following steps:... |
def load_p2th_privkey_into_local_node(provider: RpcNode, prod: bool=True) -> None:
'''Load PeerAssets P2TH privkey into the local node.'''
assert isinstance(provider, RpcNode), {"error": "Import only works with local node."}
error = {"error": "Loading P2TH privkey failed."}
pa_params = param_query(prov... | Load PeerAssets P2TH privkey into the local node. |
def res(self):
"""
the raster resolution in x and y direction
Returns
-------
tuple
(xres, yres)
"""
return (abs(float(self.geo['xres'])), abs(float(self.geo['yres']))) | the raster resolution in x and y direction
Returns
-------
tuple
(xres, yres) |
def _http_request(self, api, data, headers=None):
"""
internal method for handling request and response
and raising an exception is http return status code is not success
:rtype : response object from requests.post()
"""
if not headers:
headers = {'Content-Ty... | internal method for handling request and response
and raising an exception is http return status code is not success
:rtype : response object from requests.post() |
def validate_config(self, config):
"""We only validate the config if passed.
Also we use the ExperimentSpecification to check if this config was
intended as an experiment.
"""
# config is optional
if not config:
return config
spec = validate_experime... | We only validate the config if passed.
Also we use the ExperimentSpecification to check if this config was
intended as an experiment. |
def validate_object_id(object_id):
""" It's easy to make a mistake entering these, validate the format """
result = re.match(OBJECT_ID_RE, str(object_id))
if not result:
print("'%s' appears not to be a valid 990 object_id" % object_id)
raise RuntimeError(OBJECT_ID_MSG)
return object_id | It's easy to make a mistake entering these, validate the format |
def _retry_from_retry_config(retry_params, retry_codes):
"""Creates a Retry object given a gapic retry configuration.
Args:
retry_params (dict): The retry parameter values, for example::
{
"initial_retry_delay_millis": 1000,
"retry_delay_multiplier": 2.5,
... | Creates a Retry object given a gapic retry configuration.
Args:
retry_params (dict): The retry parameter values, for example::
{
"initial_retry_delay_millis": 1000,
"retry_delay_multiplier": 2.5,
"max_retry_delay_millis": 120000,
... |
def task_view_user(self, ):
"""View the user that is currently selected
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_task:
return
i = self.task_user_tablev.currentIndex()
item = i.internalPointer()
if item:
... | View the user that is currently selected
:returns: None
:rtype: None
:raises: None |
def get(self, timeout=None):
"""
Returns the result when it arrives. If timeout is not None and
the result does not arrive within timeout seconds then
TimeoutError is raised. If the remote call raised an exception
then that exception will be reraised by get().
"""
... | Returns the result when it arrives. If timeout is not None and
the result does not arrive within timeout seconds then
TimeoutError is raised. If the remote call raised an exception
then that exception will be reraised by get(). |
def countByValueAndWindow(self, windowDuration, slideDuration, numPartitions=None):
"""
Return a new DStream in which each RDD contains the count of distinct elements in
RDDs in a sliding window over this DStream.
@param windowDuration: width of the window; must be a multiple of this DS... | Return a new DStream in which each RDD contains the count of distinct elements in
RDDs in a sliding window over this DStream.
@param windowDuration: width of the window; must be a multiple of this DStream's
batching interval
@param slideDuration: sliding interval ... |
def plotConvergenceByDistantConnectionChance(results, featureRange, columnRange, longDistanceConnectionsRange, numTrials):
"""
Plots the convergence graph: iterations vs number of columns.
Each curve shows the convergence for a given number of unique features.
"""
#############################################... | Plots the convergence graph: iterations vs number of columns.
Each curve shows the convergence for a given number of unique features. |
def Zuber(sigma, Hvap, rhol, rhog, K=0.18):
r'''Calculates critical heat flux for nucleic boiling of a flat plate
or other shape as presented in various sources.
K = pi/24 is believed to be the original [1]_ value for K, but 0.149 is
now more widely used, a value claimed to be from [2]_ according to [5]... | r'''Calculates critical heat flux for nucleic boiling of a flat plate
or other shape as presented in various sources.
K = pi/24 is believed to be the original [1]_ value for K, but 0.149 is
now more widely used, a value claimed to be from [2]_ according to [5]_.
Cao [4]_ lists a value of 0.18 for K. The... |
def execute_by_options(args):
"""execute by argument dictionary
Args:
args (dict): command line argument dictionary
"""
if args['subcommand'] == 'sphinx':
s = Sphinx(proj_info)
if args['quickstart']:
s.quickstart()
elif args['gen_code_api']:
s.ge... | execute by argument dictionary
Args:
args (dict): command line argument dictionary |
def laplacian_of_gaussian(image, mask, size, sigma):
'''Perform the Laplacian of Gaussian transform on the image
image - 2-d image array
mask - binary mask of significant pixels
size - length of side of square kernel to use
sigma - standard deviation of the Gaussian
'''
half_size = size//... | Perform the Laplacian of Gaussian transform on the image
image - 2-d image array
mask - binary mask of significant pixels
size - length of side of square kernel to use
sigma - standard deviation of the Gaussian |
def singular_subresource(raml_resource, route_name):
""" Determine if :raml_resource: is a singular subresource.
:param raml_resource: Instance of ramlfications.raml.ResourceNode.
:param route_name: Name of the :raml_resource:.
"""
static_parent = get_static_parent(raml_resource, method='POST')
... | Determine if :raml_resource: is a singular subresource.
:param raml_resource: Instance of ramlfications.raml.ResourceNode.
:param route_name: Name of the :raml_resource:. |
async def renew(self, session, *, dc=None):
"""Renews a TTL-based session
Parameters:
session (ObjectID): Session ID
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
Returns:
ObjectMeta: where val... | Renews a TTL-based session
Parameters:
session (ObjectID): Session ID
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
Returns:
ObjectMeta: where value is session
Raises:
NotFound: ses... |
def assign_method(stochastic, scale=None, verbose=-1):
"""
Returns a step method instance to handle a
variable. If several methods have the same competence,
it picks one arbitrarily (using set.pop()).
"""
# Retrieve set of best candidates
best_candidates = pick_best_methods(stochastic)
... | Returns a step method instance to handle a
variable. If several methods have the same competence,
it picks one arbitrarily (using set.pop()). |
def column_list(string):
"""Validate and convert comma-separated list of column numbers."""
try:
columns = list(map(int, string.split(',')))
except ValueError as e:
raise argparse.ArgumentTypeError(*e.args)
for column in columns:
if column < 1:
raise argparse.Argument... | Validate and convert comma-separated list of column numbers. |
def is_manifestation_model(instance, attribute, value):
"""Must include a ``manifestationOfWork`` key."""
instance_name = instance.__class__.__name__
is_creation_model(instance, attribute, value)
manifestation_of = value.get('manifestationOfWork')
if not isinstance(manifestation_of, str):
... | Must include a ``manifestationOfWork`` key. |
def push_dir(path, glob=None, upload_path=None):
'''
Push a directory from the minion up to the master, the files will be saved
to the salt master in the master's minion files cachedir (defaults to
``/var/cache/salt/master/minions/minion-id/files``). It also has a glob
for matching specific files u... | Push a directory from the minion up to the master, the files will be saved
to the salt master in the master's minion files cachedir (defaults to
``/var/cache/salt/master/minions/minion-id/files``). It also has a glob
for matching specific files using globbing.
.. versionadded:: 2014.7.0
Since thi... |
def _parse_ethtool_opts(opts, iface):
'''
Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
config = {}
if 'autoneg' in opts:
if opts... | Filters given options and outputs valid settings for ETHTOOLS_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting. |
def _set_linkinfo_isllink_srcport_type(self, v, load=False):
"""
Setter method for linkinfo_isllink_srcport_type, mapped from YANG variable /brocade_fabric_service_rpc/show_linkinfo/output/show_link_info/linkinfo_isl/linkinfo_isllink_srcport_type (interfacetype-type)
If this variable is read-only (config: f... | Setter method for linkinfo_isllink_srcport_type, mapped from YANG variable /brocade_fabric_service_rpc/show_linkinfo/output/show_link_info/linkinfo_isl/linkinfo_isllink_srcport_type (interfacetype-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_linkinfo_isllink_srcport_typ... |
def _set_nameserver_cos(self, v, load=False):
"""
Setter method for nameserver_cos, mapped from YANG variable /brocade_nameserver_rpc/get_nameserver_detail/output/show_nameserver/nameserver_cos (nameserver-cos-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_nameser... | Setter method for nameserver_cos, mapped from YANG variable /brocade_nameserver_rpc/get_nameserver_detail/output/show_nameserver/nameserver_cos (nameserver-cos-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_nameserver_cos is considered as a private
method. Backends lo... |
def execute(self, *args, **options):
"""
Executes whole process of parsing arguments, running command and
trying to catch errors.
"""
try:
self.handle(*args, **options)
except CommandError, e:
if options['debug']:
try:
... | Executes whole process of parsing arguments, running command and
trying to catch errors. |
def create_ui(self):
'''
.. versionchanged:: 0.20
Debounce window expose and resize handlers to improve
responsiveness.
.. versionchanged:: X.X.X
Call debounced `_on_expose_event` handler on _leading_ edge to make
UI update more responsive when, e... | .. versionchanged:: 0.20
Debounce window expose and resize handlers to improve
responsiveness.
.. versionchanged:: X.X.X
Call debounced `_on_expose_event` handler on _leading_ edge to make
UI update more responsive when, e.g., changing window focus.
... |
async def discover(self, timeout=None): # TODO: better name?
"""Discover sentinels and all monitored services within given timeout.
If no sentinels discovered within timeout: TimeoutError is raised.
If some sentinels were discovered but not all — it is ok.
If not all monitored servic... | Discover sentinels and all monitored services within given timeout.
If no sentinels discovered within timeout: TimeoutError is raised.
If some sentinels were discovered but not all — it is ok.
If not all monitored services (masters/slaves) discovered
(or connections established) — it is... |
def sdiffstore(self, destination, *keys):
"""This command is equal to :meth:`~tredis.RedisClient.sdiff`, but
instead of returning the resulting set, it is stored in destination.
If destination already exists, it is overwritten.
.. note::
**Time complexity**: ``O(N)`` where ... | This command is equal to :meth:`~tredis.RedisClient.sdiff`, but
instead of returning the resulting set, it is stored in destination.
If destination already exists, it is overwritten.
.. note::
**Time complexity**: ``O(N)`` where ``N`` is the total number of
elements in a... |
async def stream(
self, version="1.1", keep_alive=False, keep_alive_timeout=None
):
"""Streams headers, runs the `streaming_fn` callback that writes
content to the response body, then finalizes the response body.
"""
headers = self.get_headers(
version,
... | Streams headers, runs the `streaming_fn` callback that writes
content to the response body, then finalizes the response body. |
def listen(self, io_in, io_out, io_err):
"""Listens to provided io stream and writes predictions
to output. In case of errors, the error stream will be used.
"""
for line in io_in:
if line.strip().lower() == 'exit':
break
try:
y_pr... | Listens to provided io stream and writes predictions
to output. In case of errors, the error stream will be used. |
def build(self):
"""Build the full HTML source."""
if self.is_built(): # pragma: no cover
return
with _wait_signal(self.loadFinished, 20):
self.rebuild()
self._built = True | Build the full HTML source. |
def build_embedding_weights(word_index, embeddings_index):
"""Builds an embedding matrix for all words in vocab using embeddings_index
"""
logger.info('Loading embeddings for all words in the corpus')
embedding_dim = list(embeddings_index.values())[0].shape[-1]
# setting special tokens such as UNK ... | Builds an embedding matrix for all words in vocab using embeddings_index |
def reset_env(exclude=[]):
"""Remove environment variables, used in Jupyter notebooks"""
if os.getenv(env.INITED):
wandb_keys = [key for key in os.environ.keys() if key.startswith(
'WANDB_') and key not in exclude]
for key in wandb_keys:
del os.environ[key]
return... | Remove environment variables, used in Jupyter notebooks |
def resolve_import(self, item):
"""Simulate how Python resolves imports.
Returns the filename of the source file Python would load
when processing a statement like 'import name' in the module
we're currently under.
Args:
item: An instance of ImportItem
Retu... | Simulate how Python resolves imports.
Returns the filename of the source file Python would load
when processing a statement like 'import name' in the module
we're currently under.
Args:
item: An instance of ImportItem
Returns:
A filename
Raises... |
def functional(self, fnct, x, y, sd=None, wt=1.0, mxit=50, fid=0):
"""Make a non-linear least squares solution.
This will make a non-linear least squares solution for the points
through the ordinates at the abscissa values, using the specified
`fnct`. Details can be found in the :meth:`... | Make a non-linear least squares solution.
This will make a non-linear least squares solution for the points
through the ordinates at the abscissa values, using the specified
`fnct`. Details can be found in the :meth:`linear` description.
:param fnct: the functional to fit
:para... |
def _bytes_to_str(lines):
"""
Convert all lines from byte string to unicode string, if necessary
"""
if len(lines) >= 1 and hasattr(lines[0], 'decode'):
return [line.decode('utf-8') for line in lines]
else:
return lines | Convert all lines from byte string to unicode string, if necessary |
def global_include(self, pattern):
"""
Include all files anywhere in the current directory that match the
pattern. This is very inefficient on large file trees.
"""
if self.allfiles is None:
self.findall()
match = translate_pattern(os.path.join('**', pattern))... | Include all files anywhere in the current directory that match the
pattern. This is very inefficient on large file trees. |
def _validate_edges_do_not_have_extra_links(class_name, properties):
"""Validate that edges do not have properties of Link type that aren't the edge endpoints."""
for property_name, property_descriptor in six.iteritems(properties):
if property_name in {EDGE_SOURCE_PROPERTY_NAME, EDGE_DESTINATION_PROPERT... | Validate that edges do not have properties of Link type that aren't the edge endpoints. |
def validate_generations_for_story_elements(
sender,
instance,
action,
target_node_type=None,
target_node=None,
pos=None,
*args,
**kwargs
):
'''
Unlike arc nodes, for which we just warn about structure, the story tree
allowed parent/child rules... | Unlike arc nodes, for which we just warn about structure, the story tree
allowed parent/child rules must be strictly enforced. |
def get(self, timeout=10):
"""get() -> {'id': 32-byte-md5, 'body': msg-body}"""
req = self.req({'op': 'GET', 'timeout': timeout})
if req.status_code != 200:
return None
result = req.json()
if result.get('status') != 'ok':
return False
return result | get() -> {'id': 32-byte-md5, 'body': msg-body} |
def wait(self):
"""
PUT THREAD IN WAIT STATE UNTIL SIGNAL IS ACTIVATED
"""
if self._go:
return True
with self.lock:
if self._go:
return True
stopper = _allocate_lock()
stopper.acquire()
if not self.waiti... | PUT THREAD IN WAIT STATE UNTIL SIGNAL IS ACTIVATED |
def export_private_key(self, password=None):
""" Export a private key in PEM-format
:param password: If it is not None, then result will be encrypt with given password
:return: bytes
"""
if self.__private_key is None:
raise ValueError('Unable to call this method. Private key must be set')
if password ... | Export a private key in PEM-format
:param password: If it is not None, then result will be encrypt with given password
:return: bytes |
def create_node_rating_counts_settings(sender, **kwargs):
""" create node rating count and settings"""
created = kwargs['created']
node = kwargs['instance']
if created:
# create node_rating_count and settings
# task will be executed in background unless settings.CELERY_ALWAYS_EAGER is Tr... | create node rating count and settings |
def _handleSelectAllAxes(self, evt):
"""Called when the 'select all axes' menu item is selected."""
if len(self._axisId) == 0:
return
for i in range(len(self._axisId)):
self._menu.Check(self._axisId[i], True)
self._toolbar.set_active(self.getActiveAxes())
... | Called when the 'select all axes' menu item is selected. |
def _ProcessArchiveTypes(self, mediator, path_spec, type_indicators):
"""Processes a data stream containing archive types such as: TAR or ZIP.
Args:
mediator (ParserMediator): mediates the interactions between
parsers and other components, such as storage and abort signals.
path_spec (dfv... | Processes a data stream containing archive types such as: TAR or ZIP.
Args:
mediator (ParserMediator): mediates the interactions between
parsers and other components, such as storage and abort signals.
path_spec (dfvfs.PathSpec): path specification.
type_indicators(list[str]): dfVFS arc... |
def nltk_stemmer(stemmer, token, i=None, tokens=None):
"""Wrapper around a NLTK SnowballStemmer, which includes stop words for
each language.
Args:
stemmer (SnowballStemmer): Stemmer instance that performs the stemming.
token (lunr.Token): The token to stem.
i (int): The index of th... | Wrapper around a NLTK SnowballStemmer, which includes stop words for
each language.
Args:
stemmer (SnowballStemmer): Stemmer instance that performs the stemming.
token (lunr.Token): The token to stem.
i (int): The index of the token in a set.
tokens (list): A list of tokens repr... |
def install_repo(args):
"""
For a user that only wants to install the repository only (and avoid
installing Ceph and its dependencies).
"""
cd_conf = getattr(args, 'cd_conf', None)
for hostname in args.host:
LOG.debug('Detecting platform for host %s ...', hostname)
distro = host... | For a user that only wants to install the repository only (and avoid
installing Ceph and its dependencies). |
def system_add_column_family(self, cf_def):
"""
adds a column family. returns the new schema id.
Parameters:
- cf_def
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_system_add_column_family(cf_def)
return d | adds a column family. returns the new schema id.
Parameters:
- cf_def |
def delete(self, resource, resource_id):
'''
A base function that performs a default delete DELETE request for a given object
'''
service_def, resource_def, path = self._get_service_information(
resource)
delete_path = "{0}{1}/" . format(path, resource_id)
re... | A base function that performs a default delete DELETE request for a given object |
def get_projects(self):
""" Get the projects list from database """
repos_list = []
gerrit_projects_db = self.projects_db
db = Database(user="root", passwd="", host="localhost", port=3306,
scrdb=None, shdb=gerrit_projects_db, prjdb=None)
sql = """
... | Get the projects list from database |
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._limit_monetary_account is not None:
return False
if self._limit_monetary_account_remaining is not None:
return False
if self._limit_card_debit_maestro is not None:
return Fal... | :rtype: bool |
def direct_perms_for_user(cls, instance, user, db_session=None):
"""
returns permissions that given user has for this resource
without ones inherited from groups that user belongs to
:param instance:
:param user:
:param db_session:
:return:
"""
... | returns permissions that given user has for this resource
without ones inherited from groups that user belongs to
:param instance:
:param user:
:param db_session:
:return: |
def save(self, bulk=False, id=None, parent=None, routing=None, force=False):
"""
Save the object and returns id
"""
meta = self._meta
conn = meta['connection']
id = id or meta.get("id", None)
parent = parent or meta.get('parent', None)
routing = routing or... | Save the object and returns id |
def parse_token(self, token, tags=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA]):
""" Returns the arguments for Sentence.append() from a tagged token representation.
The order in which token tags appear can be specified.
The default order is (separated by slashes):
- word,
... | Returns the arguments for Sentence.append() from a tagged token representation.
The order in which token tags appear can be specified.
The default order is (separated by slashes):
- word,
- part-of-speech,
- (IOB-)chunk,
- (IOB-)preposition,
... |
def record_leaving(self, time, code, frame_key, parent_stats):
"""Left from a function call."""
try:
stats = parent_stats.get_child(code)
time_entered = self._times_entered.pop((code, frame_key))
except KeyError:
return
time_elapsed = time - time_enter... | Left from a function call. |
def get_call_arguments(self, request):
"""
Get call arguments from a request. Override this if you want to use a
wire format different from AWS's.
The return value is a dictionary with three keys: 'transport_args',
'handler_args', and 'raw_args'.
The value of 'transport... | Get call arguments from a request. Override this if you want to use a
wire format different from AWS's.
The return value is a dictionary with three keys: 'transport_args',
'handler_args', and 'raw_args'.
The value of 'transport_args' must be a dictionary with the following
keys... |
def linearize_metrics(logged_metrics):
"""
Group metrics by name.
Takes a list of individual measurements, possibly belonging
to different metrics and groups them by name.
:param logged_metrics: A list of ScalarMetricLogEntries
:return: Measured values grouped by the metric name:
{"metric_... | Group metrics by name.
Takes a list of individual measurements, possibly belonging
to different metrics and groups them by name.
:param logged_metrics: A list of ScalarMetricLogEntries
:return: Measured values grouped by the metric name:
{"metric_name1": {"steps": [0,1,2], "values": [4, 5, 6],
... |
def image(self):
""" Returns an image array of current render window """
if not hasattr(self, 'ren_win') and hasattr(self, 'last_image'):
return self.last_image
ifilter = vtk.vtkWindowToImageFilter()
ifilter.SetInput(self.ren_win)
ifilter.ReadFrontBufferOff()
... | Returns an image array of current render window |
def isObservableElement(self, elementName):
"""
Mention if an element is an observable element.
:param str ElementName: the element name to evaluate
:return: true if is an observable element, otherwise false.
:rtype: bool
"""
if not(isinstance(elementName, str)):... | Mention if an element is an observable element.
:param str ElementName: the element name to evaluate
:return: true if is an observable element, otherwise false.
:rtype: bool |
def processes(self):
"""The proccesses for this app."""
return self._h._get_resources(
resource=('apps', self.name, 'ps'),
obj=Process, app=self, map=ProcessListResource
) | The proccesses for this app. |
def _validate_question_area(self):
"""Helper method to evaluate the current state of the dialog.
This function will determine if it is appropriate for the OK button to
be enabled or not.
.. note:: The enabled state of the OK button on the dialog will
NOT be updated (set True... | Helper method to evaluate the current state of the dialog.
This function will determine if it is appropriate for the OK button to
be enabled or not.
.. note:: The enabled state of the OK button on the dialog will
NOT be updated (set True or False) depending on the outcome of
... |
def update(cls, spec, updates, upsert=False):
'''
The spec is used to search for the data to update, updates contains the
values to be updated, and upsert specifies whether to do an insert if
the original data is not found.
'''
if 'key' in spec:
previous = cls... | The spec is used to search for the data to update, updates contains the
values to be updated, and upsert specifies whether to do an insert if
the original data is not found. |
def pub_poll(request, docid):
"""The initial viewer, does not provide the document content yet"""
try:
r = flat.comm.get(request, '/poll/pub/' + docid + '/', False)
except URLError:
return HttpResponseForbidden("Unable to connect to the document server [viewer/poll]")
return HttpResponse... | The initial viewer, does not provide the document content yet |
def prepend(self, key, value, expire=0, noreply=None):
"""
The memcached "prepend" command.
Args:
key: str, see class docs for details.
value: str, see class docs for details.
expire: optional int, number of seconds until the item is expired
from ... | The memcached "prepend" command.
Args:
key: str, see class docs for details.
value: str, see class docs for details.
expire: optional int, number of seconds until the item is expired
from the cache, or zero for no expiry (the default).
noreply: optional... |
def start(name):
# type: (str) -> None
""" Start working on a new feature by branching off develop.
This will create a new branch off develop called feature/<name>.
Args:
name (str):
The name of the new feature.
"""
feature_name = 'feature/' + common.to_branch_name(name)
... | Start working on a new feature by branching off develop.
This will create a new branch off develop called feature/<name>.
Args:
name (str):
The name of the new feature. |
def update(self, unique_name=values.unset, default_ttl=values.unset,
callback_url=values.unset, geo_match_level=values.unset,
number_selection_behavior=values.unset,
intercept_callback_url=values.unset,
out_of_session_callback_url=values.unset,
... | Update the ServiceInstance
:param unicode unique_name: An application-defined string that uniquely identifies the resource
:param unicode default_ttl: Default TTL for a Session, in seconds
:param unicode callback_url: The URL we should call when the interaction status changes
:param Ser... |
def min_row_dist_sum_idx(dists):
"""Find the index of the row with the minimum row distance sum
This should return the index of the row index with the least distance overall
to all other rows.
Args:
dists (np.array): must be square distance matrix
Returns:
int: index of row wit... | Find the index of the row with the minimum row distance sum
This should return the index of the row index with the least distance overall
to all other rows.
Args:
dists (np.array): must be square distance matrix
Returns:
int: index of row with min dist row sum |
def assert_link_text(self, link_text, timeout=settings.SMALL_TIMEOUT):
""" Similar to wait_for_link_text_visible(), but returns nothing.
As above, will raise an exception if nothing can be found.
Returns True if successful. Default timeout = SMALL_TIMEOUT. """
if self.timeout_mul... | Similar to wait_for_link_text_visible(), but returns nothing.
As above, will raise an exception if nothing can be found.
Returns True if successful. Default timeout = SMALL_TIMEOUT. |
def get_consumers(self, consumer_cls, channel):
""" Kombu callback to set up consumers.
Called after any (re)connection to the broker.
"""
_log.debug('setting up consumers %s', self)
for provider in self._providers:
callbacks = [partial(self.handle_message, provider... | Kombu callback to set up consumers.
Called after any (re)connection to the broker. |
def get_delta_pal(b, b_star):
"""
input: b, b_star (actual and corrected slope)
output: delta_pal
"""
delta_pal = numpy.abs(old_div((b - b_star), b)) * 100
return delta_pal | input: b, b_star (actual and corrected slope)
output: delta_pal |
def set_target_temperature_by_id(self, zone_id, target_temperature):
"""
Set the target temperature for a zone by id
"""
if not self._do_auth():
raise RuntimeError("Unable to login")
data = {
"ZoneId": zone_id,
"TargetTemperature": target_temp... | Set the target temperature for a zone by id |
def verify_password(self, password):
""" Verify a given string for being valid password """
if self.password is None:
return False
from boiler.user.util.passlib import passlib_context
return passlib_context.verify(str(password), self.password) | Verify a given string for being valid password |
def toggle_autojump():
"""Toggles Autojump"""
if not autojump_enabled():
with open(AUTOJUMP_FILE, 'w+') as ajfile:
ajfile.write("enabled")
else:
os.remove(AUTOJUMP_FILE) | Toggles Autojump |
def range_distance(a, b, distmode='ss'):
"""
Returns the distance between two ranges.
distmode is ss, se, es, ee and sets the place on read one and two to
measure the distance (s = start, e = end)
>>> range_distance(("1", 30, 45, '+'), ("1", 45, 55, '+'))
(26, '++')
>>> range_distanc... | Returns the distance between two ranges.
distmode is ss, se, es, ee and sets the place on read one and two to
measure the distance (s = start, e = end)
>>> range_distance(("1", 30, 45, '+'), ("1", 45, 55, '+'))
(26, '++')
>>> range_distance(("1", 30, 45, '-'), ("1", 57, 68, '-'))
(39, '-... |
def InitFromAff4Object(self, aff4_obj):
"""Initializes the current instance from an Aff4Object.
Iterates the inheritance hierarchy of the given Aff4Object and adds a
ApiAff4ObjectType for each class found in the hierarchy.
Args:
aff4_obj: An Aff4Object as source for the initialization.
Retu... | Initializes the current instance from an Aff4Object.
Iterates the inheritance hierarchy of the given Aff4Object and adds a
ApiAff4ObjectType for each class found in the hierarchy.
Args:
aff4_obj: An Aff4Object as source for the initialization.
Returns:
A reference to the current instance. |
def _memoize_cache_key(args, kwargs):
"""Turn args tuple and kwargs dictionary into a hashable key.
Expects that all arguments to a memoized function are either hashable
or can be uniquely identified from type(arg) and repr(arg).
"""
cache_key_list = []
# hack to get around the unhashability o... | Turn args tuple and kwargs dictionary into a hashable key.
Expects that all arguments to a memoized function are either hashable
or can be uniquely identified from type(arg) and repr(arg). |
def youtube(keyword=None):
"""Open youtube.
Args:
keyword (optional): Search word.
"""
if keyword is None:
web.open('https://www.youtube.com/watch?v=L_mBVT2jBFw')
else:
web.open(quote('https://www.youtube.com/results?search_query={}'.format(keyword), RESERVED)) | Open youtube.
Args:
keyword (optional): Search word. |
def xche4_teff(self,ifig=None,lims=[1.,0.,3.4,4.7],label=None,colour=None,
s2ms=True,dashes=None):
"""
Plot effective temperature against central helium abundance.
Parameters
----------
ifig : integer or string
Figure label, if None the current fig... | Plot effective temperature against central helium abundance.
Parameters
----------
ifig : integer or string
Figure label, if None the current figure is used
The default value is None.
lims : list [x_lower, x_upper, y_lower, y_upper]
label : string
... |
def _find_relations(self):
"""Find all relevant relation elements and return them in a list."""
# Get all extractions
extractions = \
list(self.tree.execute("$.extractions[(@.@type is 'Extraction')]"))
# Get relations from extractions
relations = []
for e in ... | Find all relevant relation elements and return them in a list. |
def _pre_flight(self):
'''
Run pre flight checks. If anything in this method fails then the master
should not start up.
'''
errors = []
critical_errors = []
try:
os.chdir('/')
except OSError as err:
errors.append(
'... | Run pre flight checks. If anything in this method fails then the master
should not start up. |
def gen_point_query(
vectors,
raster,
band=1,
layer=0,
nodata=None,
affine=None,
interpolate='bilinear',
property_name='value',
geojson_out=False):
"""
Given a set of vector features and a raster,
generate raster values at each vertex of the geometry
For features wit... | Given a set of vector features and a raster,
generate raster values at each vertex of the geometry
For features with point geometry,
the values will be a 1D with the index refering to the feature
For features with other geometry types,
it effectively creates a 2D list, such that
the first inde... |
def query(self, string, repeat_n_times=None):
"""
This method performs the operations onto self.g
:param string: The list of operations to perform. The sequences of commands should be separated by a semicolon
An example might be
CREATE {'tag': 'PE... | This method performs the operations onto self.g
:param string: The list of operations to perform. The sequences of commands should be separated by a semicolon
An example might be
CREATE {'tag': 'PERSON', 'text': 'joseph'}(v1), {'relation': 'LIVES_AT'}(v1,v2),
... |
def bsrchd(value, ndim, array):
"""
Do a binary search for a key value within a double precision array,
assumed to be in increasing order. Return the index of the matching
array entry, or -1 if the key value is not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bsrchd_c.html
:p... | Do a binary search for a key value within a double precision array,
assumed to be in increasing order. Return the index of the matching
array entry, or -1 if the key value is not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bsrchd_c.html
:param value: Value to find in array.
:typ... |
def lexify(self, text='????', letters=string.ascii_letters):
"""
Replaces all question mark ('?') occurrences with a random letter.
:param text: string to be parsed
:param letters: a set of letters to choose from.
:returns: string with all letter placeholders filled in
"... | Replaces all question mark ('?') occurrences with a random letter.
:param text: string to be parsed
:param letters: a set of letters to choose from.
:returns: string with all letter placeholders filled in |
def get_field_SQL(self, field_name, field):
"""
returns the SQL for a given field with full type information
http://www.sqlite.org/datatype3.html
field_name -- string -- the field's name
field -- Field() -- the set options for the field
return -- string -- the field ty... | returns the SQL for a given field with full type information
http://www.sqlite.org/datatype3.html
field_name -- string -- the field's name
field -- Field() -- the set options for the field
return -- string -- the field type (eg, foo BOOL NOT NULL) |
def _create_comparison_method(cls, op):
"""
Create a comparison method that dispatches to ``cls.values``.
"""
def wrapper(self, other):
if isinstance(other, ABCSeries):
# the arrays defer to Series for comparison ops but the indexes
# don't, s... | Create a comparison method that dispatches to ``cls.values``. |
def encrypt(receiver_pubhex: str, msg: bytes) -> bytes:
"""
Encrypt with eth public key
Parameters
----------
receiver_pubhex: str
Receiver's ethereum public key hex string
msg: bytes
Data to encrypt
Returns
-------
bytes
Encrypted data
"""
disposabl... | Encrypt with eth public key
Parameters
----------
receiver_pubhex: str
Receiver's ethereum public key hex string
msg: bytes
Data to encrypt
Returns
-------
bytes
Encrypted data |
def _split_after_delimiter(self, item, indent_amt):
"""Split the line only after a delimiter."""
self._delete_whitespace()
if self.fits_on_current_line(item.size):
return
last_space = None
for item in reversed(self._lines):
if (
last_spac... | Split the line only after a delimiter. |
def get_archive_url(self):
"""
:calls: `GET /user/migrations/:migration_id/archive`_
:rtype: str
"""
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/archive",
headers={
"Accept": Consts.mediaTypeMigratio... | :calls: `GET /user/migrations/:migration_id/archive`_
:rtype: str |
def getTotalPrice(self):
"""Compute total price including VAT
"""
price = self.getPrice()
vat = self.getVAT()
price = price and price or 0
vat = vat and vat or 0
return float(price) + (float(price) * float(vat)) / 100 | Compute total price including VAT |
def get_repository_admin_session(self):
"""Gets the repository administrative session for creating,
updating and deleteing repositories.
return: (osid.repository.RepositoryAdminSession) - a
RepositoryAdminSession
raise: OperationFailed - unable to complete request
... | Gets the repository administrative session for creating,
updating and deleteing repositories.
return: (osid.repository.RepositoryAdminSession) - a
RepositoryAdminSession
raise: OperationFailed - unable to complete request
raise: Unimplemented - supports_repository_admi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.