text stringlengths 81 112k |
|---|
Raise an error from the remote API if necessary.
def _raise_for_remote_status(url: str, data: dict) -> None:
"""Raise an error from the remote API if necessary."""
if data.get('errorType') and data['errorType'] > 0:
raise_remote_error(data['errorType'])
if data.get('statusCode') and data['statusCo... |
Authenticate against a RainMachine device.
async def login(
host: str,
password: str,
websession: ClientSession,
*,
port: int = 8080,
ssl: bool = True,
request_timeout: int = DEFAULT_TIMEOUT) -> Controller:
"""Authenticate against a RainMachine device."""
... |
Create a local client.
async def load_local( # pylint: disable=too-many-arguments
self,
host: str,
password: str,
port: int = DEFAULT_LOCAL_PORT,
ssl: bool = True,
skip_existing: bool = True) -> None:
"""Create a local client."""
... |
Create a local client.
async def load_remote(
self, email: str, password: str,
skip_existing: bool = True) -> None:
"""Create a local client."""
auth_resp = await self._request(
'post',
'https://my.rainmachine.com/login/auth',
json={'user': {
... |
Make a request against the RainMachine device.
async def _request(
self,
method: str,
url: str,
*,
access_token: str = None,
access_token_expiration: datetime = None,
headers: dict = None,
params: dict = None,
j... |
Raise the appropriate error with a remote error code.
def raise_remote_error(error_code: int) -> None:
"""Raise the appropriate error with a remote error code."""
try:
error = next((v for k, v in ERROR_CODES.items() if k == error_code))
raise RequestError(error)
except StopIteration:
... |
Returns first and last day of a quarter
Args:
quarter (str) quarter, in format '2015Q1'
Returns: (tuple) datetime.dates for the first and last days of the quarter
def quarter_boundaries(quarter):
"""Returns first and last day of a quarter
Args:
quarter (str) quarter, in format '2015Q... |
Returns metta metadata for a quarter's SOC code classifier matrix
Args:
quarter (str) quarter, in format '2015Q1'
num_dimensions (int) Number of features in matrix
Returns: (dict) metadata suitable for metta.archive_train_test
def metta_config(quarter, num_dimensions):
"""Returns metta me... |
Store train and test matrices using metta
Args:
train_features_path (str) Path to matrix with train features
train_labels_path (str) Path to matrix with train labels
test_features_path (str) Path to matrix with test features
test_labels_path (str) Path to matrix with test labels
... |
Lock packages. Downloader search packages
def usedby_packages(self, deps_file_path=None, depslock_file_path=None, packages=None):
"""
Lock packages. Downloader search packages
"""
if deps_file_path is None:
deps_file_path = self._deps_path
if depslock_file_path is No... |
Uploads the given file to s3
Args:
s3_conn: (boto.s3.connection) an s3 connection
filepath (str) the local filename
s3_path (str) the destination path on s3
def upload(s3_conn, filepath, s3_path):
"""Uploads the given file to s3
Args:
s3_conn: (boto.s3.connection) an s3 co... |
Syncs a dictionary to an S3 bucket, serializing each value in the
dictionary as a JSON file with the key as its name.
Args:
s3_conn: (boto.s3.connection) an s3 connection
s3_prefix: (str) the destination prefix
data_to_sync: (dict)
def upload_dict(s3_conn, s3_prefix, data_to_sync):
... |
Downloads the given s3_path
Args:
s3_conn (boto.s3.connection) a boto s3 connection
out_filename (str) local filename to save the file
s3_path (str) the source path on s3
def download(s3_conn, out_filename, s3_path):
"""Downloads the given s3_path
Args:
s3_conn (boto.s3.co... |
Wrap the generic request method to add access token, etc.
async def _request(
self,
method: str,
endpoint: str,
*,
headers: dict = None,
params: dict = None,
json: dict = None,
ssl: bool = True) -> dict:
"""Wrap the... |
Authenticate against the device (locally).
async def login(self, password):
"""Authenticate against the device (locally)."""
auth_resp = await self._client_request(
'post',
'{0}/auth/login'.format(self._host),
json={
'pwd': password,
'... |
Authenticate against the device (remotely).
async def login(
self, stage_1_access_token: str, sprinkler_id: str,
password: str) -> None:
"""Authenticate against the device (remotely)."""
auth_resp = await self._client_request(
'post',
'https://my.rainmach... |
For all package set flag duplicated, if it's not unique package
:return:
def set_duplicated_flag(self):
"""
For all package set flag duplicated, if it's not unique package
:return:
"""
package_by_name = defaultdict(list)
for package1 in self._root_package.all_pa... |
Return python object from string
:param object_path: e.g os.path.join
:return: python object
def get_object_from_string(object_path):
"""
Return python object from string
:param object_path: e.g os.path.join
:return: python object
"""
# split like crosspm.template.GUS => crosspm.templat... |
Post data to a (non)existing zone.
async def _post(self, zone_id: int = None, json: dict = None) -> dict:
"""Post data to a (non)existing zone."""
return await self._request(
'post', 'zone/{0}/properties'.format(zone_id), json=json) |
Return all zones (with optional advanced properties).
async def all(
self, *, details: bool = False,
include_inactive: bool = False) -> list:
"""Return all zones (with optional advanced properties)."""
endpoint = 'zone'
if details:
endpoint += '/properties'
... |
Return a specific zone.
async def get(self, zone_id: int, *, details: bool = False) -> dict:
"""Return a specific zone."""
endpoint = 'zone/{0}'.format(zone_id)
if details:
endpoint += '/properties'
return await self._request('get', endpoint) |
Start a program.
async def start(self, zone_id: int, time: int) -> dict:
"""Start a program."""
return await self._request(
'post', 'zone/{0}/start'.format(zone_id), json={'time': time}) |
I turn a method into something that can be observed by other callables.
You can use me as a decorator on a method, like this:
class Foo(object):
__init__(self, name):
self.name = name
@observable_method
def bar(self, x):
print("%s called bar wit... |
Register an observer to observe me.
Args:
observer: The callable to register as an observer.
identify_observed: If True, then the observer will get myself
passed as an additional first argument whenever it is invoked.
See ObserverFunction and ObserverBoun... |
Add a function as an observer.
Args:
func: The function to register as an observer.
identify_observed: See docstring for add_observer.
Returns:
True if the function is added, otherwise False.
def _add_function(self, func, identify_observed):
"""Add a functi... |
Add an bound method as an observer.
Args:
bound_method: The bound method to add as an observer.
identify_observed: See the docstring for add_observer.
Returns:
True if the bound method is added, otherwise False.
def _add_bound_method(self, bound_method, identify_ob... |
Un-register an observer.
Args:
observer: The observer to un-register.
Returns true if an observer was removed, otherwise False.
def discard_observer(self, observer):
"""Un-register an observer.
Args:
observer: The observer to un-register.
Returns true... |
Construct a unique, hashable, immutable key for an observer.
def make_key(observer):
"""Construct a unique, hashable, immutable key for an observer."""
if hasattr(observer, "__self__"):
inst = observer.__self__
method_name = observer.__name__
key = (id(inst), method... |
Recursively fill in a command tree in cmd_params according to a docopt-parsed "pattern" object.
def build_command_tree(pattern, cmd_params):
"""
Recursively fill in a command tree in cmd_params according to a docopt-parsed "pattern" object.
"""
from docopt import Either, Optional, OneOrMore, Required, ... |
Yield a group from the iterable
def group(self):
"""Yield a group from the iterable"""
yield self.current
# start enumerate at 1 because we already yielded the last saved item
for num, item in enumerate(self.iterator, 1):
self.current = item
if num == self.limit:... |
Lock packages. Downloader search packages
def lock_packages(self, deps_file_path=None, depslock_file_path=None, packages=None):
"""
Lock packages. Downloader search packages
"""
if deps_file_path is None:
deps_file_path = self._deps_path
if depslock_file_path is None... |
Флаг --stdout может быть взят из переменной окружения CROSSPM_STDOUT.
Если есть любое значение в CROSSPM_STDOUT - оно понимается как True
:return:
def stdout(self):
"""
Флаг --stdout может быть взят из переменной окружения CROSSPM_STDOUT.
Если есть любое значение в CROSSPM_STDOU... |
Prepare args - add support for old interface, e.g:
- --recursive was "flag" and for now it support True or False value
:param args:
:return:
def prepare_args(args, windows=None):
"""
Prepare args - add support for old interface, e.g:
- --recursive was "flag" and ... |
Get watering information for X days from Y date.
async def log(
self,
date: datetime.date = None,
days: int = None,
details: bool = False) -> list:
"""Get watering information for X days from Y date."""
endpoint = 'watering/log'
if details:
... |
Return all program runs for X days from Y date.
async def runs(self, date: datetime.date = None, days: int = None) -> list:
"""Return all program runs for X days from Y date."""
endpoint = 'watering/past'
if date and days:
endpoint = '{0}/{1}/{2}'.format(
endpoint, ... |
Looking for auth in env, cmdline, str
:param list_or_file_path:
:param source:
def search_auth(self, list_or_file_path, source):
"""
Looking for auth in env, cmdline, str
:param list_or_file_path:
:param source:
"""
_auth = source.args['auth']
if ... |
Post data to a (non)existing program.
async def _post(self, program_id: int = None, json: dict = None) -> dict:
"""Post data to a (non)existing program."""
return await self._request(
'post', 'program/{0}'.format(program_id), json=json) |
Return all programs.
async def all(self, include_inactive: bool = False) -> list:
"""Return all programs."""
data = await self._request('get', 'program')
return [p for p in data['programs'] if include_inactive or p['active']] |
Caches the JSON-serializable output of the function to a given file
Args:
filename (str) The filename (sans directory) to store the output
Returns: decorator, applicable to a function that produces JSON-serializable output
def cache_json(filename):
"""Caches the JSON-serializable output of the fu... |
Check if the folder exisits. If not, create the folder
def check_create_folder(filename):
"""Check if the folder exisits. If not, create the folder"""
os.makedirs(os.path.dirname(filename), exist_ok=True) |
From the given request, redirect onto the checkout view, hosted by PayPal.
def get_payment_request(self, cart, request):
"""
From the given request, redirect onto the checkout view, hosted by PayPal.
"""
shop_ns = resolve(request.path).namespace
return_url = reverse('{}:{}:retur... |
Yield job postings in common schema format
Args:
quarter (str) The quarter, in format '2015Q1'
stats_counter (object, optional) A counter that can track both
input and output documents using a 'track' method.
def postings(self, quarter, stats_counter=None):
"""Y... |
Map search terms to what test case(s) they're related to
Returns:
dict: maps search terms to what test case(s) it's relevant to
Example:
{
'12034': ['ui.tests.TestSomething.test_hello_world'],
'buggy': ['ui.tests.TestSomething.test_hello_world', 'ui.tests.Te... |
After everything is done, generate the report
def afterSummaryReport(self, event):
"""
After everything is done, generate the report
"""
logger.info('Generating HTML report...')
sorted_test_results = self._sort_test_results()
context = {
'test_report_title'... |
Convert a quarter in arbitrary filename-ready format (e.g. 2015Q1)
into start and end datetimes
def quarter_to_daterange(quarter):
"""Convert a quarter in arbitrary filename-ready format (e.g. 2015Q1)
into start and end datetimes"""
assert len(quarter) == 6
year = int(quarter[0:4])
quarter = qu... |
Args:
dt: a datetime
Returns:
tuple of the datetime's year and quarter
def datetime_to_year_quarter(dt):
"""
Args:
dt: a datetime
Returns:
tuple of the datetime's year and quarter
"""
year = dt.year
quarter = int(math.ceil(float(dt.month)/3))
return (year... |
Returns all dates between two dates.
Inclusive of the start date but not the end date.
Args:
start_date (datetime.date)
end_date (datetime.date)
Returns:
(list) of datetime.date objects
def dates_in_range(start_date, end_date):
"""Returns all dates between two dates.
Inc... |
Load the exposed hooks.
Returns a dict of hooks where the keys are the name of the hook and the
values are the actual hook functions.
def load_hooks():
"""
Load the exposed hooks.
Returns a dict of hooks where the keys are the name of the hook and the
values are the actual hook functions.
... |
Let you use gettext instead of the Qt tools for l18n
def gettext(ui_file_path):
"""
Let you use gettext instead of the Qt tools for l18n
"""
with open(ui_file_path, 'r') as fin:
content = fin.read()
# replace ``_translate("context", `` by ``_(``
content = re.sub(r'_translate\(".*",\s',... |
Stream a JSON file (in JSON-per-line format)
Args:
local_file (file-like object) an open file-handle that contains a
JSON string on each line
Yields:
(dict) JSON objects
def stream_json_file(local_file):
"""Stream a JSON file (in JSON-per-line format)
Args:
local_f... |
Download file containing this package.
:param force: Force download even if it seems file already exists
:return: Full path with filename of downloaded package file.
def download(self, force=False):
"""
Download file containing this package.
:param force: Force download even if ... |
Find all dependencies by package
:param depslock_file_path:
:param property_validate: for `root` packages we need check property, bad if we find packages from `lock` file,
:param deps_content: HACK for use --dependencies-content and existed dependencies.txt.lock file
we can skip validate... |
Find all dependencies by package
:param depslock_file_path:
:param property_validate: for `root` packages we need check property, bad if we find packages from `lock` file,
we can skip validate part
:return:
def find_usedby(self, depslock_file_path, property_validate=True):
"""
... |
Get Package params
:param param_list: name or list of parameters
:param get_path:
:param merged: if version splited, True return version in string
:param raw:
:return:
def get_params(self, param_list=None, get_path=False, merged=False, raw=False):
"""
Get Package... |
Get packages with None (not founded), recursively
def get_none_packages(self):
"""
Get packages with None (not founded), recursively
"""
not_found = set()
for package_name, package in self.packages.items():
if package is None:
not_found.add(package_na... |
Возвращает запрос AQL (без репозитория), из файла конфигурации
:param params:
:return:
def get_usedby_aql(self, params):
"""
Возвращает запрос AQL (без репозитория), из файла конфигурации
:param params:
:return:
"""
if self._usedby is None:
re... |
Get params with extra, like 'any'
:param rule_name: 'path'
:param params: default params
:return: list of combination params
def get_params_with_extra(self, rule_name, params):
"""
Get params with extra, like 'any'
:param rule_name: 'path'
:param params: default ... |
Split path into fixed and masked parts
:param path: e.g
https://repo.example.com/artifactory/libs-cpp-release.snapshot/boost/1.60-pm/*.*.*/vc110/x86/win/boost.*.*.*.tar.gz
:return:
_path_fixed: https://repo.example.com/artifactory/libs-cpp-release.snapshot/boost/1.60-pm/
... |
Split path into fixed, masked parts and filename
:param path: e.g
https://repo.example.com/artifactory/libs-cpp-release.snapshot/boost/1.60-pm/*.*.*/vc110/x86/win/boost.*.*.*.tar.gz
:return:
_path_fixed: https://repo.example.com/artifactory/libs-cpp-release.snapshot/boost/1.60-pm/
... |
Returns an Elasticsearch basic client that is responsive
to the environment variable ELASTICSEARCH_ENDPOINT
def basic_client():
"""Returns an Elasticsearch basic client that is responsive
to the environment variable ELASTICSEARCH_ENDPOINT"""
es_connected = False
while not es_connected:
try:... |
Creates an index with a given configuration
Args:
index_name (str): Name of the index you want to create
index_config (dict) configuration for the index
client (Elasticsearch.IndicesClient) the Elasticsearch client
def create_index(index_name, index_config, client):
"""Creates an index... |
Retrieve the base index name from an alias
Args:
alias_name (str) Name of the alias
index_client (Elasticsearch.IndicesClient) an Elasticsearch index
client. Optional, will create one if not given
Returns: (str) Name of index
def get_index_from_alias(alias_name, index_client=None)... |
Points an alias to a new index, then delete the old index if needed
Uses client.update_aliases to perform this with zero downtime
Args:
alias_name (str) Name of the alias
new_index_name (str) The new index that the alias should point to
index_client (Elasticsearch.IndicesClient) Elasti... |
Context manager to create a new index based on a given alias,
allow the caller to index it, and then point the alias to the new index
Args:
index_name (str) Name of an alias that should point to the new index
index_config (dict) Configuration for the new index
Yields: (name) The full name ... |
Replace index with a new one
zero_downtime_index for safety and rollback
def replace(self):
"""Replace index with a new one
zero_downtime_index for safety and rollback
"""
with zero_downtime_index(self.alias_name, self.index_config()) as target_index:
self.index_all(... |
Index documents onto an existing index
def append(self):
"""Index documents onto an existing index"""
target_index = get_index_from_alias(self.alias_name)
if not target_index:
self.replace()
else:
self.index_all(target_index) |
Index all available documents, using streaming_bulk for speed
Args:
index_name (string): The index
def index_all(self, index_name):
"""Index all available documents, using streaming_bulk for speed
Args:
index_name (string): The index
"""
oks = 0
notoks ... |
Build arguments list for passing to subprocess.call_check
:param cmd str: Command string to interpolate src and dst filepaths into.
Typically the output of `config.Config.uic_command` or `config.Config.rcc_command`.
:param src str: Source filepath.
:param dst str: Destination filepa... |
Load output format function to dictionary (decorator with this function name)
def register_output_format(name):
"""
Load output format function to dictionary (decorator with this function name)
"""
def check_decorator(fn):
_output_format_map[name] = fn
def wrapper(*args, **kwargs):
... |
Функция вызывает определенную функцию для фиксированного out-format
:param params:
:param packages:
:return:
def write_output(self, params, packages):
"""
Функция вызывает определенную функцию для фиксированного out-format
:param params:
:param packages:
... |
Text to lock file
def output_format_lock(self, packages, **kwargs):
""" Text to lock file """
self._output_config['type'] = PLAIN
text = ''
tmp_packages = OrderedDict()
columns = self._config.get_columns()
widths = {}
for _pkg in packages.values():
_p... |
Create out with child first position
def output_format_module(self, packages, esc_path=False):
"""
Create out with child first position
"""
def create_ordered_list(packages_):
"""
Recursive for package.packages
"""
list_ = []
... |
Simple decorator to get custom fields on admin class, using this you will use less line codes
:param short_description: description of custom field
:type str:
:param admin_order_field: field to order on click
:type str:
:param allow_tags: allow html tags
:type bool:
:param boolean: if fi... |
If the value is a float, create a numpy array of the required length, filled with value
If the value is a numpy array, check its length
Otherwise throw a type error
def create_buffer(params, value):
'''
If the value is a float, create a numpy array of the required length, filled with value
If the v... |
Update the length of the buffer in seconds
:param time: number of seconds
:return: self
def set_time(self, time):
'''
Update the length of the buffer in seconds
:param time: number of seconds
:return: self
'''
self.length = int(time*self.sample_rate)
... |
Make a request to another service. If `context` is provided, then
context and correlation will be pulled from the provided request
object for you. This includes credentials, correlationid,
and service-headers.
:param method: GET/PUT/PATCH, etc.
:param service: name of service
... |
Make a get request (this returns a coroutine)
def get(self, service, path, **kwargs):
""" Make a get request (this returns a coroutine)"""
return self.make_request(Methods.GET, service, path, **kwargs) |
Make a put request (this returns a coroutine)
def put(self, service, path, body, **kwargs):
""" Make a put request (this returns a coroutine)"""
return self.make_request(Methods.POST, service, path, body=body,
**kwargs) |
Make a patche requests (this returns a coroutine)
def patch(self, service, path, body, **kwargs):
""" Make a patche requests (this returns a coroutine)"""
return self.make_request(Methods.PATCH, service, path, body=body,
**kwargs) |
Make a delete requests (this returns a coroutine)
def delete(self, service, path, **kwargs):
""" Make a delete requests (this returns a coroutine)"""
return self.make_request(Methods.DELETE, service, path, **kwargs) |
Fetch Resource and return Entity
def process_request(self, request_object):
"""Fetch Resource and return Entity"""
identifier = request_object.identifier
# Look for the object by its ID and return it
resource = request_object.entity_cls.get(identifier)
return ResponseSuccess(S... |
Initialize a ListRequestObject object from a dictionary.
def from_dict(cls, entity_cls, adict):
"""Initialize a ListRequestObject object from a dictionary."""
invalid_req = InvalidRequestObject()
# Extract the pagination parameters from the input
page = int(adict.pop('page', 1))
... |
Return a list of resources
def process_request(self, request_object):
"""Return a list of resources"""
resources = (request_object.entity_cls.query
.filter(**request_object.filters)
.offset((request_object.page - 1) * request_object.per_page)
... |
Process Create Resource Request
def process_request(self, request_object):
"""Process Create Resource Request"""
resource = request_object.entity_cls.create(**request_object.data)
return ResponseSuccessCreated(resource) |
Process Update Resource Request
def process_request(self, request_object):
"""Process Update Resource Request"""
# Retrieve the object by its identifier
entity = request_object.entity_cls.get(request_object.identifier)
# Update the object and return the updated data
resource =... |
Process the Delete Resource Request
def process_request(self, request_object):
"""Process the Delete Resource Request"""
# Delete the object by its identifier
entity = request_object.entity_cls.get(request_object.identifier)
entity.delete()
# FIXME Check for return value of `d... |
Convert the value to its string representation
def _cast_to_type(self, value):
""" Convert the value to its string representation"""
if isinstance(value, str) or value is None:
return value
return str(value) |
Convert the value to an int and raise error on failures
def _cast_to_type(self, value):
""" Convert the value to an int and raise error on failures"""
try:
return int(value)
except (ValueError, TypeError):
self.fail('invalid', value=value) |
Convert the value to a float and raise error on failures
def _cast_to_type(self, value):
""" Convert the value to a float and raise error on failures"""
try:
return float(value)
except (ValueError, TypeError):
self.fail('invalid', value=value) |
Convert the value to a boolean and raise error on failures
def _cast_to_type(self, value):
""" Convert the value to a boolean and raise error on failures"""
if value in (True, False):
return bool(value)
if value in ('t', 'True', '1'):
return True
if value in ('f'... |
Raise error if the value is not a list
def _cast_to_type(self, value):
""" Raise error if the value is not a list """
if not isinstance(value, list):
self.fail('invalid', value=value)
return value |
Raise error if the value is not a dict
def _cast_to_type(self, value):
""" Raise error if the value is not a dict """
if not isinstance(value, dict):
self.fail('invalid', value=value)
return value |
Convert the value to a date and raise error on failures
def _cast_to_type(self, value):
""" Convert the value to a date and raise error on failures"""
if isinstance(value, datetime.datetime):
return value.date()
if isinstance(value, datetime.date):
return value
t... |
Convert the value to a datetime and raise error on failures
def _cast_to_type(self, value):
""" Convert the value to a datetime and raise error on failures"""
if isinstance(value, datetime.datetime):
return value
if isinstance(value, datetime.date):
value = datetime.date... |
Method for actually making a request
:param service: service to make request too
:param method: HTTP method: GET/PUT/POST etc.
:param path: routing path.
Should support dots `foo.2.bars` or slashes `foo/2/bars`
:param body: request body. Bytes-like object
:param query... |
Generic executor method of all UseCases
def execute(self, request_object):
"""Generic executor method of all UseCases"""
# If the request object is not valid then return a failure response
if not request_object.is_valid:
return ResponseFailure.build_from_invalid_request(
... |
To check execution time of a function
borrowed from https://medium.com/pythonhive/python-decorator-to-measure-the-execution-time-of-methods-fa04cb6bb36d
>>> def logger(details, args, kwargs): #some function that uses the time output
... print(details)
...
>>> @FunctionTimer(on_done= logger)
... |
Override this method to change how a exchange is declared
async def exchange_declare(self):
""" Override this method to change how a exchange is declared """
await self.channel.exchange_declare(
self.exchange,
self.exchange_type,
durable=self.durable,
aut... |
Override this method to change how a queue is declared
async def queue_declare(self):
""" Override this method to change how a queue is declared """
await self.channel.queue_declare(
self.queue,
durable=self.durable,
exclusive=self.exclusive,
... |
Convert the entity to a dictionary record
def from_entity(cls, entity: Entity) -> 'DictModel':
"""Convert the entity to a dictionary record """
dict_obj = {}
for field_name in entity.meta_.attributes:
dict_obj[field_name] = getattr(entity, field_name)
return dict_obj |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.