code
stringlengths
1
18.2k
def set_interface_down(ifindex, auth, url, devid=None, devip=None): """ function takest devid and ifindex of specific device and interface and issues a RESTFUL call to " shut" the specified interface on the target device. :param devid: int or str value of the target device :param devip: ipv4 address of the target devic...
object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: HTTP status code 204 with no values. :rtype:int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "...
204 >>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221') >>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devip = '10.101.0.221') 204 >>> assert type(int_down_response) is int >>> assert int_down_response is 204 >>> int_up_response = set_inteface_up('9', auth.cr...
= url + set_int_down_url try: response = requests.put(f_url, auth=auth, headers=HEADERS) print(response.status_code) if response.status_code == 204: return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " set_inteface_down: An Error has occured"
def set_inteface_up(ifindex, auth, url, devid=None, devip=None): """ function takest devid and ifindex of specific device and interface and issues a RESTFUL call to "undo shut" the specified interface on the target device. :param devid: int or str value of the target device :param devip: ipv4 address of the target devi...
object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: HTTP status code 204 with no values. :rype: int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "...
devid = '10') >>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devid = '10') 204 >>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221') >>> assert type(int_up_response) is int >>> assert int_up_response is 204 """ if devip is not None: devid = get_dev_details(devi...
auth=auth, headers=HEADERS) if response.status_code == 204: return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " set_inteface_up: An Error has occured"
def _make_cmd_list(cmd_list): """ Helper function to easily create the proper json formated string from a list of strs :param cmd_list: list of strings :return: str json formatted """ cmd = '' for i in cmd_list: cmd = cmd + '"' + i + '",' cmd = cmd[:-1] return cmd
async def create(cls, user_id: Union[int, str], is_active: bool = True, is_admin: bool = False, resource_policy: str = None, rate_limit: int = None, fields: Iterable[str] = None) -> dict: ''' Creates a new keypair with the given options. You need an admin privilege for this operation. ''' if fields is None: fields = ('...
'mutation($user_id: {0}, $input: KeyPairInput!) {{'.format(uid_type) + \ ' create_keypair(user_id: $user_id, props: $input) {' \ ' ok msg keypair { $fields }' \ ' }' \ '}' q = q.replace('$fields', ' '.join(fields)) variables = { 'user_id': user_id, 'input': { 'is_active': is_active, 'is_admin': is_admin, 'resource_poli...
data = await resp.json() return data['create_keypair']
async def update(cls, access_key: str, is_active: bool = None, is_admin: bool = None, resource_policy: str = None, rate_limit: int = None) -> dict: """ Creates a new keypair with the given options. You need an admin privilege for this operation. """ q = 'mutation($access_key: String!, $input: ModifyKeyPairInput!) {' + ...
'}' variables = { 'access_key': access_key, 'input': { 'is_active': is_active, 'is_admin': is_admin, 'resource_policy': resource_policy, 'rate_limit': rate_limit, }, } rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.set_json({ 'query': q, 'variables': variables, }) async with rqst.fetch() as resp: data = awa...
async def delete(cls, access_key: str): """ Deletes an existing keypair with given ACCESSKEY. """ q = 'mutation($access_key: String!) {' \ ' delete_keypair(access_key: $access_key) {' \ ' ok msg' \ ' }' \ '}' variables = { 'access_key': access_key, } rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.set_json({...
async def list(cls, user_id: Union[int, str] = None, is_active: bool = None, fields: Iterable[str] = None) -> Sequence[dict]: ''' Lists the keypairs. You need an admin privilege for this operation. ''' if fields is None: fields = ( 'access_key', 'secret_key', 'is_active', 'is_admin', ) if user_id is None: q = 'query($i...
'}' else: uid_type = 'Int!' if isinstance(user_id, int) else 'String!' q = 'query($user_id: {0}, $is_active: Boolean) {{'.format(uid_type) + \ ' keypairs(user_id: $user_id, is_active: $is_active) {' \ ' $fields' \ ' }' \ '}' q = q.replace('$fields', ' '.join(fields)) variables = { 'is_active': is_active, } if user_id i...
with rqst.fetch() as resp: data = await resp.json() return data['keypairs']
async def info(self, fields: Iterable[str] = None) -> dict: ''' Returns the keypair's information such as resource limits. :param fields: Additional per-agent query fields to fetch. .. versionadded:: 18.12 ''' if fields is None: fields = ( 'access_key', 'secret_key', 'is_active', 'is_admin', ) q = 'query {' \ ' keypair...
= Request(self.session, 'POST', '/admin/graphql') rqst.set_json({ 'query': q, }) async with rqst.fetch() as resp: data = await resp.json() return data['keypair']
async def activate(cls, access_key: str) -> dict: ''' Activates this keypair. You need an admin privilege for this operation. ''' q = 'mutation($access_key: String!, $input: ModifyKeyPairInput!) {' + \ ' modify_keypair(access_key: $access_key, props: $input) {' \ ' ok msg' \ ' }' \ '}' variables = { 'access_key': acces...
'POST', '/admin/graphql') rqst.set_json({ 'query': q, 'variables': variables, }) async with rqst.fetch() as resp: data = await resp.json() return data['modify_keypair']
async def deactivate(cls, access_key: str) -> dict: ''' Deactivates this keypair. Deactivated keypairs cannot make any API requests unless activated again by an administrator. You need an admin privilege for this operation. ''' q = 'mutation($access_key: String!, $input: ModifyKeyPairInput!) {' + \ ' modify_keypair(acc...
'is_active': False, 'is_admin': None, 'resource_policy': None, 'rate_limit': None, }, } rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.set_json({ 'query': q, 'variables': variables, }) async with rqst.fetch() as resp: data = await resp.json() return data['modify_keypair']
def add_ip_scope(auth, url,startIp, endIp, name, description): """ Function takes input of four strings Start Ip, endIp, name, and description to add new Ip Scope to terminal access in the HPE IMC base platform :param startIp: str Start of IP address scope ex. '10.101.0.1' :param endIp: str End of IP address scope ex. ...
ex. 'admin' :param description: str description of the Ip scope :return: """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() add_ip_scope_url = "/imcrs/res/access/assignedIpScope" f_url = url + add_ip_scope_url payload = ('''{ "startIp": "%s", "endIp": "%s","...
using the payload variable as the contents try: if r.status_code == 200: print("IP Scope Successfully Created") return r.status_code elif r.status_code == 409: print ("IP Scope Already Exists") return r.status_code except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " add_ip_scope: An Error h...
async def check_presets(cls): ''' Lists all resource presets in the current scaling group with additiona information. ''' rqst = Request(cls.session, 'POST', '/resource/check-presets') async with rqst.fetch() as resp: return await resp.json()
def add_perf_task(task, auth, url): """ function takes the a python dict containing all necessary fields for a performance tasks, transforms the dict into JSON and issues a RESTFUL call to create the performance task. device. :param task: dictionary containing all required fields for performance tasks :param auth: requ...
auth.url from pyhpeimc.auth.authclass :return: 204 :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.perf import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> new_task = {'indexDesc': '1.3.6.1.4.1.9.9.13.1.3.1.3','indexType': '[index1[0]:ciscoEnvMonTemperatureStatusValue...
r = requests.post(f_url, data = payload, auth=auth, headers=headers) try: return r.status_code except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_dev_alarms: An Error has occured'
def get_perf_task(task_name, auth, url): """ function takes the a str object containing the name of an existing performance tasks and issues a RESTFUL call to the IMC REST service. It will return a list :param task_name: str containing the name of the performance task :param auth: requests auth object #usually auth.cre...
from pyhpeimc.auth.authclass :return: 204 :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.perf import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> selected_task = get_perf_task('Cisco_Temperature', auth.creds, auth.url) >>> assert type(selected_task) is dict >>> asse...
headers=headers) try: if r.status_code == 200: perf_task_info = (json.loads(r.text))['task'] return perf_task_info except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_dev_alarms: An Error has occured'
def get_vm_host_info(hostip, auth, url): """ function takes hostId as input to RESTFUL call to HP IMC :param hostip: int or string of hostip of Hypervisor host :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.aut...
* >>> from pyhpeimc.plat.vrm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> host_info = get_vm_host_info('10.101.0.6', auth.creds, auth.url) >>> assert type(host_info) is dict >>> assert len(host_info) == 10 >>> assert 'cpuFeg' in host_info >>> assert 'cpuNum' in host_info >>> asse...
host_info >>> assert 'porductFlag' in host_info >>> assert 'serverName' in host_info >>> assert 'vendor' in host_info """ hostId = get_dev_details(hostip, auth, url)['id'] get_vm_host_info_url = "/imcrs/vrm/host?hostId=" + str(hostId) f_url = url + get_vm_host_info_url payload = None r = requests.get(f_url, auth=auth, ...
elif r.status_code == 204: print("Device is not a supported Hypervisor") return "Device is not a supported Hypervisor" except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " get_vm_host_info: An Error has occured"
def get_ac_info_all(auth, url): """ function takes no input as input to RESTFUL call to HP IMC :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionaries where each element of t...
list >>> from pyhpeimc.auth import * >>> from pyhpeimc.wsm.acinfo import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> ac_info_all = get_ac_info_all(auth.creds, auth.url) """ f_url = url + "/imcrs/wlan/acInfo/queryAcBasicInfo" response = requests.get(f_url, auth=auth, headers=HEADERS) tr...
+ " get_ac_info_all: An Error has occured"
def set_imc_creds(h_url=None, imc_server=None, imc_port=None, imc_user=None,imc_pw=None): """ This function prompts user for IMC server information and credentuials and stores values in url and auth global variables""" global auth, url if h_url is None: imc_protocol = input( "What protocol would you like to use to conn...
'http://' else: h_url = 'https://' imc_server = input("What is the ip address of the IMC server?") imc_port = input("What is the port number of the IMC server?") imc_user = input("What is the username of the IMC eAPI user?") imc_pw = input('''What is the password of the IMC eAPI user?''') url = h_url + imc_server + ":"...
'/imcrs' f_url = url + test_url try: r = requests.get(f_url, auth=auth, headers=headers, verify=False) print (r.status_code) return auth # checks for reqeusts exceptions except requests.exceptions.RequestException as e: print("Error:\n" + str(e)) print("\n\nThe IMC server address is invalid. Please try again\n\n") set_...
IMC eAPI")
def print_to_file(object): """ Function takes in object of type str, list, or dict and prints out to current working directory as pyoutput.txt :param: Object: object of type str, list, or dict :return: No return. Just prints out to file handler and save to current working directory as pyoutput.txt """ with open ('pyout...
json.dumps(object, indent = 4) if type(object) is dict: x = json.dumps(object, indent = 4) if type (object) is str: x = object fh.write(x)
def get_auth(self): """ This method requests an authentication object from the HPE IMC NMS and returns an HTTPDigest Auth Object :return: """ url = self.h_url + self.server + ":" + self.port auth = requests.auth.HTTPDigestAuth(self.username,self.password) auth_url = "/imcrs" f_url = url + auth_url try: r = requests.get...
+ '\n\nThe IMC server address is invalid. Please try again') set_imc_creds() if r.status_code != 200: # checks for valid IMC credentials return ("Error:\n" + str(e) +"Error: \n You're credentials are invalid. Please try again\n\n") set_imc_creds()
def get_version(root): """ Load and return the contents of version.json. :param root: The root path that the ``version.json`` file will be opened :type root: str :returns: Content of ``version.json`` or None :rtype: dict or None """ version_json = os.path.join(root, 'version.json') if os.path.exists(version_json): with...
def fetch(self, endpoint_name, identifier_input, query_params=None): """Calls this instance's request_client's post method with the specified component endpoint Args: - endpoint_name (str) - The endpoint to call like "property/value". - identifier_input - One or more identifiers to request data for. An identifier can b...
(address, zipcode, unit, city, state, slug, meta). One of 'address' or 'slug' is required. Ex: [{"address": "82 County Line Rd", "zipcode": "72173", "meta": "some ID"}] A slug is a URL-safe string that identifies a property. These are obtained from HouseCanary. Ex: [{"slug": "123-Example-St-San-Francisco-CA-94105"}] - ...
meta). 'block_id' is required. Ex: [{"block_id": "060750615003005", "meta": "some ID"}] - A list of dicts representing a zipcode: Ex: [{"zipcode": "90274", "meta": "some ID"}] - A list of dicts representing an MSA: Ex: [{"msa": "41860", "meta": "some ID"}] The "meta" field is always optional. Returns: A Response object...
= constants.URL_PREFIX + "/" + self._version + "/" + endpoint_name if query_params is None: query_params = {} if len(identifier_input) == 1: # If only one identifier specified, use a GET request query_params.update(identifier_input[0]) return self._request_client.get(endpoint_url, query_params) # when more than one add...
def fetch_synchronous(self, endpoint_name, query_params=None): """Calls this instance's request_client's get method with the specified component endpoint""" endpoint_url = constants.URL_PREFIX + "/" + self._version + "/" + endpoint_name if query_params is None: query_params = {} return self._request_client.get(endpoint...
def get_identifier_input(self, identifier_data): """Convert the various formats of input identifier_data into the proper json format expected by the ApiClient fetch method, which is a list of dicts.""" identifier_input = [] if isinstance(identifier_data, list) and len(identifier_data) > 0: # if list, convert each item ...
def fetch_identifier_component(self, endpoint_name, identifier_data, query_params=None): """Common method for handling parameters before passing to api_client""" if query_params is None: query_params = {} identifier_input = self.get_identifier_input(identifier_data) return self._api_client.fetch(endpoint_name, identifi...
def _convert_to_identifier_json(self, address_data): """Convert input address data into json format""" if isinstance(address_data, str): # allow just passing a slug string. return {"slug": address_data} if isinstance(address_data, tuple) and len(address_data) > 0: address_json = {"address": address_data[0]} if len(addr...
# ensure the dict does not contain any unallowed keys for key in address_data: if key not in allowed_keys: msg = "Key in address input not allowed: " + key raise housecanary.exceptions.InvalidInputException(msg) # ensure it contains an "address" key if "address" in address_data or "slug" in address_data: return address...
invalid. Must be a list of (address, zipcode) tuples, or a dict or list" " of dicts with each item containing at least an 'address' or 'slug' key.") raise housecanary.exceptions.InvalidInputException((msg))
def value_report(self, address, zipcode, report_type="full", format_type="json"): """Call the value_report component Value Report only supports a single address. Args: - address - zipcode Kwargs: - report_type - "full" or "summary". Default is "full". - format_type - "json", "pdf", "xlsx" or "all". Default is "json". "...
def rental_report(self, address, zipcode, format_type="json"): """Call the rental_report component Rental Report only supports a single address. Args: - address - zipcode Kwargs: - format_type - "json", "xlsx" or "all". Default is "json". """ # only json is supported by rental report. query_params = { "format": format_...
def component_mget(self, zip_data, components): """Call the zip component_mget endpoint Args: - zip_data - As described in the class docstring. - components - A list of strings for each component to include in the request. Example: ["zip/details", "zip/volatility"] """ if not isinstance(components, list): print("Compon...
def version(request): """ Returns the contents of version.json or a 404. """ version_json = import_string(version_callback)(settings.BASE_DIR) if version_json is None: return HttpResponseNotFound('version.json not found') else: return JsonResponse(version_json)
def heartbeat(request): """ Runs all the Django checks and returns a JsonResponse with either a status code of 200 or 500 depending on the results of the checks. Any check that returns a warning or worse (error, critical) will return a 500 response. """ all_checks = checks.registry.registry.get_checks( include_deployme...
= heartbeat_check_detail(check) statuses[check.__name__] = detail['status'] level = max(level, detail['level']) if detail['level'] > 0: details[check.__name__] = detail if level < checks.messages.WARNING: status_code = 200 heartbeat_passed.send(sender=heartbeat, level=level) else: status_code = 500 heartbeat_failed.sen...
def _create_component_results(json_data, result_key): """ Returns a list of ComponentResult from the json_data""" component_results = [] for key, value in list(json_data.items()): if key not in [result_key, "meta"]: component_result = ComponentResult( key, value["result"], value["api_code"], value["api_code_description...
def has_error(self): """Returns whether there was a business logic error when fetching data for any components for this property. Returns: boolean """ return next( (True for cr in self.component_results if cr.has_error()), False )
def get_errors(self): """If there were any business errors fetching data for this property, returns the error messages. Returns: string - the error message, or None if there was no error. """ return [{cr.component_name: cr.get_error()} for cr in self.component_results if cr.has_error()]
def create_from_json(cls, json_data): """Deserialize property json data into a Property object Args: json_data (dict): The json data for this property Returns: Property object """ prop = Property() address_info = json_data["address_info"] prop.address = address_info["address"] prop.block_id = address_info["block_id"] p...
= address_info["state"] prop.unit = address_info["unit"] prop.meta = None if "meta" in json_data: prop.meta = json_data["meta"] prop.component_results = _create_component_results(json_data, "address_info") return prop
def create_from_json(cls, json_data): """Deserialize block json data into a Block object Args: json_data (dict): The json data for this block Returns: Block object """ block = Block() block_info = json_data["block_info"] block.block_id = block_info["block_id"] block.num_bins = block_info["num_bins"] if "num_bins" in bl...
return block
def create_from_json(cls, json_data): """Deserialize zipcode json data into a ZipCode object Args: json_data (dict): The json data for this zipcode Returns: Zip object """ zipcode = ZipCode() zipcode.zipcode = json_data["zipcode_info"]["zipcode"] zipcode.meta = json_data["meta"] if "meta" in json_data else None zipcode...
def create_from_json(cls, json_data): """Deserialize msa json data into a Msa object Args: json_data (dict): The json data for this msa Returns: Msa object """ msa = Msa() msa.msa = json_data["msa_info"]["msa"] msa.meta = json_data["meta"] if "meta" in json_data else None msa.component_results = _create_component_resul...
def starts_when(iterable, condition): # type: (Iterable, Union[Callable, Any]) -> Iterable """Start yielding items when a condition arise. Args: iterable: the iterable to filter. condition: if the callable returns True once, start yielding items. If it's not a callable, it will be converted to one as `lambda condition:...
7)) [7, 8, 9] """ if not callable(condition): cond_value = condition def condition(x): return x == cond_value return itertools.dropwhile(lambda x: not condition(x), iterable)
def stops_when(iterable, condition): # type: (Iterable, Union[Callable, Any]) -> Iterable """Stop yielding items when a condition arise. Args: iterable: the iterable to filter. condition: if the callable returns True once, stop yielding items. If it's not a callable, it will be converted to one as `lambda condition: co...
>>> list(stops_when(range(10), 7)) [0, 1, 2, 3, 4, 5, 6] """ if not callable(condition): cond_value = condition def condition(x): return x == cond_value return itertools.takewhile(lambda x: not condition(x), iterable)
def skip_duplicates(iterable, key=None, fingerprints=()): # type: (Iterable, Callable, Any) -> Iterable """ Returns a generator that will yield all objects from iterable, skipping duplicates. Duplicates are identified using the `key` function to calculate a unique fingerprint. This does not use natural equality, but th...
fingerprint is the object itself, which ensure the functions works as-is with an iterable of primitives such as int, str or tuple. :Example: >>> list(skip_duplicates([1, 2, 3, 4, 4, 2, 1, 3 , 4])) [1, 2, 3, 4] The return value of `key` MUST be hashable, which means for non hashable objects such as dict, set or list, yo...
function that returns a hashable fingerprint. :Example: >>> list(skip_duplicates(([], [], (), [1, 2], (1, 2)), ... lambda x: tuple(x))) [[], [1, 2]] >>> list(skip_duplicates(([], [], (), [1, 2], (1, 2)), ... lambda x: (type(x), tuple(x)))) [[], (), [1, 2], (1, 2)] For more complex types, such as custom classes, the def...
wish to filter those. :Example: >>> class Test(object): ... def __init__(self, foo='bar'): ... self.foo = foo ... def __repr__(self): ... return "Test('%s')" % self.foo ... >>> list(skip_duplicates([Test(), Test(), Test('other')])) [Test('bar'), Test('bar'), Test('other')] >>> list(skip_duplicates([Test(), Test(), Test...
gain perf in the most common case if key is None: for x in iterable: if x not in fingerprints: yield x fingerprints.add(x) else: for x in iterable: fingerprint = key(x) if fingerprint not in fingerprints: yield x fingerprints.add(fingerprint) except TypeError: try: hash(fingerprint) except TypeError: raise TypeError( "...
this function always " "returns a hashable object. Hint: immutable primitives like" "int, str or tuple, are hashable while dict, set and list are " "not." % (type(fingerprint), x)) else: raise
def chunks(iterable, chunksize, cast=tuple): # type: (Iterable, int, Callable) -> Iterable """ Yields items from an iterator in iterable chunks. """ it = iter(iterable) while True: yield cast(itertools.chain([next(it)], itertools.islice(it, chunksize - 1)))
def window(iterable, size=2, cast=tuple): # type: (Iterable, int, Callable) -> Iterable """ Yields iterms by bunch of a given size, but rolling only one item in and out at a time when iterating. >>> list(window([1, 2, 3])) [(1, 2), (2, 3)] By default, this will cast the window to a tuple before yielding it; however, an...
argument is a valid target. If you pass None as a cast value, the deque will be returned as-is, which is more performant. However, since only one deque is used for the entire iteration, you'll get the same reference everytime, only the deque will contains different items. The result might not be what you want : >>> lis...
deque([2, 3], maxlen=2)] """ iterable = iter(iterable) d = deque(itertools.islice(iterable, size), size) if cast: yield cast(d) for x in iterable: d.append(x) yield cast(d) else: yield d for x in iterable: d.append(x) yield d
def at_index(iterable, index): # type: (Iterable[T], int) -> T """" Return the item at the index of this iterable or raises IndexError. WARNING: this will consume generators. Negative indices are allowed but be aware they will cause n items to be held in memory, where n = abs(index) """ try: if index < 0: return deque(...
(StopIteration, IndexError) as e: raise_from(IndexError('Index "%d" out of range' % index), e)
def first_true(iterable, func): # type: (Iterable[T], Callable) -> T """" Return the first item of the iterable for which func(item) == True. Or raises IndexError. WARNING: this will consume generators. """ try: return next((x for x in iterable if func(x))) except StopIteration as e: # TODO: Find a better error message...
def iterslice(iterable, start=0, stop=None, step=1): # type: (Iterable[T], int, int, int) -> Iterable[T] """ Like itertools.islice, but accept int and callables. If `start` is a callable, start the slice after the first time start(item) == True. If `stop` is a callable, stop the slice after the first time stop(item) ==...
given" % step) if not isinstance(start, int): # [Callable:Callable] if not isinstance(stop, int) and stop: return stops_when(starts_when(iterable, start), stop) # [Callable:int] return starts_when(itertools.islice(iterable, None, stop, step), start) # [int:Callable] if not isinstance(stop, int) and stop: return stops_w...
def firsts(iterable, items=1, default=None): # type: (Iterable[T], int, T) -> Iterable[T] """ Lazily return the first x items from this iterable or default. """ try: items = int(items) except (ValueError, TypeError): raise ValueError("items should be usable as an int but is currently " "'{}' of type '{}'".format(items,...
{items} but should " "be greater than 0. If you wish to get the last " "items, use the lasts() function.")) i = 0 for i, item in zip(range(items), iterable): yield item for x in range(items - (i + 1)): yield default
def lasts(iterable, items=1, default=None): # type: (Iterable[T], int, T) -> Iterable[T] """ Lazily return the last x items from this iterable or default. """ last_items = deque(iterable, maxlen=items) for _ in range(items - len(last_items)): yield default for y in last_items: yield y
def is_legacy_server(): '''Determine execution mode. Legacy mode: <= v4.20181215 ''' with Session() as session: ret = session.Kernel.hello() bai_version = ret['version'] legacy = True if bai_version <= 'v4.20181215' else False return legacy
def close(self): ''' Terminates the session. It schedules the ``close()`` coroutine of the underlying aiohttp session and then enqueues a sentinel object to indicate termination. Then it waits until the worker thread to self-terminate by joining. ''' if self._closed: return self._closed = True self._worker_thread.work_...
def asyncio_run_forever(setup_coro, shutdown_coro, *, stop_signals={signal.SIGINT}, debug=False): ''' A proposed-but-not-implemented asyncio.run_forever() API based on @vxgmichel's idea. See discussions on https://github.com/python/asyncio/pull/465 ''' async def wait_for_stop(): loop = current_loop() future = loop.crea...