code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def set_shell(self, svc_ref):
"""
Binds the given shell service.
:param svc_ref: A service reference
"""
if svc_ref is None:
return
with self._lock:
# Get the service
self._shell_ref = svc_ref
self._shell = self._context.g... | Binds the given shell service.
:param svc_ref: A service reference |
def extract_keys(self,key_list):
""" >>> d = {'a':1,'b':2,'c':3}
>>> print d.extract_keys('b,c,d')
>>> {'b':2,'c':3}
>>> print d.extract_keys(['b','c','d'])
>>> {'b':2,'c':3} """
if isinstance(key_list,basestring):
key_list = key_list.split(','... | >>> d = {'a':1,'b':2,'c':3}
>>> print d.extract_keys('b,c,d')
>>> {'b':2,'c':3}
>>> print d.extract_keys(['b','c','d'])
>>> {'b':2,'c':3} |
def _validate_action_parameters(func, params):
""" Verifies that the parameters specified are actual parameters for the
function `func`, and that the field types are FIELD_* types in fields.
"""
if params is not None:
# Verify field name is valid
valid_fields = [getattr(fields, f) for f ... | Verifies that the parameters specified are actual parameters for the
function `func`, and that the field types are FIELD_* types in fields. |
def _migrate_subresource(subresource, parent, migrations):
"""
Migrate a resource's subresource
:param subresource: the perch.SubResource instance
:param parent: the parent perch.Document instance
:param migrations: the migrations for a resource
"""
for key, doc in getattr(parent, subresour... | Migrate a resource's subresource
:param subresource: the perch.SubResource instance
:param parent: the parent perch.Document instance
:param migrations: the migrations for a resource |
def _make_request_with_auth_fallback(self, url, headers=None, params=None):
"""
Generic request handler for OpenStack API requests
Raises specialized Exceptions for commonly encountered error codes
"""
self.log.debug("Request URL and Params: %s, %s", url, params)
try:
... | Generic request handler for OpenStack API requests
Raises specialized Exceptions for commonly encountered error codes |
def _pretend_to_run(self, migration, method):
"""
Pretend to run the migration.
:param migration: The migration
:type migration: eloquent.migrations.migration.Migration
:param method: The method to execute
:type method: str
"""
for query in self._get_que... | Pretend to run the migration.
:param migration: The migration
:type migration: eloquent.migrations.migration.Migration
:param method: The method to execute
:type method: str |
def send_command(self, command, as_list=False):
"""Send a :class:`~panoramisk.actions.Command` to the server::
manager = Manager()
resp = manager.send_command('http show status')
Return a response :class:`~panoramisk.message.Message`.
See https://wiki.asterisk.org/wiki/... | Send a :class:`~panoramisk.actions.Command` to the server::
manager = Manager()
resp = manager.send_command('http show status')
Return a response :class:`~panoramisk.message.Message`.
See https://wiki.asterisk.org/wiki/display/AST/ManagerAction_Command |
def port_bindings(val, **kwargs):
'''
On the CLI, these are passed as multiple instances of a given CLI option.
In Salt, we accept these as a comma-delimited list but the API expects a
Python dictionary mapping ports to their bindings. The format the API
expects is complicated depending on whether o... | On the CLI, these are passed as multiple instances of a given CLI option.
In Salt, we accept these as a comma-delimited list but the API expects a
Python dictionary mapping ports to their bindings. The format the API
expects is complicated depending on whether or not the external port maps
to a differen... |
def run_command(self, cmd, new_prompt=True):
"""Run command in interpreter"""
if cmd == 'exit()':
self.exit_flag = True
self.write('\n')
return
# -- Special commands type I
# (transformed into commands executed in the interpreter)
# ... | Run command in interpreter |
def wrap_as_node(self, func):
'wrap a function as a node'
name = self.get_name(func)
@wraps(func)
def wrapped(*args, **kwargs):
'wrapped version of func'
message = self.get_message_from_call(*args, **kwargs)
self.logger.info('calling "%s" with %r', na... | wrap a function as a node |
def iso8601_datetime(d):
"""
Return a string representation of a date that the Twilio API understands
Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date
"""
if d == values.unset:
return d
elif isinstance(d, datetime.datetime) or isinstance(d, datetime.date):
... | Return a string representation of a date that the Twilio API understands
Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date |
def __get_sigmas(self):
"""will populate the stack_sigma dictionary with the energy and sigma array
for all the compound/element and isotopes"""
stack_sigma = {}
_stack = self.stack
_file_path = os.path.abspath(os.path.dirname(__file__))
_database_folder = os.path.join(_... | will populate the stack_sigma dictionary with the energy and sigma array
for all the compound/element and isotopes |
def pagination_calc(items_count, page_size, cur_page=1, nearby=2):
"""
:param nearby:
:param items_count: count of all items
:param page_size: size of one page
:param cur_page: current page number, accept string digit
:return: num of pages, an iterator
"""
if type(cur_page) == str:
... | :param nearby:
:param items_count: count of all items
:param page_size: size of one page
:param cur_page: current page number, accept string digit
:return: num of pages, an iterator |
def _array(group_idx, a, size, fill_value, dtype=None):
"""groups a into separate arrays, keeping the order intact."""
if fill_value is not None and not (np.isscalar(fill_value) or
len(fill_value) == 0):
raise ValueError("fill_value must be None, a scalar or an emp... | groups a into separate arrays, keeping the order intact. |
def process(self):
"""
This method handles the actual processing of Modules and Transforms
"""
self.modules.sort(key=lambda x: x.priority)
for module in self.modules:
transforms = module.transform(self.data)
transforms.sort(key=lambda x: x.linenum, revers... | This method handles the actual processing of Modules and Transforms |
def shared(self, value, name=None):
"""
Create a shared theano scalar value.
"""
if type(value) == int:
final_value = np.array(value, dtype="int32")
elif type(value) == float:
final_value = np.array(value, dtype=env.FLOATX)
else:
final_... | Create a shared theano scalar value. |
def get_most_distinct_words(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None):
"""
Order the words from `vocab` by "distinctiveness score" (Chuang et al. 2012) from most to least distinctive.
Optionally only return the `n` most distinctive words.
J. Chuang, C. Manning, J. Heer 2012: "T... | Order the words from `vocab` by "distinctiveness score" (Chuang et al. 2012) from most to least distinctive.
Optionally only return the `n` most distinctive words.
J. Chuang, C. Manning, J. Heer 2012: "Termite: Visualization Techniques for Assessing Textual Topic Models" |
def add_portal(self, origin, destination, symmetrical=False, **kwargs):
"""Connect the origin to the destination with a :class:`Portal`.
Keyword arguments are the :class:`Portal`'s
attributes. Exception: if keyword ``symmetrical`` == ``True``,
a mirror-:class:`Portal` will be placed in ... | Connect the origin to the destination with a :class:`Portal`.
Keyword arguments are the :class:`Portal`'s
attributes. Exception: if keyword ``symmetrical`` == ``True``,
a mirror-:class:`Portal` will be placed in the opposite
direction between the same nodes. It will always appear to
... |
def mark_dead(self, proxy, _time=None):
""" Mark a proxy as dead """
if proxy not in self.proxies:
logger.warn("Proxy <%s> was not found in proxies list" % proxy)
return
if proxy in self.good:
logger.debug("GOOD proxy became DEAD: <%s>" % proxy)
else:... | Mark a proxy as dead |
def get_group_hidden(self):
"""Determine if the entire group of elements is hidden
(decide whether to hide the entire group).
"""
# Loop through all the elements in the group.
for element in self.group_list:
# Handle element that is not hidden or has a form.
... | Determine if the entire group of elements is hidden
(decide whether to hide the entire group). |
def execute(self, resource, **kw):
"""
Execute the task and return a TaskOperationPoller.
:rtype: TaskOperationPoller
"""
params = kw.pop('params', {})
json = kw.pop('json', None)
task = self.make_request(
TaskRunFailed,
method='cr... | Execute the task and return a TaskOperationPoller.
:rtype: TaskOperationPoller |
def api_reference(root_url, service, version):
"""Generate URL for a Taskcluster api reference."""
root_url = root_url.rstrip('/')
if root_url == OLD_ROOT_URL:
return 'https://references.taskcluster.net/{}/{}/api.json'.format(service, version)
else:
return '{}/references/{}/{}/api.json'.... | Generate URL for a Taskcluster api reference. |
def get_oauth_access_token(url_base, client_id, client_secret, company_id, user_id, user_type):
""" Retrieves OAuth 2.0 access token using the client credentials grant.
Args:
url_base (str): Oauth2 access token endpoint
client_id (str): client ID
client_secret (str):... | Retrieves OAuth 2.0 access token using the client credentials grant.
Args:
url_base (str): Oauth2 access token endpoint
client_id (str): client ID
client_secret (str): client secret
company_id (str): SAP company ID
user_id (str): SAP user ID
... |
def print_clusters(fastas, info, ANI):
"""
choose represenative genome and
print cluster information
*if ggKbase table is provided, use SCG info to choose best genome
"""
header = ['#cluster', 'num. genomes', 'rep.', 'genome', '#SCGs', '#SCG duplicates', \
'genome size (bp)', 'fragm... | choose represenative genome and
print cluster information
*if ggKbase table is provided, use SCG info to choose best genome |
def _populate_unknown_statuses(set_tasks):
"""
Add the "upstream_*" and "not_run" statuses my mutating set_tasks.
"""
visited = set()
for task in set_tasks["still_pending_not_ext"]:
_depth_first_search(set_tasks, task, visited) | Add the "upstream_*" and "not_run" statuses my mutating set_tasks. |
def get_request_params(self) -> List[ExtensionParameter]:
"""
Build request parameters.
"""
return _build_parameters(
self.server_no_context_takeover,
self.client_no_context_takeover,
self.server_max_window_bits,
self.client_max_window_bit... | Build request parameters. |
def load(self, key, noexpire=None):
'''Lookup an item in the cache and return the raw content of
the file as a string.'''
with self.load_fd(key, noexpire=noexpire) as fd:
return fd.read() | Lookup an item in the cache and return the raw content of
the file as a string. |
def get_indexed_slices(self, column_parent, index_clause, column_predicate, consistency_level):
"""
Returns the subset of columns specified in SlicePredicate for the rows matching the IndexClause
@deprecated use get_range_slices instead with range.row_filter specified
Parameters:
- column_parent
... | Returns the subset of columns specified in SlicePredicate for the rows matching the IndexClause
@deprecated use get_range_slices instead with range.row_filter specified
Parameters:
- column_parent
- index_clause
- column_predicate
- consistency_level |
def inactive_response(self, request):
"""
Return an inactive message.
"""
inactive_url = getattr(settings, 'LOGIN_INACTIVE_REDIRECT_URL', '')
if inactive_url:
return HttpResponseRedirect(inactive_url)
else:
return self.error_to_response(request, {'... | Return an inactive message. |
def _construct_state_machines(self):
""" :return: dict in format <state_machine_common_name: instance_of_the_state_machine> """
state_machines = dict()
for state_machine in [StateMachineRecomputing(self.logger, self),
StateMachineContinuous(self.logger, self),
... | :return: dict in format <state_machine_common_name: instance_of_the_state_machine> |
def apply(self, df):
"""Takes a pd.DataFrame and returns the newly defined column, i.e.
a pd.Series that has the same index as `df`.
"""
if hasattr(self.definition, '__call__'):
r = self.definition(df)
elif self.definition in df.columns:
r = df[self.defini... | Takes a pd.DataFrame and returns the newly defined column, i.e.
a pd.Series that has the same index as `df`. |
def unique(iterable, key=identity):
"""Yields all the unique values in an iterable maintaining order"""
seen = set()
for item in iterable:
item_key = key(item)
if item_key not in seen:
seen.add(item_key)
yield item | Yields all the unique values in an iterable maintaining order |
def calendar(self, val):
"""
Update ``self._calendar_i``if ``self.calendar`` changes.
"""
self._calendar = val
if val is not None and not val.empty:
self._calendar_i = self._calendar.set_index("service_id")
else:
self._calendar_i = None | Update ``self._calendar_i``if ``self.calendar`` changes. |
def load_from_db(self, cache=False):
"""Return a dictionary of preferences by section directly from DB"""
a = {}
db_prefs = {p.preference.identifier(): p for p in self.queryset}
for preference in self.registry.preferences():
try:
db_pref = db_prefs[preference.... | Return a dictionary of preferences by section directly from DB |
def get_all_targets(self):
"""Returns all targets for all batches of this Executor."""
result = []
for batch in self.batches:
result.extend(batch.targets)
return result | Returns all targets for all batches of this Executor. |
def put(self, url: StrOrURL,
*, data: Any=None, **kwargs: Any) -> '_RequestContextManager':
"""Perform HTTP PUT request."""
return _RequestContextManager(
self._request(hdrs.METH_PUT, url,
data=data,
**kwargs)) | Perform HTTP PUT request. |
def tag_array(events):
"""
Return a numpy array mapping events to tags
- Rows corresponds to events
- Columns correspond to tags
"""
all_tags = sorted(set(tag for event in events for tag in event.tags))
array = np.zeros((len(events), len(all_tags)))
for row, event in enumerate(events):
... | Return a numpy array mapping events to tags
- Rows corresponds to events
- Columns correspond to tags |
def _neg_bounded_fun(fun, bounds, x, args=()):
"""
Wrapper for bounding and taking the negative of `fun` for the
Nelder-Mead algorithm. JIT-compiled in `nopython` mode using Numba.
Parameters
----------
fun : callable
The objective function to be minimized.
`fun(x, *args) ->... | Wrapper for bounding and taking the negative of `fun` for the
Nelder-Mead algorithm. JIT-compiled in `nopython` mode using Numba.
Parameters
----------
fun : callable
The objective function to be minimized.
`fun(x, *args) -> float`
where x is an 1-D array with shape (n,) and... |
def load_metadata_csv(input_filepath):
"""
Return dict of metadata.
Format is either dict (filenames are keys) or dict-of-dicts (project member
IDs as top level keys, then filenames as keys).
:param input_filepath: This field is the filepath of the csv file.
"""
with open(input_filepath) a... | Return dict of metadata.
Format is either dict (filenames are keys) or dict-of-dicts (project member
IDs as top level keys, then filenames as keys).
:param input_filepath: This field is the filepath of the csv file. |
def _validate(self, validator, data, key, position=None, includes=None):
"""
Run through a schema and a data structure,
validating along the way.
Ignores fields that are in the data structure, but not in the schema.
Returns an array of errors.
"""
errors = []
... | Run through a schema and a data structure,
validating along the way.
Ignores fields that are in the data structure, but not in the schema.
Returns an array of errors. |
def __start_waiting_for_events(self):
'''
This waits until the whole chain of callback methods triggered by
"trigger_connection_to_rabbit_etc()" has finished, and then starts
waiting for publications.
This is done by starting the ioloop.
Note: In the pika usage example,... | This waits until the whole chain of callback methods triggered by
"trigger_connection_to_rabbit_etc()" has finished, and then starts
waiting for publications.
This is done by starting the ioloop.
Note: In the pika usage example, these things are both called inside the run()
met... |
async def shutdown(self, container, force=False):
'''
Shutdown all connections. Exclusive connections created by get_connection will shutdown after release()
'''
p = self._connpool
self._connpool = []
self._shutdown = True
if self._defaultconn:
p.appen... | Shutdown all connections. Exclusive connections created by get_connection will shutdown after release() |
def toIndex(self, value):
'''
toIndex - An optional method which will return the value prepped for index.
By default, "toStorage" will be called. If you provide "hashIndex=True" on the constructor,
the field will be md5summed for indexing purposes. This is useful for large strings, etc.
'''
if self._isI... | toIndex - An optional method which will return the value prepped for index.
By default, "toStorage" will be called. If you provide "hashIndex=True" on the constructor,
the field will be md5summed for indexing purposes. This is useful for large strings, etc. |
def status_for_all_orders_in_a_stock(self, stock):
"""Status for all orders in a stock
https://starfighter.readme.io/docs/status-for-all-orders-in-a-stock
"""
url_fragment = 'venues/{venue}/accounts/{account}/stocks/{stock}/orders'.format(
stock=stock,
venue=self... | Status for all orders in a stock
https://starfighter.readme.io/docs/status-for-all-orders-in-a-stock |
def predict(self, choosers, alternatives, debug=False):
"""
Choose from among alternatives for a group of agents.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
alternatives : pandas.DataFrame
... | Choose from among alternatives for a group of agents.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
alternatives : pandas.DataFrame
Table describing the things from which agents are choosing.
... |
def _get_or_create_uaa(self, uaa):
"""
Returns a valid UAA instance for performing administrative functions
on services.
"""
if isinstance(uaa, predix.admin.uaa.UserAccountAuthentication):
return uaa
logging.debug("Initializing a new UAA")
return pred... | Returns a valid UAA instance for performing administrative functions
on services. |
def ccor(alt, r, h1, zh):
"""
/* CHEMISTRY/DISSOCIATION CORRECTION FOR MSIS MODELS
* ALT - altitude
* R - target ratio
* H1 - transition scale length
* ZH - altitude of 1/2 R
*/
"""
e = (alt - zh) / h1
if(e>70.0):
return 1.0 # exp(0) # pragma: no cover
... | /* CHEMISTRY/DISSOCIATION CORRECTION FOR MSIS MODELS
* ALT - altitude
* R - target ratio
* H1 - transition scale length
* ZH - altitude of 1/2 R
*/ |
def get_default_config_file(rootdir=None):
"""Search for configuration file."""
if rootdir is None:
return DEFAULT_CONFIG_FILE
for path in CONFIG_FILES:
path = os.path.join(rootdir, path)
if os.path.isfile(path) and os.access(path, os.R_OK):
return path | Search for configuration file. |
def _learn(# mutated args
permanences, rng,
# activity
activeCells, activeInput, growthCandidateInput,
# configuration
sampleSize, initialPermanence, permanenceIncrement,
permanenceDecrement, connectedPermanence):
"""
For each activ... | For each active cell, reinforce active synapses, punish inactive synapses,
and grow new synapses to a subset of the active input bits that the cell
isn't already connected to.
Parameters:
----------------------------
@param permanences (SparseMatrix)
Matrix of permanences, with cells a... |
def dereference(self, data, host=None):
"""Dereferences RefObjects stuck in the hierarchy. This is a bit
of an ugly hack."""
return self.deep_decode(self.deep_encode(data, host), deref=True) | Dereferences RefObjects stuck in the hierarchy. This is a bit
of an ugly hack. |
def _apply_replace_backrefs(m, repl=None, flags=0):
"""Expand with either the `ReplaceTemplate` or compile on the fly, or return None."""
if m is None:
raise ValueError("Match is None!")
else:
if isinstance(repl, ReplaceTemplate):
return repl.expand(m)
elif isinstance(re... | Expand with either the `ReplaceTemplate` or compile on the fly, or return None. |
def get_lm_challenge_response(self):
"""
[MS-NLMP] v28.0 2016-07-14
3.3.1 - NTLM v1 Authentication
3.3.2 - NTLM v2 Authentication
This method returns the LmChallengeResponse key based on the ntlm_compatibility chosen
and the target_info supplied by the CHALLENGE_MESSAGE... | [MS-NLMP] v28.0 2016-07-14
3.3.1 - NTLM v1 Authentication
3.3.2 - NTLM v2 Authentication
This method returns the LmChallengeResponse key based on the ntlm_compatibility chosen
and the target_info supplied by the CHALLENGE_MESSAGE. It is quite different from what
is set in the d... |
def load_and_assign_npz_dict(name='model.npz', sess=None):
"""Restore the parameters saved by ``tl.files.save_npz_dict()``.
Parameters
----------
name : str
The name of the `.npz` file.
sess : Session
TensorFlow Session.
"""
if sess is None:
raise ValueError("sessio... | Restore the parameters saved by ``tl.files.save_npz_dict()``.
Parameters
----------
name : str
The name of the `.npz` file.
sess : Session
TensorFlow Session. |
def rename(name, new_name, root=None):
'''
Change the username for a named user
name
User to modify
new_name
New value of the login name
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' user.rename name new_name
'''
if inf... | Change the username for a named user
name
User to modify
new_name
New value of the login name
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' user.rename name new_name |
def map(self, func):
"""
Return a dictionary of the results of func applied to each
of the segmentlist objects in self.
Example:
>>> x = segmentlistdict()
>>> x["H1"] = segmentlist([segment(0, 10)])
>>> x["H2"] = segmentlist([segment(5, 15)])
>>> x.map(lambda l: 12 in l)
{'H2': True, 'H1': False}
... | Return a dictionary of the results of func applied to each
of the segmentlist objects in self.
Example:
>>> x = segmentlistdict()
>>> x["H1"] = segmentlist([segment(0, 10)])
>>> x["H2"] = segmentlist([segment(5, 15)])
>>> x.map(lambda l: 12 in l)
{'H2': True, 'H1': False} |
def list_tables(self, limit=None, start_table=None):
"""
Return a list of the names of all Tables associated with the
current account and region.
TODO - Layer2 should probably automatically handle pagination.
:type limit: int
:param limit: The maximum number of tables to... | Return a list of the names of all Tables associated with the
current account and region.
TODO - Layer2 should probably automatically handle pagination.
:type limit: int
:param limit: The maximum number of tables to return.
:type start_table: str
:param limit: The name o... |
def create(self, serviceBinding):
"""
Create a new external service.
The service must include all of the details required to connect
and authenticate to the external service in the credentials property.
Parameters:
- serviceName (string) - Name of the service
... | Create a new external service.
The service must include all of the details required to connect
and authenticate to the external service in the credentials property.
Parameters:
- serviceName (string) - Name of the service
- serviceType (string) - must be either eventst... |
def getDynDnsClientForConfig(config, plugins=None):
"""Instantiate and return a complete and working dyndns client.
:param config: a dictionary with configuration keys
:param plugins: an object that implements PluginManager
"""
initparams = {}
if "interval" in config:
initparams["detect... | Instantiate and return a complete and working dyndns client.
:param config: a dictionary with configuration keys
:param plugins: an object that implements PluginManager |
def loaded_ret(ret, loaded, test, debug, compliance_report=False, opts=None):
'''
Return the final state output.
ret
The initial state output structure.
loaded
The loaded dictionary.
'''
# Always get the comment
changes = {}
ret['comment'] = loaded['comment']
if 'diff... | Return the final state output.
ret
The initial state output structure.
loaded
The loaded dictionary. |
def get_root_families(self):
"""Gets the root families in the family hierarchy.
A node with no parents is an orphan. While all family ``Ids``
are known to the hierarchy, an orphan does not appear in the
hierarchy unless explicitly added as a root node or child of
another node.
... | Gets the root families in the family hierarchy.
A node with no parents is an orphan. While all family ``Ids``
are known to the hierarchy, an orphan does not appear in the
hierarchy unless explicitly added as a root node or child of
another node.
return: (osid.relationship.Famil... |
def get_flux(self, reaction):
"""Get resulting flux value for reaction."""
return self._prob.result.get_value(self._v(reaction)) | Get resulting flux value for reaction. |
def create_powerflow_problem(timerange, components):
"""
Create PyPSA network object and fill with data
Parameters
----------
timerange: Pandas DatetimeIndex
Time range to be analyzed by PF
components: dict
Returns
-------
network: PyPSA powerflow problem object
"""
... | Create PyPSA network object and fill with data
Parameters
----------
timerange: Pandas DatetimeIndex
Time range to be analyzed by PF
components: dict
Returns
-------
network: PyPSA powerflow problem object |
def process_amqp_msgs(self):
"""Process AMQP queue messages.
It connects to AMQP server and calls callbacks to process DCNM events,
i.e. routing key containing '.cisco.dcnm.', once they arrive in the
queue.
"""
LOG.info('Starting process_amqp_msgs...')
while Tru... | Process AMQP queue messages.
It connects to AMQP server and calls callbacks to process DCNM events,
i.e. routing key containing '.cisco.dcnm.', once they arrive in the
queue. |
def make_rendition(self, width, height):
'''build a rendition
0 x 0 -> will give master URL
only width -> will make a renditions with master's aspect ratio
width x height -> will make an image potentialy cropped
'''
image = Image.open(self.master)
format = image.... | build a rendition
0 x 0 -> will give master URL
only width -> will make a renditions with master's aspect ratio
width x height -> will make an image potentialy cropped |
def add_precip_file(self, precip_file_path, interpolation_type=None):
"""
Adds a precip file to project with interpolation_type
"""
# precip file read in
self._update_card('PRECIP_FILE', precip_file_path, True)
if interpolation_type is None:
# check if precip... | Adds a precip file to project with interpolation_type |
def info():
"""
Generate information for a bug report.
Based on the requests package help utility module.
"""
try:
platform_info = {"system": platform.system(), "release": platform.release()}
except IOError:
platform_info = {"system": "Unknown", "release": "Unknown"}
impleme... | Generate information for a bug report.
Based on the requests package help utility module. |
def _check_uuid_fmt(self):
"""Checks .uuid_fmt, and raises an exception if it is not valid."""
if self.uuid_fmt not in UUIDField.FORMATS:
raise FieldValueRangeException(
"Unsupported uuid_fmt ({})".format(self.uuid_fmt)) | Checks .uuid_fmt, and raises an exception if it is not valid. |
def release(ctx, version):
"""
``version`` should be a string like '0.4' or '1.0'.
"""
invoke.run("git tag -s {0} -m '{0} release'".format(version))
invoke.run("git push --tags")
invoke.run("python setup.py sdist")
invoke.run("twine upload -s dist/PyNaCl-{0}* ".format(version))
sessio... | ``version`` should be a string like '0.4' or '1.0'. |
def fromCSV(csvfile,out=None,fieldnames=None,fmtparams=None,conv_func={},
empty_to_None=[]):
"""Conversion from CSV to PyDbLite
csvfile : name of the CSV file in the file system
out : path for the new PyDbLite base in the file system
fieldnames : list of field names. If set to None, the fie... | Conversion from CSV to PyDbLite
csvfile : name of the CSV file in the file system
out : path for the new PyDbLite base in the file system
fieldnames : list of field names. If set to None, the field names must
be present in the first line of the CSV file
fmtparams : the format paramete... |
def index():
"""Display the Scout dashboard."""
accessible_institutes = current_user.institutes
if not 'admin' in current_user.roles:
accessible_institutes = current_user.institutes
if not accessible_institutes:
flash('Not allowed to see information - please visit the dashboard l... | Display the Scout dashboard. |
def refresh(self, only_closed=False):
"""refresh ports status
Args:
only_closed - check status only for closed ports
"""
if only_closed:
opened = filter(self.__check_port, self.__closed)
self.__closed = self.__closed.difference(opened)
self._... | refresh ports status
Args:
only_closed - check status only for closed ports |
def _summarize_combined(samples, vkey):
"""Prepare summarized CSV and plot files for samples to combine together.
Helps handle cases where we want to summarize over multiple samples.
"""
validate_dir = utils.safe_makedir(os.path.join(samples[0]["dirs"]["work"], vkey))
combined, _ = _group_validate_... | Prepare summarized CSV and plot files for samples to combine together.
Helps handle cases where we want to summarize over multiple samples. |
def cleanup(self):
"""
Attempt to set a new current symlink if it is broken. If no other
prefixes exist and the workdir is empty, try to delete the entire
workdir.
Raises:
:exc:`~MalformedWorkdir`: if no prefixes were found, but the
workdir is not emp... | Attempt to set a new current symlink if it is broken. If no other
prefixes exist and the workdir is empty, try to delete the entire
workdir.
Raises:
:exc:`~MalformedWorkdir`: if no prefixes were found, but the
workdir is not empty. |
def upgrade(*pkgs):
'''
Runs an update operation on the specified packages, or all packages if none is specified.
:type pkgs: list(str)
:param pkgs:
List of packages to update
:return: The upgraded packages. Example element: ``['libxslt-1.1.0', 'libxslt-1.1.10']``
:rtype: list(tuple(st... | Runs an update operation on the specified packages, or all packages if none is specified.
:type pkgs: list(str)
:param pkgs:
List of packages to update
:return: The upgraded packages. Example element: ``['libxslt-1.1.0', 'libxslt-1.1.10']``
:rtype: list(tuple(str, str))
.. code-block:: ba... |
def interface_lookup(interfaces, hwaddr, address_type):
"""Search the address within the interface list."""
for interface in interfaces.values():
if interface.get('hwaddr') == hwaddr:
for address in interface.get('addrs'):
if address.get('type') == address_type:
... | Search the address within the interface list. |
def _check_perpendicular_r2_axis(self, axis):
"""
Checks for R2 axes perpendicular to unique axis. For handling
symmetric top molecules.
"""
min_set = self._get_smallest_set_not_on_axis(axis)
for s1, s2 in itertools.combinations(min_set, 2):
test_axis = np.cr... | Checks for R2 axes perpendicular to unique axis. For handling
symmetric top molecules. |
def call_runtime(self):
'''
Execute the runtime
'''
cache = self.gather_cache()
chunks = self.get_chunks()
interval = self.opts['thorium_interval']
recompile = self.opts.get('thorium_recompile', 300)
r_start = time.time()
while True:
ev... | Execute the runtime |
def dataframe(self, spark, group_by='greedy', limit=None, sample=1, seed=42, decode=None, summaries=None, schema=None, table_name=None):
"""Convert RDD returned from records function to a dataframe
:param spark: a SparkSession object
:param group_by: specifies a paritition strategy for the obje... | Convert RDD returned from records function to a dataframe
:param spark: a SparkSession object
:param group_by: specifies a paritition strategy for the objects
:param limit: maximum number of objects to retrieve
:param decode: an optional transformation to apply to the objects retrieved
... |
def _validate_type(cls, typeobj):
"""
Validate that all required type methods are implemented.
At minimum a type must have:
- a convert() or convert_binary() function
- a default_formatter() function
Raises an ArgumentError if the type is not valid
"""
... | Validate that all required type methods are implemented.
At minimum a type must have:
- a convert() or convert_binary() function
- a default_formatter() function
Raises an ArgumentError if the type is not valid |
def _create_event(instance, action):
"""
Create a new event, getting the use if django-cuser is available.
"""
user = None
user_repr = repr(user)
if CUSER:
user = CuserMiddleware.get_user()
user_repr = repr(user)
if user is not None and user.is_anonymous:
user... | Create a new event, getting the use if django-cuser is available. |
def decode_body(cls, header, f):
"""Generates a `MqttPingresp` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pingresp`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Rais... | Generates a `MqttPingresp` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pingresp`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
... |
def validate_token(self, request, consumer, token):
"""
Check the token and raise an `oauth.Error` exception if invalid.
"""
oauth_server, oauth_request = oauth_provider.utils.initialize_server_request(request)
oauth_server.verify_request(oauth_request, consumer, token) | Check the token and raise an `oauth.Error` exception if invalid. |
def temp_url(self, duration=120):
"""Returns a temporary URL for the given key."""
return self.bucket._boto_s3.meta.client.generate_presigned_url(
'get_object',
Params={'Bucket': self.bucket.name, 'Key': self.name},
ExpiresIn=duration
) | Returns a temporary URL for the given key. |
def _init(self):
"""Read the b"\\r\\n" at the end of the message."""
read_values = []
read = self._file.read
last = read(1)
current = read(1)
while last != b'' and current != b'' and not \
(last == b'\r' and current == b'\n'):
read_values.appen... | Read the b"\\r\\n" at the end of the message. |
def searchFilesIndex(self, nameData, fileData, fileIndex, searchString, category="", math=False, game=False, extension=""):
"""Search the files index using the namedata and returns the filedata"""
try:
fileFile = open(fileIndex, 'rt')
except IOError:
self.repo.printd("Error: Unable to read index file " + se... | Search the files index using the namedata and returns the filedata |
def getAsKmlGridAnimation(self, session, projectFile=None, path=None, documentName=None, colorRamp=None, alpha=1.0, noDataValue=0.0):
"""
Retrieve the WMS dataset as a gridded time stamped KML string.
Args:
session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object b... | Retrieve the WMS dataset as a gridded time stamped KML string.
Args:
session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database.
projectFile(:class:`gsshapy.orm.ProjectFile`): Project file object for the GSSHA project to which the WMS da... |
def disable_snapshots(self, volume_id, schedule_type):
"""Disables snapshots for a specific block volume at a given schedule
:param integer volume_id: The id of the volume
:param string schedule_type: 'HOURLY'|'DAILY'|'WEEKLY'
:return: Returns whether successfully disabled or not
... | Disables snapshots for a specific block volume at a given schedule
:param integer volume_id: The id of the volume
:param string schedule_type: 'HOURLY'|'DAILY'|'WEEKLY'
:return: Returns whether successfully disabled or not |
def normalize_weekly(data):
"""Normalization for dining menu data"""
if "tblMenu" not in data["result_data"]["Document"]:
data["result_data"]["Document"]["tblMenu"] = []
if isinstance(data["result_data"]["Document"]["tblMenu"], dict):
data["result_data"]["Document"]["tblMenu"] = [data["resul... | Normalization for dining menu data |
def normalize_name(name):
"""
Given a key name (e.g. "LEFT CONTROL"), clean up the string and convert to
the canonical representation (e.g. "left ctrl") if one is known.
"""
if not name or not isinstance(name, basestring):
raise ValueError('Can only normalize non-empty string names. Unexpect... | Given a key name (e.g. "LEFT CONTROL"), clean up the string and convert to
the canonical representation (e.g. "left ctrl") if one is known. |
def nCr(n, r):
"""
Calculates nCr.
Args:
n (int): total number of items.
r (int): items to choose
Returns:
nCr.
"""
f = math.factorial
return int(f(n) / f(r) / f(n-r)) | Calculates nCr.
Args:
n (int): total number of items.
r (int): items to choose
Returns:
nCr. |
def repl_update(self, config):
"""Reconfig Replicaset with new config"""
cfg = config.copy()
cfg['version'] += 1
try:
result = self.run_command("replSetReconfig", cfg)
if int(result.get('ok', 0)) != 1:
return False
except pymongo.errors.Aut... | Reconfig Replicaset with new config |
def _mean_prediction(self, mu, Y, h, t_z):
""" Creates a h-step ahead mean prediction
Parameters
----------
mu : np.ndarray
The past predicted values
Y : np.ndarray
The past data
h : int
How many steps ahead for the prediction
... | Creates a h-step ahead mean prediction
Parameters
----------
mu : np.ndarray
The past predicted values
Y : np.ndarray
The past data
h : int
How many steps ahead for the prediction
t_z : np.ndarray
A vector of (transforme... |
def get_authn_contexts(self):
"""
Gets the authentication contexts
:returns: The authentication classes for the SAML Response
:rtype: list
"""
authn_context_nodes = self.__query_assertion('/saml:AuthnStatement/saml:AuthnContext/saml:AuthnContextClassRef')
return ... | Gets the authentication contexts
:returns: The authentication classes for the SAML Response
:rtype: list |
def _set_bgp_state(self, v, load=False):
"""
Setter method for bgp_state, mapped from YANG variable /bgp_state/neighbor/evpn/bgp_state (bgp-states)
If this variable is read-only (config: false) in the
source YANG file, then _set_bgp_state is considered as a private
method. Backends looking to popula... | Setter method for bgp_state, mapped from YANG variable /bgp_state/neighbor/evpn/bgp_state (bgp-states)
If this variable is read-only (config: false) in the
source YANG file, then _set_bgp_state is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj... |
def validateDocument(self, ctxt):
"""Try to validate the document instance basically it does
the all the checks described by the XML Rec i.e. validates
the internal and external subset (if present) and validate
the document tree. """
if ctxt is None: ctxt__o = None
... | Try to validate the document instance basically it does
the all the checks described by the XML Rec i.e. validates
the internal and external subset (if present) and validate
the document tree. |
def put_file(client, source_file, destination_file):
"""
Copy file to instance using Paramiko client connection.
"""
try:
sftp_client = client.open_sftp()
sftp_client.put(source_file, destination_file)
except Exception as error:
raise IpaUtilsException(
'Error cop... | Copy file to instance using Paramiko client connection. |
def generate_string_to_sign(date, region, canonical_request):
"""
Generate string to sign.
:param date: Date is input from :meth:`datetime.datetime`
:param region: Region should be set to bucket region.
:param canonical_request: Canonical request generated previously.
"""
formatted_date_tim... | Generate string to sign.
:param date: Date is input from :meth:`datetime.datetime`
:param region: Region should be set to bucket region.
:param canonical_request: Canonical request generated previously. |
def _get_ids_from_hostname(self, hostname):
"""List VS ids which match the given hostname."""
results = self.list_instances(hostname=hostname, mask="id")
return [result['id'] for result in results] | List VS ids which match the given hostname. |
def _init_map(self):
"""stub"""
QuestionTextFormRecord._init_map(self)
QuestionFilesFormRecord._init_map(self)
super(QuestionTextAndFilesMixin, self)._init_map() | stub |
def _check_import_source():
"""Check if tlgu imported, if not import it."""
path_rel = '~/cltk_data/greek/software/greek_software_tlgu/tlgu.h'
path = os.path.expanduser(path_rel)
if not os.path.isfile(path):
try:
corpus_importer = CorpusImporter('greek')
... | Check if tlgu imported, if not import it. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.