code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def rgb_to_hsl(r, g, b):
"""Convert a color in r, g, b to a color in h, s, l"""
r = r or 0
g = g or 0
b = b or 0
r /= 255
g /= 255
b /= 255
max_ = max((r, g, b))
min_ = min((r, g, b))
d = max_ - min_
if not d:
h = 0
elif r is max_:
h = 60 * (g - b) / d
... | Convert a color in r, g, b to a color in h, s, l |
def str_digit_to_int(chr):
"""
Converts a string character to a decimal number.
Where "A"->10, "B"->11, "C"->12, ...etc
Args:
chr(str): A single character in the form of a string.
Returns:
The integer value of the input string digit.
"""
# 0 - 9
if chr in ("... | Converts a string character to a decimal number.
Where "A"->10, "B"->11, "C"->12, ...etc
Args:
chr(str): A single character in the form of a string.
Returns:
The integer value of the input string digit. |
def _reshape_m_vecs(self):
"""return list of arrays, each array represents a different n mode"""
lst = []
for n in xrange(0, self.nmax + 1):
mlst = []
if n <= self.mmax:
nn = n
else:
nn = self.mmax
... | return list of arrays, each array represents a different n mode |
def parse_args(args):
"""
Parse command line parameters
:param args: command line parameters as list of strings
:return: command line parameters as :obj:`argparse.Namespace`
"""
parser = argparse.ArgumentParser(
description="Build html reveal.js slides from markdown in docs/ dir")
p... | Parse command line parameters
:param args: command line parameters as list of strings
:return: command line parameters as :obj:`argparse.Namespace` |
def __parse_precipfc_data(data, timeframe):
"""Parse the forecasted precipitation data."""
result = {AVERAGE: None, TOTAL: None, TIMEFRAME: None}
log.debug("Precipitation data: %s", data)
lines = data.splitlines()
index = 1
totalrain = 0
numberoflines = 0
nrlines = min(len(lines), round... | Parse the forecasted precipitation data. |
def check_api_error(api_response):
print(api_response)
"""Check if returned API response contains an error."""
if type(api_response) == dict and 'code' in api_response and api_response['code'] <> 200:
print("Server response code: %s" % api_response['code'])
print("Server response: %s... | Check if returned API response contains an error. |
def checkout(self):
'''
Checkout the configured branch/tag. We catch an "Exception" class here
instead of a specific exception class because the exceptions raised by
GitPython when running these functions vary in different versions of
GitPython.
'''
tgt_ref = self... | Checkout the configured branch/tag. We catch an "Exception" class here
instead of a specific exception class because the exceptions raised by
GitPython when running these functions vary in different versions of
GitPython. |
def _sub16(ins):
''' Pops last 2 words from the stack and subtract them.
Then push the result onto the stack. Top of the stack is
subtracted Top -1
Optimizations:
* If 2nd op is ZERO,
then do NOTHING: A - 0 = A
* If any of the operands is < 4, then
DEC is used
* If a... | Pops last 2 words from the stack and subtract them.
Then push the result onto the stack. Top of the stack is
subtracted Top -1
Optimizations:
* If 2nd op is ZERO,
then do NOTHING: A - 0 = A
* If any of the operands is < 4, then
DEC is used
* If any of the operands is > 6... |
def send(self, content=None, *, wait=False, username=None, avatar_url=None, tts=False,
file=None, files=None, embed=None, embeds=None):
"""|maybecoro|
Sends a message using the webhook.
If the webhook is constructed with a :class:`RequestsWebhookAdapter` the... | |maybecoro|
Sends a message using the webhook.
If the webhook is constructed with a :class:`RequestsWebhookAdapter` then this is
not a coroutine.
The content must be a type that can convert to a string through ``str(content)``.
To upload a single file, the ``file`` parameter ... |
def build(ctx, less=False, docs=False, js=False, force=False):
"""Build everything and collectstatic.
"""
specified = any([less, docs, js])
buildall = not specified
if buildall or less:
less_fname = ctx.pkg.source_less / ctx.pkg.name + '.less'
if less_fname.exists():
les... | Build everything and collectstatic. |
def parse_string(self):
"""Tokenize a Fortran string."""
word = ''
if self.prior_delim:
delim = self.prior_delim
self.prior_delim = None
else:
delim = self.char
word += self.char
self.update_chars()
while True:
... | Tokenize a Fortran string. |
def query(params):
"""`params` is a city name or a city name + hospital name.
CLI:
1. query all putian hospitals in a city:
$ iquery -p 南京
+------+
| 南京 |
+------+
|... |
+------+
|... |
+------+
...
2. query if the... | `params` is a city name or a city name + hospital name.
CLI:
1. query all putian hospitals in a city:
$ iquery -p 南京
+------+
| 南京 |
+------+
|... |
+------+
|... |
+------+
...
2. query if the hospital in the city is p... |
def get_summary_and_description(self):
"""
Compat: drf-yasg 1.12+
"""
summary = self.get_summary()
_, description = super().get_summary_and_description()
return summary, description | Compat: drf-yasg 1.12+ |
def simplify_recursive(typ):
# type: (AbstractType) -> AbstractType
"""Simplify all components of a type."""
if isinstance(typ, UnionType):
return combine_types(typ.items)
elif isinstance(typ, ClassType):
simplified = ClassType(typ.name, [simplify_recursive(arg) for arg in typ.args])
... | Simplify all components of a type. |
def get_port_channel_detail_output_lacp_aggr_member_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_channel_detail = ET.Element("get_port_channel_detail")
config = get_port_channel_detail
output = ET.SubElement(get_port_ch... | Auto Generated Code |
def _load_ini(path):
"""
Load an INI file from *path*.
"""
cfg = RawConfigParser()
with codecs.open(path, mode="r", encoding="utf-8") as f:
try:
cfg.read_file(f)
except AttributeError:
cfg.readfp(f)
return cfg | Load an INI file from *path*. |
def particle_clusters(
particle_locations, particle_weights=None,
eps=0.5, min_particles=5, metric='euclidean',
weighted=False, w_pow=0.5,
quiet=True
):
"""
Yields an iterator onto tuples ``(cluster_label, cluster_particles)``,
where ``cluster_label`` is an `int` identify... | Yields an iterator onto tuples ``(cluster_label, cluster_particles)``,
where ``cluster_label`` is an `int` identifying the cluster (or ``NOISE``
for the particles lying outside of all clusters), and where
``cluster_particles`` is an array of ``dtype`` `bool` specifying the indices
of all particles in th... |
def _run_introspection(self, runtime='', whitelist=[], verbose=False):
""" Figure out which objects are opened by a test binary and are matched by the white list.
:param runtime: The binary to run.
:type runtime: str
:param whitelist: A list of regular expressions describing acceptable library names
... | Figure out which objects are opened by a test binary and are matched by the white list.
:param runtime: The binary to run.
:type runtime: str
:param whitelist: A list of regular expressions describing acceptable library names
:type whitelist: [str] |
def save_translations(self, *args, **kwargs):
"""
The method to save all translations.
This can be overwritten to implement any custom additions.
This method calls :func:`save_translation` for every fetched language.
:param args: Any custom arguments to pass to :func:`save`.
... | The method to save all translations.
This can be overwritten to implement any custom additions.
This method calls :func:`save_translation` for every fetched language.
:param args: Any custom arguments to pass to :func:`save`.
:param kwargs: Any custom arguments to pass to :func:`save`. |
def room_members(self, stream_id):
''' get list of room members '''
req_hook = 'pod/v2/room/' + str(stream_id) + '/membership/list'
req_args = None
status_code, response = self.__rest__.GET_query(req_hook, req_args)
self.logger.debug('%s: %s' % (status_code, response))
re... | get list of room members |
def get_timespan(name):
"""
This function extracts the time span from the Tplot Variables stored in memory.
Parameters:
name : str
Name of the tplot variable
Returns:
time_begin : float
The beginning of the time series
time_end : float
... | This function extracts the time span from the Tplot Variables stored in memory.
Parameters:
name : str
Name of the tplot variable
Returns:
time_begin : float
The beginning of the time series
time_end : float
The end of the time series... |
def _parse_date_time_time_zone(self, date_time_time_zone):
""" Parses and convert to protocol timezone a dateTimeTimeZone resource
This resource is a dict with a date time and a windows timezone
This is a common structure on Microsoft apis so it's included here.
"""
if date_time_... | Parses and convert to protocol timezone a dateTimeTimeZone resource
This resource is a dict with a date time and a windows timezone
This is a common structure on Microsoft apis so it's included here. |
def try_get_department(department_or_code):
"""
Try to take the first department code, or fall back to string as passed
"""
try:
value = take_first_department_code(department_or_code)
except AssertionError:
value = department_or_code
if value in DEPARTMENT_MAPPING:
value... | Try to take the first department code, or fall back to string as passed |
def add_subcomponent(self, name):
"""
Create an instance of :class:`SubComponent <hl7apy.core.SubComponent>` having the given name
:param name: the name of the subcomponent to be created (e.g. CE_1)
:return: an instance of :class:`SubComponent <hl7apy.core.SubComponent>`
>>> c ... | Create an instance of :class:`SubComponent <hl7apy.core.SubComponent>` having the given name
:param name: the name of the subcomponent to be created (e.g. CE_1)
:return: an instance of :class:`SubComponent <hl7apy.core.SubComponent>`
>>> c = Component(datatype='CE')
>>> ce_1 = c.add_su... |
def execute(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
jid='',
kwarg=None,
**kwargs):
'''
.. versionadded:: 2017.7.0
Execute ``fun`` on all minions matched by ``tgt`` and ``tgt_type``.
Paramete... | .. versionadded:: 2017.7.0
Execute ``fun`` on all minions matched by ``tgt`` and ``tgt_type``.
Parameter ``fun`` is the name of execution module function to call.
This function should mainly be used as a helper for runner modules,
in order to avoid redundant code.
For example, when inside a runner... |
def generate_component_annotation_miriam_match(elements, component, db):
"""
Tabulate which MIRIAM databases the element's annotation match.
If the relevant MIRIAM identifier is not in an element's annotation it is
ignored.
Parameters
----------
elements : list
Elements of a model,... | Tabulate which MIRIAM databases the element's annotation match.
If the relevant MIRIAM identifier is not in an element's annotation it is
ignored.
Parameters
----------
elements : list
Elements of a model, either metabolites or reactions.
component : {"metabolites", "reactions"}
... |
def add_overlay_to_slice_file(
self,
filename,
overlay,
i_overlay,
filename_out=None
):
""" Function adds overlay to existing file.
"""
if filename_out is None:
filename_out = filename
filename = op.expanduser(filename)
data... | Function adds overlay to existing file. |
def fetch_twitter_lists_for_user_ids_generator(twitter_app_key,
twitter_app_secret,
user_id_list):
"""
Collects at most 500 Twitter lists for each user from an input list of Twitter user ids.
Inputs: - twitter_app... | Collects at most 500 Twitter lists for each user from an input list of Twitter user ids.
Inputs: - twitter_app_key: What is says on the tin.
- twitter_app_secret: Ditto.
- user_id_list: A python list of Twitter user ids.
Yields: - user_twitter_id: A Twitter user id.
- twitt... |
def search(self, keyword):
"""Return all buildings related to the provided query.
:param keyword:
The keyword for your map search
>>> results = n.search('Harrison')
"""
params = {
"source": "map",
"description": keyword
}
data... | Return all buildings related to the provided query.
:param keyword:
The keyword for your map search
>>> results = n.search('Harrison') |
def send_static_message(sender, message):
"""Send a static message to the listeners.
Static messages represents a whole new message. Usually it will
replace the previous message.
.. versionadded:: 3.3
:param sender: The sender.
:type sender: object
:param message: An instance of our rich... | Send a static message to the listeners.
Static messages represents a whole new message. Usually it will
replace the previous message.
.. versionadded:: 3.3
:param sender: The sender.
:type sender: object
:param message: An instance of our rich message class.
:type message: safe.messaging... |
def _parse_cod_segment(cls, fptr):
"""Parse the COD segment.
Parameters
----------
fptr : file
Open file object.
Returns
-------
CODSegment
The current COD segment.
"""
offset = fptr.tell() - 2
read_buffer = fptr.... | Parse the COD segment.
Parameters
----------
fptr : file
Open file object.
Returns
-------
CODSegment
The current COD segment. |
def get(self, option, default=undefined, cast=undefined):
"""
Return the value for option or default if defined.
"""
if option in self.repository:
value = self.repository.get(option)
else:
value = default
if isinstance(value, Undefined):
... | Return the value for option or default if defined. |
def record(self, frame_parameters: dict=None, channels_enabled: typing.List[bool]=None, timeout: float=None) -> typing.List[DataAndMetadata.DataAndMetadata]:
"""Record data and return a list of data_and_metadata objects.
.. versionadded:: 1.0
:param frame_parameters: The frame parameters for t... | Record data and return a list of data_and_metadata objects.
.. versionadded:: 1.0
:param frame_parameters: The frame parameters for the record. Pass None for defaults.
:type frame_parameters: :py:class:`FrameParameters`
:param channels_enabled: The enabled channels for the record. Pass... |
def do( self, params ):
"""Perform the number of repetitions we want. The results returned
will be a list of the results dicts generated by the repeated experiments.
The metedata for each experiment will include an entry
:attr:`RepeatedExperiment.REPETITIONS` for the number of
re... | Perform the number of repetitions we want. The results returned
will be a list of the results dicts generated by the repeated experiments.
The metedata for each experiment will include an entry
:attr:`RepeatedExperiment.REPETITIONS` for the number of
repetitions that occurred (which will... |
def zsum(s, *args, **kwargs):
"""
pandas 0.21.0 changes sum() behavior so that the result of applying sum
over an empty DataFrame is NaN.
Meant to be set as pd.Series.zsum = zsum.
"""
return 0 if s.empty else s.sum(*args, **kwargs) | pandas 0.21.0 changes sum() behavior so that the result of applying sum
over an empty DataFrame is NaN.
Meant to be set as pd.Series.zsum = zsum. |
def dict_contents(self, use_dict=None, as_class=dict):
"""Return the contents of an object as a dict."""
if _debug: APDU._debug("dict_contents use_dict=%r as_class=%r", use_dict, as_class)
# make/extend the dictionary of content
if use_dict is None:
use_dict = as_class()
... | Return the contents of an object as a dict. |
def backup(self, id=None, src=None, timestamp=None):
"""
This runs a backup job outside of the storage api,
which is useful for performance testing backups
"""
# Set basic Logging
logging.basicConfig()
# Get the lunr logger
log = logger.get_logger()
... | This runs a backup job outside of the storage api,
which is useful for performance testing backups |
def set_split_extents_by_tile_shape(self):
"""
Sets split shape :attr:`split_shape` and
split extents (:attr:`split_begs` and :attr:`split_ends`)
from value of :attr:`tile_shape`.
"""
self.split_shape = ((self.array_shape - 1) // self.tile_shape) + 1
self.split_be... | Sets split shape :attr:`split_shape` and
split extents (:attr:`split_begs` and :attr:`split_ends`)
from value of :attr:`tile_shape`. |
def index_table(self, axis=None, baseline=None, prune=False):
"""Return index percentages for a given axis and baseline.
The index values represent the difference of the percentages to the
corresponding baseline values. The baseline values are the univariate
percentages of the correspon... | Return index percentages for a given axis and baseline.
The index values represent the difference of the percentages to the
corresponding baseline values. The baseline values are the univariate
percentages of the corresponding variable. |
def login(self):
""" Logs the user in, returns the result
Returns
bool - Whether or not the user logged in successfully
"""
# Request index to obtain initial cookies and look more human
pg = self.getPage("http://www.neopets.com")
form = pg.... | Logs the user in, returns the result
Returns
bool - Whether or not the user logged in successfully |
def _check_vpcs_version(self):
"""
Checks if the VPCS executable version is >= 0.8b or == 0.6.1.
"""
try:
output = yield from subprocess_check_output(self._vpcs_path(), "-v", cwd=self.working_dir)
match = re.search("Welcome to Virtual PC Simulator, version ([0-9a-... | Checks if the VPCS executable version is >= 0.8b or == 0.6.1. |
def get_accessibles(request, roles=None):
"""
Returns the list of *dictionnaries* for which the accounts are
accessibles by ``request.user`` filtered by ``roles`` if present.
"""
results = []
for role_name, organizations in six.iteritems(request.session.get(
... | Returns the list of *dictionnaries* for which the accounts are
accessibles by ``request.user`` filtered by ``roles`` if present. |
def plot_dop(bands, int_max, dop, hund_cu, name):
"""Plot of Quasiparticle weight for N degenerate bands
under selected doping shows transition only at half-fill
the rest are metallic states"""
data = ssplt.calc_z(bands, dop, np.arange(0, int_max, 0.1), hund_cu, name)
ssplt.plot_curves_z(data,... | Plot of Quasiparticle weight for N degenerate bands
under selected doping shows transition only at half-fill
the rest are metallic states |
def collapse_pair(graph, survivor: BaseEntity, victim: BaseEntity) -> None:
"""Rewire all edges from the synonymous node to the survivor node, then deletes the synonymous node.
Does not keep edges between the two nodes.
:param pybel.BELGraph graph: A BEL graph
:param survivor: The BEL node to collapse... | Rewire all edges from the synonymous node to the survivor node, then deletes the synonymous node.
Does not keep edges between the two nodes.
:param pybel.BELGraph graph: A BEL graph
:param survivor: The BEL node to collapse all edges on the synonym to
:param victim: The BEL node to collapse into the s... |
def change_jira_status(test_key, test_status, test_comment, test_attachments):
"""Update test status in Jira
:param test_key: test case key in Jira
:param test_status: test case status
:param test_comment: test case comments
:param test_attachments: test case attachments
"""
logger = loggin... | Update test status in Jira
:param test_key: test case key in Jira
:param test_status: test case status
:param test_comment: test case comments
:param test_attachments: test case attachments |
def get_score(self, terms):
"""Get score for a list of terms.
:type terms: list
:param terms: A list of terms to be analyzed.
:returns: dict
"""
assert isinstance(terms, list) or isinstance(terms, tuple)
score_li = np.asarray([self._get_score(t) ... | Get score for a list of terms.
:type terms: list
:param terms: A list of terms to be analyzed.
:returns: dict |
def count_matches(self):
"""Set the matches_p, matches_c and rows attributes."""
try:
self.fn = self.fo.name
rows = self.file_rows(self.fo)
self.fo.seek(0)
except AttributeError:
with open(self.fn) as fo:
rows = self.file_rows(fo)... | Set the matches_p, matches_c and rows attributes. |
def get_hook(hook_name):
"""Returns the specified hook.
Args:
hook_name (str)
Returns:
str - (the content of) the hook
Raises:
HookNotFoundError
"""
if not pkg_resources.resource_exists(__name__, hook_name):
raise HookNotFoundError
return pkg_resources.reso... | Returns the specified hook.
Args:
hook_name (str)
Returns:
str - (the content of) the hook
Raises:
HookNotFoundError |
def init_parser():
""" function to init option parser """
usage = "usage: %prog -u user -s secret -n name [-l label] \
[-t title] [-c callback] [TEXT]"
parser = OptionParser(usage, version="%prog " + notifo.__version__)
parser.add_option("-u", "--user", action="store", dest="user",
... | function to init option parser |
def calculate_ellipse_description(covariance, scale = 2.0):
"""!
@brief Calculates description of ellipse using covariance matrix.
@param[in] covariance (numpy.array): Covariance matrix for which ellipse area should be calculated.
@param[in] scale (float): Scale of the ellipse.
@ret... | !
@brief Calculates description of ellipse using covariance matrix.
@param[in] covariance (numpy.array): Covariance matrix for which ellipse area should be calculated.
@param[in] scale (float): Scale of the ellipse.
@return (float, float, float) Return ellipse description: angle, width, ... |
def one(prompt, *args, **kwargs):
"""Instantiates a picker, registers custom handlers for going back,
and starts the picker.
"""
indicator = '‣'
if sys.version_info < (3, 0):
indicator = '>'
def go_back(picker):
return None, -1
options, verbose_options = prepare_options(arg... | Instantiates a picker, registers custom handlers for going back,
and starts the picker. |
def average_gradients(tower_gradients):
r'''
A routine for computing each variable's average of the gradients obtained from the GPUs.
Note also that this code acts as a synchronization point as it requires all
GPUs to be finished with their mini-batch before it can run to completion.
'''
# List ... | r'''
A routine for computing each variable's average of the gradients obtained from the GPUs.
Note also that this code acts as a synchronization point as it requires all
GPUs to be finished with their mini-batch before it can run to completion. |
def get_attributes(var):
"""
Given a varaible, return the list of attributes that are available inside
of a template
"""
is_valid = partial(is_valid_in_template, var)
return list(filter(is_valid, dir(var))) | Given a varaible, return the list of attributes that are available inside
of a template |
def list_dataset_uris(cls, base_uri, config_path):
"""Return list containing URIs in location given by base_uri."""
parsed_uri = generous_parse_uri(base_uri)
uri_list = []
path = parsed_uri.path
if IS_WINDOWS:
path = unix_to_windows_path(parsed_uri.path, parsed_uri.... | Return list containing URIs in location given by base_uri. |
def transp(I,J,c,d,M):
"""transp -- model for solving the transportation problem
Parameters:
I - set of customers
J - set of facilities
c[i,j] - unit transportation cost on arc (i,j)
d[i] - demand at node i
M[j] - capacity
Returns a model, ready to be solved.
"""
... | transp -- model for solving the transportation problem
Parameters:
I - set of customers
J - set of facilities
c[i,j] - unit transportation cost on arc (i,j)
d[i] - demand at node i
M[j] - capacity
Returns a model, ready to be solved. |
def cancel_order(self, order_id, private_key):
"""
This function is a wrapper function around the create and execute cancellation functions to help make this
processes simpler for the end user by combining these requests in 1 step.
Execution of this function is as follows::
... | This function is a wrapper function around the create and execute cancellation functions to help make this
processes simpler for the end user by combining these requests in 1 step.
Execution of this function is as follows::
cancel_order(order_id=order['id'], private_key=kp)
canc... |
def context_chunks(self, context):
"""
Retrieves all tokens, divided into the chunks in context ``context``.
Parameters
----------
context : str
Context name.
Returns
-------
chunks : list
Each item in ``chunks`` is a list of toke... | Retrieves all tokens, divided into the chunks in context ``context``.
Parameters
----------
context : str
Context name.
Returns
-------
chunks : list
Each item in ``chunks`` is a list of tokens. |
def media_url(self, with_ssl=False):
"""
Used to return a base media URL. Depending on whether we're serving
media remotely or locally, this either hands the decision off to the
backend, or just uses the value in settings.STATIC_URL.
args:
with_ssl: (bool) If T... | Used to return a base media URL. Depending on whether we're serving
media remotely or locally, this either hands the decision off to the
backend, or just uses the value in settings.STATIC_URL.
args:
with_ssl: (bool) If True, return an HTTPS url (depending on how
... |
def download(url, dir, filename=None, expect_size=None):
"""
Download URL to a directory.
Will figure out the filename automatically from URL, if not given.
"""
mkdir_p(dir)
if filename is None:
filename = url.split('/')[-1]
fpath = os.path.join(dir, filename)
if os.path.isfile(... | Download URL to a directory.
Will figure out the filename automatically from URL, if not given. |
def stop(self):
"""Stop the publisher.
"""
self.publish.setsockopt(zmq.LINGER, 1)
self.publish.close()
return self | Stop the publisher. |
def date_map(doc, datemap_list, time_format=None):
'''
For all the datetime fields in "datemap" find that key in doc and map the datetime object to
a strftime string. This pprint and others will print out readable datetimes.
'''
if datemap_list:
for i in datemap_list:... | For all the datetime fields in "datemap" find that key in doc and map the datetime object to
a strftime string. This pprint and others will print out readable datetimes. |
def remove_send_last_message(self, connection):
"""Removes a send_last_message function previously registered
with the Dispatcher.
Args:
connection (str): A locally unique identifier provided
by the receiver of messages.
"""
if connection in self._sen... | Removes a send_last_message function previously registered
with the Dispatcher.
Args:
connection (str): A locally unique identifier provided
by the receiver of messages. |
def _expand_data(self, old_data, new_data, group):
""" data expansion - uvision needs filename and path separately. """
for file in old_data:
if file:
extension = file.split(".")[-1].lower()
if extension in self.file_types.keys():
new_data[... | data expansion - uvision needs filename and path separately. |
def install_package_command(package_name):
'''install python package from pip'''
#TODO refactor python logic
if sys.platform == "win32":
cmds = 'python -m pip install --user {0}'.format(package_name)
else:
cmds = 'python3 -m pip install --user {0}'.format(package_name)
call(cmds, she... | install python package from pip |
def add_ssh_scheme_to_git_uri(uri):
# type: (S) -> S
"""Cleans VCS uris from pipenv.patched.notpip format"""
if isinstance(uri, six.string_types):
# Add scheme for parsing purposes, this is also what pip does
if uri.startswith("git+") and "://" not in uri:
uri = uri.replace("git+... | Cleans VCS uris from pipenv.patched.notpip format |
def is_base_form(self, univ_pos, morphology=None):
"""
Check whether we're dealing with an uninflected paradigm, so we can
avoid lemmatization entirely.
"""
morphology = {} if morphology is None else morphology
others = [key for key in morphology
if key ... | Check whether we're dealing with an uninflected paradigm, so we can
avoid lemmatization entirely. |
def alarm_on_log(self, alarm, matcher, skip=False):
"""Raise (or skip) the specified alarm when a log line matches the specified regexp.
:param AlarmType|list[AlarmType] alarm: Alarm.
:param str|unicode matcher: Regular expression to match log line.
:param bool skip:
"""
... | Raise (or skip) the specified alarm when a log line matches the specified regexp.
:param AlarmType|list[AlarmType] alarm: Alarm.
:param str|unicode matcher: Regular expression to match log line.
:param bool skip: |
def autoconf(self):
"""Implements Munin Plugin Auto-Configuration Option.
@return: True if plugin can be auto-configured, False otherwise.
"""
fpminfo = PHPfpmInfo(self._host, self._port, self._user, self._password,
self._monpath,... | Implements Munin Plugin Auto-Configuration Option.
@return: True if plugin can be auto-configured, False otherwise. |
def list_loadbalancers(call=None):
'''
Return a list of the loadbalancers that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-loadbalancers option'
)
... | Return a list of the loadbalancers that are on the provider |
def add_circle(self,
center_lat=None,
center_lng=None,
radius=None,
**kwargs):
""" Adds a circle dict to the Map.circles attribute
The circle in a sphere is called "spherical cap" and is defined in the
Google Maps API b... | Adds a circle dict to the Map.circles attribute
The circle in a sphere is called "spherical cap" and is defined in the
Google Maps API by at least the center coordinates and its radius, in
meters. A circle has color and opacity both for the border line and the
inside area.
It a... |
def normalize_attachment(attachment):
''' Convert attachment metadata from es to archivant format
This function makes side effect on input attachment
'''
res = dict()
res['type'] = 'attachment'
res['id'] = attachment['id']
del(attachment['id'])
res['u... | Convert attachment metadata from es to archivant format
This function makes side effect on input attachment |
def parse_headers(self, use_cookies, raw):
"""
analyze headers from file or raw messages
:return: (url, dat)
:rtype:
"""
if not raw:
packet = helper.to_str(helper.read_file(self.fpth))
else:
packet = raw
dat = {}
pks = [x ... | analyze headers from file or raw messages
:return: (url, dat)
:rtype: |
def get_variables(self, sort=None, collapse_same_ident=False):
"""
Get a list of variables.
:param str or None sort: Sort of the variable to get.
:param collapse_same_ident: Whether variables of the same identifier should be collapsed or not.
:return: A lis... | Get a list of variables.
:param str or None sort: Sort of the variable to get.
:param collapse_same_ident: Whether variables of the same identifier should be collapsed or not.
:return: A list of variables.
:rtype: list |
def _dataframe_to_edge_list(df):
"""
Convert dataframe into list of edges, assuming that source and target ids are stored in _SRC_VID_COLUMN, and _DST_VID_COLUMN respectively.
"""
cols = df.columns
if len(cols):
assert _SRC_VID_COLUMN in cols, "Vertex DataFrame must contain column %s" % _SRC... | Convert dataframe into list of edges, assuming that source and target ids are stored in _SRC_VID_COLUMN, and _DST_VID_COLUMN respectively. |
def _get_solarflux(self):
"""Derive the in-band solar flux from rsr over the Near IR band (3.7
or 3.9 microns)
"""
solar_spectrum = \
SolarIrradianceSpectrum(TOTAL_IRRADIANCE_SPECTRUM_2000ASTM,
dlambda=0.0005,
... | Derive the in-band solar flux from rsr over the Near IR band (3.7
or 3.9 microns) |
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('r... | Returns an instance of the redis client |
def bootstrap_results(self, init_state):
"""Returns an object with the same type as returned by `one_step`.
Args:
init_state: `Tensor` or Python `list` of `Tensor`s representing the
initial state(s) of the Markov chain(s).
Returns:
kernel_results: A (possibly nested) `tuple`, `namedtup... | Returns an object with the same type as returned by `one_step`.
Args:
init_state: `Tensor` or Python `list` of `Tensor`s representing the
initial state(s) of the Markov chain(s).
Returns:
kernel_results: A (possibly nested) `tuple`, `namedtuple` or `list` of
`Tensor`s representing ... |
def serialize(self):
'''Serialize this object as dictionary usable for conversion to JSON.
:return: Dictionary representing this object.
'''
return {
'type': 'event',
'id': self.uid,
'attributes': {
'start': self.start,
... | Serialize this object as dictionary usable for conversion to JSON.
:return: Dictionary representing this object. |
def isInside(self, point, tol=0.0001):
"""
Return True if point is inside a polydata closed surface.
"""
poly = self.polydata(True)
points = vtk.vtkPoints()
points.InsertNextPoint(point)
pointsPolydata = vtk.vtkPolyData()
pointsPolydata.SetPoints(points)
... | Return True if point is inside a polydata closed surface. |
def retrieve_list(self, session, filters, *args, **kwargs):
"""
Retrieves a list of the model for this manager.
It is restricted by the filters provided.
:param Session session: The SQLAlchemy session to use
:param dict filters: The filters to restrict the returned
m... | Retrieves a list of the model for this manager.
It is restricted by the filters provided.
:param Session session: The SQLAlchemy session to use
:param dict filters: The filters to restrict the returned
models on
:return: A tuple of the list of dictionary representation
... |
def import_image(self, imported_image_name, image_name):
"""
Import image using `oc import-image` command.
:param imported_image_name: str, short name of an image in internal registry, example:
- hello-openshift:latest
:param image_name: full repository name, example:
... | Import image using `oc import-image` command.
:param imported_image_name: str, short name of an image in internal registry, example:
- hello-openshift:latest
:param image_name: full repository name, example:
- docker.io/openshift/hello-openshift:latest
:return: str, short... |
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}" | Return the iso time string only |
def init_device(self):
"""Device constructor."""
Device.init_device(self)
# Add anything here that has to be done before the device is set to
# its ON state.
self._set_master_state('on')
self._devProxy = DeviceProxy(self.get_name()) | Device constructor. |
def is_attr_protected(attrname: str) -> bool:
"""return True if attribute name is protected (start with _ and some other
details), False otherwise.
"""
return (
attrname[0] == "_"
and attrname != "_"
and not (attrname.startswith("__") and attrname.endswith("__"))
) | return True if attribute name is protected (start with _ and some other
details), False otherwise. |
def union(self, other):
""" Intersect current range with other."""
return Interval(min(self.low, other.low), max(self.high, other.high)) | Intersect current range with other. |
def Close(self):
"""Disconnects from the database.
This method will create the necessary indices and commit outstanding
transactions before disconnecting.
"""
# Build up indices for the fields specified in the args.
# It will commit the inserts automatically before creating index.
if not se... | Disconnects from the database.
This method will create the necessary indices and commit outstanding
transactions before disconnecting. |
def register(id, url=None):
"""Register a UUID key in the global S3 bucket."""
bucket = registration_s3_bucket()
key = registration_key(id)
obj = bucket.Object(key)
obj.put(Body=url or "missing")
return _generate_s3_url(bucket, key) | Register a UUID key in the global S3 bucket. |
def set_thumbnail(self, thumbnail):
"""
Sets the thumbnail for this OAuth Client. If thumbnail is bytes,
uploads it as a png. Otherwise, assumes thumbnail is a path to the
thumbnail and reads it in as bytes before uploading.
"""
headers = {
"Authorization": ... | Sets the thumbnail for this OAuth Client. If thumbnail is bytes,
uploads it as a png. Otherwise, assumes thumbnail is a path to the
thumbnail and reads it in as bytes before uploading. |
def websocket_safe_read(self):
""" Returns data if available, otherwise ''. Newlines indicate multiple
messages
"""
data = []
while True:
try:
data.append(self.websocket.recv())
except (SSLError, SSLWantReadError) as err:
... | Returns data if available, otherwise ''. Newlines indicate multiple
messages |
async def _parse_lines(lines, regex):
"""Parse the lines using the given regular expression.
If a line can't be parsed it is logged and skipped in the output.
"""
results = []
if inspect.iscoroutinefunction(lines):
lines = await lines
for line in lines:
if line:
matc... | Parse the lines using the given regular expression.
If a line can't be parsed it is logged and skipped in the output. |
def attach_ip(self, server, family='IPv4'):
"""
Attach a new (random) IPAddress to the given server (object or UUID).
"""
body = {
'ip_address': {
'server': str(server),
'family': family
}
}
res = self.request('POST... | Attach a new (random) IPAddress to the given server (object or UUID). |
def answer_challenge(authzr, client, responders):
"""
Complete an authorization using a responder.
:param ~acme.messages.AuthorizationResource auth: The authorization to
complete.
:param .Client client: The ACME client.
:type responders: List[`~txacme.interfaces.IResponder`]
:param res... | Complete an authorization using a responder.
:param ~acme.messages.AuthorizationResource auth: The authorization to
complete.
:param .Client client: The ACME client.
:type responders: List[`~txacme.interfaces.IResponder`]
:param responders: A list of responders that can be used to complete the... |
def editHook(self, repo_user, repo_name, hook_id, name, config,
events=None, add_events=None, remove_events=None, active=None):
"""
PATCH /repos/:owner/:repo/hooks/:id
:param hook_id: Id of the hook.
:param name: The name of the service that is being called.
:param ... | PATCH /repos/:owner/:repo/hooks/:id
:param hook_id: Id of the hook.
:param name: The name of the service that is being called.
:param config: A Hash containing key/value pairs to provide settings
for this hook. |
def handle_trunks(self, trunks, event_type):
"""Trunk data model change from the server."""
LOG.debug("Trunks event received: %(event_type)s. Trunks: %(trunks)s",
{'event_type': event_type, 'trunks': trunks})
if event_type == events.DELETED:
# The port trunks have... | Trunk data model change from the server. |
def select_by_index(self, val, level=0, squeeze=False, filter=False, return_mask=False):
"""
Select or filter elements of the Series by index values (across levels, if multi-index).
The index is a property of a Series object that assigns a value to each position within
the arrays stored... | Select or filter elements of the Series by index values (across levels, if multi-index).
The index is a property of a Series object that assigns a value to each position within
the arrays stored in the records of the Series. This function returns a new Series where,
within each record, only the... |
def get_unused_color(self):
"""Returns an xlwt color index that has not been previously returned by
this instance. Attempts to maximize the distance between the color and
all previously used colors.
"""
if not self.unused_colors:
# If we somehow run out of colors, re... | Returns an xlwt color index that has not been previously returned by
this instance. Attempts to maximize the distance between the color and
all previously used colors. |
def resolve_group_names(self, r, target_group_ids, groups):
"""Resolve any security group names to the corresponding group ids
With the context of a given network attached resource.
"""
names = self.get_group_names(target_group_ids)
if not names:
return target_group_... | Resolve any security group names to the corresponding group ids
With the context of a given network attached resource. |
def fill(self, paths):
"""
Initialise the tree.
paths is a list of strings where each string is the relative path to some
file.
"""
for path in paths:
tree = self.tree
parts = tuple(path.split('/'))
dir_parts = parts[:-1]
b... | Initialise the tree.
paths is a list of strings where each string is the relative path to some
file. |
def installed(name,
features=None,
recurse=False,
restart=False,
source=None,
exclude=None):
'''
Install the windows feature. To install a single feature, use the ``name``
parameter. To install multiple features, use the ``features`` para... | Install the windows feature. To install a single feature, use the ``name``
parameter. To install multiple features, use the ``features`` parameter.
.. note::
Some features require reboot after un/installation. If so, until the
server is restarted other features can not be installed!
Args:
... |
def _results(self, scheduler_instance_id):
"""Get the results of the executed actions for the scheduler which instance id is provided
Calling this method for daemons that are not configured as passive do not make sense.
Indeed, this service should only be exposed on poller and reactionner daemo... | Get the results of the executed actions for the scheduler which instance id is provided
Calling this method for daemons that are not configured as passive do not make sense.
Indeed, this service should only be exposed on poller and reactionner daemons.
:param scheduler_instance_id: instance id... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.