code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def run(self, call, num_alts): for key, value in call.data.items(): self._check_count(call, key, value, num_alts)
Check ``FORMAT`` of a record.Call Currently, only checks for consistent counts are implemented
def _read_next_line(self): prev_line = self._line self._line = self.stream.readline() return prev_line
Read next line store in self._line and return old one
def parse_header(self, parsed_samples=None): # parse header lines sub_parser = HeaderParser() header_lines = [] while self._line and self._line.startswith("##"): header_lines.append(sub_parser.parse_line(self._line)) self._read_next_line() # parse...
Read and parse :py:class:`vcfpy.header.Header` from file, set into ``self.header`` and return it :param list parsed_samples: ``list`` of ``str`` for subsetting the samples to parse :returns: ``vcfpy.header.Header`` :raises: ``vcfpy.exceptions.InvalidHeaderException`` in the ...
def _handle_sample_line(self, parsed_samples=None): Check and interpret the "##CHROM" line and return samples""" if not self._line or not self._line.startswith("#CHROM"): raise exceptions.IncorrectVCFFormat('Missing line starting with "#CHROM"') # check for space before INFO ...
Check and interpret the "##CHROM" line and return samples
def _check_samples_line(klass, arr): if len(arr) <= len(REQUIRE_NO_SAMPLE_HEADER): if tuple(arr) != REQUIRE_NO_SAMPLE_HEADER: raise exceptions.IncorrectVCFFormat( "Sample header line indicates no sample but does not " "equal required p...
Peform additional check on samples line
def numpy(): '''Lazily import the numpy module''' if LazyImport.numpy_module is None: try: LazyImport.numpy_module = __import__('numpypy') except ImportError: try: LazyImport.numpy_module = __import__('numpy') ex...
Lazily import the numpy module
def rpy2(): '''Lazily import the rpy2 module''' if LazyImport.rpy2_module is None: try: rpy2 = __import__('rpy2.robjects') except ImportError: raise ImportError('The rpy2 module is required') LazyImport.rpy2_module = rpy2 tr...
Lazily import the rpy2 module
def map_position(pos): posiction_dict = dict(zip(range(1, 17), [i for i in range(30, 62) if i % 2])) return posiction_dict[pos]
Map natural position to machine code postion
def snap(self, path=None): if path is None: path = "/tmp" else: path = path.rstrip("/") day_dir = datetime.datetime.now().strftime("%d%m%Y") hour_dir = datetime.datetime.now().strftime("%H%M") ensure_snapshot_dir(path+"/"+self.cam_id+"/"+day_dir+"...
Get a snapshot and save it to disk.
def move(self, pos): try: payload = {"address":self.address, "user": self.user, "pwd": self.pswd, "pos": map_position(pos)} resp = requests.get( "http://{address}/decoder_control.cgi?command={pos}&user={user}&pwd={pwd}".format(**payload) ) ...
Move cam to given preset position. pos - must be within 1 to 16. Returns: CamException in case of errors, "ok" otherwise.
def status(self): resp = requests.get("http://{0}/get_status.cgi".format(self.address)) data = resp.text.replace(";", "") data = data.replace("var", "") data_s = data.split("\n") # Last is an empty line data_s.pop() data_array = [s.split("=") for s in d...
Retrieve some configuration params. Note: info are returned even without password
def findOODWords(isleDict, wordList): ''' Returns all of the out-of-dictionary words found in a list of utterances ''' oodList = [] for word in wordList: try: isleDict.lookup(word) except WordNotInISLE: oodList.append(word) oodList = list(...
Returns all of the out-of-dictionary words found in a list of utterances
def autopair(isleDict, wordList): ''' Tests whether adjacent words are OOD or not It returns complete wordLists with the matching words replaced. Each match yields one sentence. e.g. red ball chaser would return [[red_ball chaser], [red ball_chaser]], [0, 1] if 'red_ba...
Tests whether adjacent words are OOD or not It returns complete wordLists with the matching words replaced. Each match yields one sentence. e.g. red ball chaser would return [[red_ball chaser], [red ball_chaser]], [0, 1] if 'red_ball' and 'ball_chaser' were both in the diction...
def _buildDict(self): ''' Builds the isle textfile into a dictionary for fast searching ''' lexDict = {} with io.open(self.islePath, "r", encoding='utf-8') as fd: wordList = [line.rstrip('\n') for line in fd] for row in wordList: word, pro...
Builds the isle textfile into a dictionary for fast searching
def search(self, matchStr, numSyllables=None, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok', multiword='ok', pos=None): ''' for help on isletool.LexicalTool.search(), see see isletool.search() ''' return search(self.data.items(),...
for help on isletool.LexicalTool.search(), see see isletool.search()
def timestamps(self): '''Get all timestamps from all series in the group.''' timestamps = set() for series in self.groups.itervalues(): timestamps |= set(series.timestamps) return sorted(list(timestamps)f timestamps(self): '''Get all timestamps from all series in the ...
Get all timestamps from all series in the group.
def trend(self, **kwargs): '''Calculate a trend for all series in the group. See the `TimeSeries.trend()` method for more information.''' return DataFrame({ name: series.trend(**kwargs) \ for name, series in self.groups.iteritems() }f trend(self, **kwargs): '''Calculate a tre...
Calculate a trend for all series in the group. See the `TimeSeries.trend()` method for more information.
def forecast(self, horizon, **kwargs): '''Forecast all time series in the group. See the `TimeSeries.forecast()` method for more information.''' return DataFrame({ name: series.forecast(horizon, **kwargs) \ for name, series in self.groups.iteritems() }f forecast(self, horizon, **kwar...
Forecast all time series in the group. See the `TimeSeries.forecast()` method for more information.
def plot(self, overlay=True, **labels): # pragma: no cover '''Plot all time series in the group.''' pylab = LazyImport.pylab() colours = list('rgbymc') colours_len = len(colours) colours_pos = 0 plots = len(self.groups) for name, series in self.groups.iteritems():...
Plot all time series in the group.
def rename(self, **kwargs): '''Rename series in the group.''' for old, new in kwargs.iteritems(): if old in self.groups: self.groups[new] = self.groups[old] del self.groups[oldf rename(self, **kwargs): '''Rename series in the group.''' for old,...
Rename series in the group.
def from_stream( klass, stream, path=None, tabix_path=None, record_checks=None, parsed_samples=None ): record_checks = record_checks or [] if tabix_path and not path: raise ValueError("Must give path if tabix_path is given") return Reader( stream=stre...
Create new :py:class:`Reader` from file .. note:: If you use the ``parsed_samples`` feature and you write out records then you must not change the ``FORMAT`` of the record. :param stream: ``file``-like object to read from :param path: optional string with path to store ...
def from_path(klass, path, tabix_path=None, record_checks=None, parsed_samples=None): record_checks = record_checks or [] path = str(path) if path.endswith(".gz"): f = gzip.open(path, "rt") if not tabix_path: tabix_path = path + ".tbi" ...
Create new :py:class:`Reader` from path .. note:: If you use the ``parsed_samples`` feature and you write out records then you must not change the ``FORMAT`` of the record. :param path: the path to load from (converted to ``str`` for compatibility with ``path.py``) ...
def fetch(self, chrom_or_region, begin=None, end=None): if begin is not None and end is None: raise ValueError("begin and end must both be None or neither") # close tabix file if any and is open if self.tabix_file and not self.tabix_file.closed: self.tabix_file.c...
Jump to the start position of the given chromosomal position and limit iteration to the end position :param str chrom_or_region: name of the chromosome to jump to if begin and end are given and a samtools region string otherwise (e.g. "chr1:123,456-123,900"). :param int ...
def close(self): if self.tabix_file and not self.tabix_file.closed: self.tabix_file.close() if self.stream: self.stream.close()
Close underlying stream
def serialize_for_header(key, value): if key in QUOTE_FIELDS: return json.dumps(value) elif isinstance(value, str): if " " in value or "\t" in value: return json.dumps(value) else: return value elif isinstance(value, list): return "[{}]".format(",...
Serialize value for the given mapping key for a VCF header line
def header_without_lines(header, remove): remove = set(remove) # Copy over lines that are not removed lines = [] for line in header.lines: if hasattr(line, "mapping"): if (line.key, line.mapping.get("ID", None)) in remove: continue # filter out else: ...
Return :py:class:`Header` without lines given in ``remove`` ``remove`` is an iterable of pairs ``key``/``ID`` with the VCF header key and ``ID`` of entry to remove. In the case that a line does not have a ``mapping`` entry, you can give the full value to remove. .. code-block:: python # head...
def mapping_to_str(mapping): result = ["<"] for i, (key, value) in enumerate(mapping.items()): if i > 0: result.append(",") result += [key, "=", serialize_for_header(key, value)] result += [">"] return "".join(result)
Convert mapping to string
def _build_indices(self): result = {key: OrderedDict() for key in LINES_WITH_ID} for line in self.lines: if line.key in LINES_WITH_ID: result.setdefault(line.key, OrderedDict()) if line.mapping["ID"] in result[line.key]: warnings.w...
Build indices for the different field types
def copy(self): return Header([line.copy() for line in self.lines], self.samples.copy())
Return a copy of this header
def get_lines(self, key): if key in self._indices: return self._indices[key].values() else: return []
Return header lines having the given ``key`` as their type
def has_header_line(self, key, id_): if key not in self._indices: return False else: return id_ in self._indices[key]
Return whether there is a header line with the given ID of the type given by ``key`` :param key: The VCF header key/line type. :param id_: The ID value to compare fore :return: ``True`` if there is a header line starting with ``##${key}=`` in the VCF file having the mapping...
def add_line(self, header_line): self.lines.append(header_line) self._indices.setdefault(header_line.key, OrderedDict()) if not hasattr(header_line, "mapping"): return False # no registration required if self.has_header_line(header_line.key, header_line.mapping["ID"...
Add header line, updating any necessary support indices :return: ``False`` on conflicting line and ``True`` otherwise
def copy(self): mapping = OrderedDict(self.mapping.items()) return self.__class__(self.key, self.value, mapping)
Return a copy
def _parse_number(klass, number): try: return int(number) except ValueError as e: if number in VALID_NUMBERS: return number else: raise e
Parse ``number`` into an ``int`` or return ``number`` if a valid expression for a INFO/FORMAT "Number". :param str number: ``str`` to parse and check
def _syllabifyPhones(phoneList, syllableList): ''' Given a phone list and a syllable list, syllabify the phones Typically used by findBestSyllabification which first aligns the phoneList with a dictionary phoneList and then uses the dictionary syllabification to syllabify the input phoneList. ...
Given a phone list and a syllable list, syllabify the phones Typically used by findBestSyllabification which first aligns the phoneList with a dictionary phoneList and then uses the dictionary syllabification to syllabify the input phoneList.
def _getSyllableNucleus(phoneList): ''' Given the phones in a syllable, retrieves the vowel index ''' cvList = ['V' if isletool.isVowel(phone) else 'C' for phone in phoneList] vowelCount = cvList.count('V') if vowelCount > 1: raise TooManyVowelsInSyllable(phoneList, cvList) ...
Given the phones in a syllable, retrieves the vowel index
def findClosestPronunciation(inputIsleWordList, aPron): ''' Find the closest dictionary pronunciation to a provided pronunciation ''' retList = _findBestPronunciation(inputIsleWordList, aPron) isleWordList = retList[0] bestIndex = retList[3] return isleWordList[bestIndexf findClose...
Find the closest dictionary pronunciation to a provided pronunciation
def create_switch(type, settings, pin): switch = None if type == "A": group, device = settings.split(",") switch = pi_switch.RCSwitchA(group, device) elif type == "B": addr, channel = settings.split(",") addr = int(addr) channel = int(channel) switch = pi_switch.RCSwitchB(addr, channel) elif type =...
Create a switch. Args: type: (str): type of the switch [A,B,C,D] settings (str): a comma separted list pin (int): wiringPi pin Returns: switch
def format_atomic(value): # Perform escaping if isinstance(value, str): if any(r in value for r in record.RESERVED_CHARS): for k, v in record.ESCAPE_MAPPING: value = value.replace(k, v) # String-format the given value if value is None: return "." else...
Format atomic value This function also takes care of escaping the value in case one of the reserved characters occurs in the value.
def format_value(field_info, value, section): if section == "FORMAT" and field_info.id == "FT": if not value: return "." elif isinstance(value, list): return ";".join(map(format_atomic, value)) elif field_info.number == 1: if value is None: return...
Format possibly compound value given the FieldInfo
def from_stream(klass, stream, header, path=None, use_bgzf=None): if use_bgzf or (use_bgzf is None and path and path.endswith(".gz")): stream = bgzf.BgzfWriter(fileobj=stream) return Writer(stream, header, path)
Create new :py:class:`Writer` from file Note that for getting bgzf support, you have to pass in a stream opened in binary mode. Further, you either have to provide a ``path`` ending in ``".gz"`` or set ``use_bgzf=True``. Otherwise, you will get the notorious "TypeError: 'str' does not...
def from_path(klass, path, header): path = str(path) use_bgzf = False # we already interpret path if path.endswith(".gz"): f = bgzf.BgzfWriter(filename=path) else: f = open(path, "wt") return klass.from_stream(f, header, path, use_bgzf=use_bgzf)
Create new :py:class:`Writer` from path :param path: the path to load from (converted to ``str`` for compatibility with ``path.py``) :param header: VCF header to use, lines and samples are deep-copied
def _write_header(self): for line in self.header.lines: print(line.serialize(), file=self.stream) if self.header.samples.names: print( "\t".join(list(parser.REQUIRE_SAMPLE_HEADER) + self.header.samples.names), file=self.stream, ...
Write out the header
def _serialize_record(self, record): f = self._empty_to_dot row = [record.CHROM, record.POS] row.append(f(";".join(record.ID))) row.append(f(record.REF)) if not record.ALT: row.append(".") else: row.append(",".join([f(a.serialize()) for a ...
Serialize whole Record
def _serialize_info(self, record): result = [] for key, value in record.INFO.items(): info = self.header.get_info_field_info(key) if info.type == "Flag": result.append(key) else: result.append("{}={}".format(key, format_value(i...
Return serialized version of record.INFO
def _serialize_call(self, format_, call): if isinstance(call, record.UnparsedCall): return call.unparsed_data else: result = [ format_value(self.header.get_format_field_info(key), call.data.get(key), "FORMAT") for key in format_ ...
Return serialized version of the Call using the record's FORMAT
def _create_extended_jinja_tags(self, nodes): jinja_a = None jinja_b = None ext_node = None ext_nodes = [] for node in nodes: if isinstance(node, EmptyLine): continue if node.has_children(): node.children = sel...
Loops through the nodes and looks for special jinja tags that contains more than one tag but only one ending tag.
def has_children(self): "returns False if children is empty or contains only empty lines else True." return bool([x for x in self.children if not isinstance(x, EmptyLine)]f has_children(self): "returns False if children is empty or contains only empty lines else True." return bool([x for...
returns False if children is empty or contains only empty lines else True.
def parse_requirements(path): requirements = [] with open(path, "rt") as reqs_f: for line in reqs_f: line = line.strip() if line.startswith("-r"): fname = line.split()[1] inner_path = os.path.join(os.path.dirname(path), fname) ...
Parse ``requirements.txt`` at ``path``.
def __parse_args(cam_c): user = None pswd = None name = None address = "{address}:{port}".format(**cam_c) if "user" in cam_c: user = cam_c["user"] if "pswd" in cam_c: pswd = cam_c["pswd"] if "name" in cam_c: name = cam_c["name"] return {"user": user, ...
Arrange class init params from conf file. Returns: a dict with values.
def load_cams(conf_file): with open(conf_file, "r") as c_file: lines = c_file.readlines() cams_conf = [json.loads(j) for j in lines] cams = [] for cam_c in cams_conf: init_params = __parse_args(cam_c) cams.append(cam_types[cam_c["type"]](**init_params)) return cams
Reads cams conf from file and intantiate appropiate classes. Returns: an array of IpCam classes.
def watch(cams, path=None, delay=10): while True: for c in cams: c.snap(path) time.sleep(delay)
Get screenshots from all cams at defined intervall.
def score(self, phone_number, account_lifecycle_event, **params): return self.post(SCORE_RESOURCE.format(phone_number=phone_number), account_lifecycle_event=account_lifecycle_event, **params)
Score is an API that delivers reputation scoring based on phone number intelligence, traffic patterns, machine learning, and a global data consortium. See https://developer.telesign.com/docs/score-api for detailed API documentation.
def load_version(filename='fuzzyhashlib/version.py'): with open(filename) as source: text = source.read() match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", text) if not match: msg = "Unable to find version number in {}".format(filename) raise RuntimeError(...
Parse a __version__ number from a source file
def post(self, resource, **params): return self._execute(self.session.post, 'POST', resource, **params)
Generic TeleSign REST API POST handler. :param resource: The partial resource URI to perform the request against, as a string. :param params: Body params to perform the POST request with, as a dictionary. :return: The RestClient Response object.
def get(self, resource, **params): return self._execute(self.session.get, 'GET', resource, **params)
Generic TeleSign REST API GET handler. :param resource: The partial resource URI to perform the request against, as a string. :param params: Body params to perform the GET request with, as a dictionary. :return: The RestClient Response object.
def put(self, resource, **params): return self._execute(self.session.put, 'PUT', resource, **params)
Generic TeleSign REST API PUT handler. :param resource: The partial resource URI to perform the request against, as a string. :param params: Body params to perform the PUT request with, as a dictionary. :return: The RestClient Response object.
def delete(self, resource, **params): return self._execute(self.session.delete, 'DELETE', resource, **params)
Generic TeleSign REST API DELETE handler. :param resource: The partial resource URI to perform the request against, as a string. :param params: Body params to perform the DELETE request with, as a dictionary. :return: The RestClient Response object.
def _execute(self, method_function, method_name, resource, **params): resource_uri = "{api_host}{resource}".format(api_host=self.api_host, resource=resource) url_encoded_fields = self._encode_params(params) headers = RestClient.generate_telesign_headers(self.customer_id, ...
Generic TeleSign REST API request handler. :param method_function: The Requests HTTP request function to perform the request. :param method_name: The HTTP method name, as an upper case string. :param resource: The partial resource URI to perform the request against, as a string. :param ...
def message(self, phone_number, message, message_type, **params): return self.post(MESSAGING_RESOURCE, phone_number=phone_number, message=message, message_type=message_type, **params)
Send a message to the target phone_number. See https://developer.telesign.com/docs/messaging-api for detailed API documentation.
def status(self, reference_id, **params): return self.get(MESSAGING_STATUS_RESOURCE.format(reference_id=reference_id), **params)
Retrieves the current status of the message. See https://developer.telesign.com/docs/messaging-api for detailed API documentation.
def phoneid(self, phone_number, **params): return self.post(PHONEID_RESOURCE.format(phone_number=phone_number), **params)
The PhoneID API provides a cleansed phone number, phone type, and telecom carrier information to determine the best communication method - SMS or voice. See https://developer.telesign.com/docs/phoneid-api for detailed API documentation.
def hexdigest(self): if self._pre_computed_hash is None: return libssdeep_wrapper.fuzzy_digest(self._state, 0) else: return self._pre_computed_hash
Return the digest value as a string of hexadecimal digits.
def update(self, buf): if self._updatable: return libssdeep_wrapper.fuzzy_update(self._state, buf) else: raise InvalidOperation("Cannot update sdeep created from hash")
Update this hash object's state with the provided string.
def copy(self): if self._pre_computed_hash is None: temp = ssdeep(buf="") else: temp = ssdeep(hash=hash) libssdeep_wrapper.fuzzy_free(temp._state) temp._state = libssdeep_wrapper.fuzzy_clone(self._state) temp._updatable = self._updatable t...
Returns a new instance which identical to this instance.
def hexdigest(self): if not self._final: if self._buf_len >= self._MIN_LEN: self._tlsh.final() self._final = True else: raise ValueError("tlsh requires buffer with length >= %d " "for mode where for...
Return the digest value as a string of hexadecimal digits.
def update(self, buf): if self._final: raise InvalidOperation("Cannot update finalised tlsh") else: self._buf_len += len(buf) return self._tlsh.update(buf)
Update this hash object's state with the provided string.
def call(self, phone_number, message, message_type, **params): return self.post(VOICE_RESOURCE, phone_number=phone_number, message=message, message_type=message_type, **params)
Send a voice call to the target phone_number. See https://developer.telesign.com/docs/voice-api for detailed API documentation.
def status(self, reference_id, **params): return self.get(VOICE_STATUS_RESOURCE.format(reference_id=reference_id), **params)
Retrieves the current status of the voice call. See https://developer.telesign.com/docs/voice-api for detailed API documentation.
def status(self, external_id, **params): return self.get(APPVERIFY_STATUS_RESOURCE.format(external_id=external_id), **params)
Retrieves the verification result for an App Verify transaction by external_id. To ensure a secure verification flow you must check the status using TeleSign's servers on your backend. Do not rely on the SDK alone to indicate a successful verification. See https://developer.telesign.com/docs/ap...
def get_asset_location(element, attr): asset_location = re.match(r'^/?(static)?/?(.*)', element[attr], re.IGNORECASE) # replace relative links i.e (../../static) asset_location = asset_location.group(2).replace('../', '') return asset_location
Get Asset Location. Remove leading slash e.g '/static/images.jpg' ==> static/images.jpg Also, if the url is also prefixed with static, it would be removed. e.g static/image.jpg ==> image.jpg
def transform(matches, framework, namespace, static_endpoint): transformed = [] namespace = namespace + '/' if namespace else '' for attribute, elements in matches: for element in elements: asset_location = get_asset_location(element, attribute) # string substitution ...
The actual transformation occurs here. flask example: images/staticfy.jpg', ==> "{{ url_for('static', filename='images/staticfy.jpg') }}"
def get_elements(html_file, tags): with open(html_file) as f: document = BeautifulSoup(f, 'html.parser') def condition(tag, attr): # Don't include external links return lambda x: x.name == tag \ and not x.get(attr, 'http').startswith(('http', '//')) ...
Extract all the elements we're interested in. Returns a list of tuples with the attribute as first item and the list of elements as the second item.
def replace_lines(html_file, transformed): result = [] with codecs.open(html_file, 'r', 'utf-8') as input_file: for line in input_file: # replace all single quotes with double quotes line = re.sub(r'\'', '"', line) for attr, value, new_link in transformed: ...
Replace lines in the old file with the transformed lines.
def staticfy(html_file, args=argparse.ArgumentParser()): # unpack arguments static_endpoint = args.static_endpoint or 'static' framework = args.framework or os.getenv('STATICFY_FRAMEWORK', 'flask') add_tags = args.add_tags or {} exc_tags = args.exc_tags or {} namespace = args.namespace or {...
Staticfy method. Loop through each line of the file and replaces the old links
def file_ops(staticfied, args): destination = args.o or args.output if destination: with open(destination, 'w') as file: file.write(staticfied) else: print(staticfied)
Write to stdout or a file
def parse_cmd_arguments(): parser = argparse.ArgumentParser() parser.add_argument('file', type=str, help='Filename to be staticfied') parser.add_argument('--static-endpoint', help='Static endpoint which is "static" by default') parser.add_argument('--...
Parse command line arguments.
def main(): args = parse_cmd_arguments() html_file = args.file try: json.loads(args.add_tags or '{}') json.loads(args.exc_tags or '{}') except ValueError: print('\033[91m' + 'Invalid json string: please provide a valid json ' 'string e.g {}'.format('\'{"img": ...
Main method.
def find_keys(args): key = args['--key'] if key: return [key] keyfile = args['--apikeys'] if keyfile: return read_keyfile(keyfile) envkey = os.environ.get('TINYPNG_API_KEY', None) if envkey: return [envkey] local_keys = join(abspath("."), "tinypng.keys") ...
Get keys specified in arguments returns list of keys or None
def get_shrink_data_info(in_data, api_key=None): if api_key: return _shrink_info(in_data, api_key) api_keys = find_keys() for key in api_keys: try: return _shrink_info(in_data, key) except ValueError: pass raise ValueError('No valid api key found')
Shrink binary data of a png returns api_info
def get_shrunk_data(shrink_info): out_url = shrink_info['output']['url'] try: return requests.get(out_url).content except HTTPError as err: if err.code != 404: raise exc = ValueError("Unable to read png file \"{0}\"".format(out_url)) exc.__cause__ = err ...
Read shrunk file from tinypng.org api.
def shrink_data(in_data, api_key=None): info = get_shrink_data_info(in_data, api_key) return info, get_shrunk_data(info)
Shrink binary data of a png returns (api_info, shrunk_data)
def shrink_file(in_filepath, api_key=None, out_filepath=None): info = get_shrink_file_info(in_filepath, api_key, out_filepath) write_shrunk_file(info) return info
Shrink png file and write it back to a new file The default file path replaces ".png" with ".tiny.png". returns api_info (including info['ouput']['filepath'])
def verify_telesign_callback_signature(api_key, signature, json_str): your_signature = b64encode(HMAC(b64decode(api_key), json_str.encode("utf-8"), sha256).digest()).decode("utf-8") if len(signature) != len(your_signature): return False # avoid timing attack with constant time equality check ...
Verify that a callback was made by TeleSign and was not sent by a malicious client by verifying the signature. :param api_key: the TeleSign API api_key associated with your account. :param signature: the TeleSign Authorization header value supplied in the callback, as a string. :param json_str: the POST bo...
def add_item(self, host, key, value, clock=None, state=0): if clock is None: clock = self.clock if self._config.data_type == "items": item = {"host": host, "key": key, "value": value, "clock": clock, "state": state} elif self._config.data_type...
Add a single item into DataContainer :host: hostname to which item will be linked to :key: item key as defined in Zabbix :value: item value :clock: timestemp as integer. If not provided self.clock()) will be used
def add(self, data): for host in data: for key in data[host]: if not data[host][key] == []: self.add_item(host, key, data[host][key])
Add a list of item into the container :data: dict of items & value per hostname
def _send_common(self, item): total = len(item) processed = failed = time = 0 if self._config.dryrun is True: total = len(item) processed = failed = time = 0 response = 'dryrun' else: self._send_to_zabbix(item) response...
Common part of sending operations Calls SenderProtocol._send_to_zabbix Returns result as provided by _handle_response :item: either a list or a single item depending on debug_level
def _reset(self): # Reset DataContainer to default values # So that it can be reused if self.logger: # pragma: no cover self.logger.info("Reset DataContainer") self._items_list = [] self._config.data_type = None
Reset main DataContainer properties
def logger(self, value): if isinstance(value, logging.Logger): self._logger = value else: if self._logger: # pragma: no cover self._logger.error("logger requires a logging instance") raise ValueError('logger requires a logging instance')
Set logger instance for the class
def bind(self, event_name, callback): if event_name not in self.event_callbacks.keys(): self.event_callbacks[event_name] = [] self.event_callbacks[event_name].append(callback)
Bind an event to a callback :param event_name: The name of the event to bind to. :type event_name: str :param callback: The callback to notify of this event.
def get_issue(self, issue_id, params=None): return self._get(self.API_URL + 'issue/{}'.format(issue_id), params=params)
Returns a full representation of the issue for the given issue key. The issue JSON consists of the issue key and a collection of fields. Additional information like links to workflow transition sub-resources, or HTML rendered values of the fields supporting HTML rendering can be retrieved with ...
def create_issue(self, data, params=None): return self._post(self.API_URL + 'issue', data=data, params=params)
Creates an issue or a sub-task from a JSON representation. You can provide two parameters in request's body: update or fields. The fields, that can be set on an issue create operation, can be determined using the /rest/api/2/issue/createmeta resource. If a particular field is not configured to ...
def delete_issue(self, issue_id, params=None): return self._delete(self.API_URL + 'issue/{}'.format(issue_id), params=params)
Deletes an individual issue. If the issue has sub-tasks you must set the deleteSubtasks=true parameter to delete the issue. You cannot delete an issue without deleting its sub-tasks. Args: issue_id: params: Returns:
def subscribe(self, channel_name): data = {'channel': channel_name} if channel_name.startswith('presence-'): data['auth'] = self._generate_presence_key( self.connection.socket_id, self.key, channel_name, self.secret, ...
Subscribe to a channel :param channel_name: The name of the channel to subscribe to. :type channel_name: str :rtype : Channel
def _handle_response(self, zbx_answer): zbx_answer = json.loads(zbx_answer) if self._logger: # pragma: no cover self._logger.info( "Anaylizing Zabbix Server's answer" ) if zbx_answer: self._logger.debug("Zabbix Server response ...
Analyze Zabbix Server response Returns a list with number of: * processed items * failed items * total items * time spent :zbx_answer: Zabbix server response as string
def list(self, pagination=True, page_size=None, page=None, **queryparams): if page_size and pagination: try: page_size = int(page_size) except (ValueError, TypeError): page_size = 100 queryparams['page_size'] = page_size result...
Retrieves a list of objects. By default uses local cache and remote pagination If pagination is used and no page is requested (the default), all the remote objects are retrieved and appended in a single list. If pagination is disabled, all the objects are fetched from the endp...
def parse(cls, requester, entries): result_entries = SearchableList() for entry in entries: result_entries.append(cls.instance.parse(requester, entry)) return result_entries
Parse a JSON array into a list of model instances.
def parse_list(self, entries): result_entries = SearchableList() for entry in entries: result_entries.append(self.instance.parse(self.requester, entry)) return result_entries
Parse a JSON array into a list of model instances.
def update(self, **args): self_dict = self.to_dict() if args: self_dict = dict(list(self_dict.items()) + list(args.items())) response = self.requester.put( '/{endpoint}/{id}', endpoint=self.endpoint, id=self.id, payload=self_dict ) obj...
Update the current :class:`InstanceResource`
def patch(self, fields, **args): self_dict = dict([(key, value) for (key, value) in self.to_dict().items() if key in fields]) if args: self_dict = dict(list(self_dict.items()) + list(args.items())) response = self.requester...
Patch the current :class:`InstanceResource`