docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Verifying a mailfy query in this platform. This might be redefined in any class inheriting from Platform. The only condition is that any of this should return a dictionary as defined. Args: ----- query: The element to be searched. kwargs: Dictionary with extra p...
def check_searchfy(self, query, kwargs={}): data = self.launchQueryForMode(query=query, mode="searchfy") if self._somethingFound(data, mode="searchfy"): return data return None
438,383
Verifying a mailfy query in this platform. This might be redefined in any class inheriting from Platform. The only condition is that any of this should return a dictionary as defined. Args: ----- query: The element to be searched. kwargs: Dictionary with extra p...
def check_phonefy(self, query, kwargs={}): data = self.launchQueryForMode(query=query, mode="phonefy") if self._somethingFound(data, mode="phonefy"): return data return None
438,385
Verifying a phonefy query in this platform. This might be redefined in any class inheriting from Platform. Args: ----- query: The element to be searched. Return: ------- A list of elements to be appended.
def do_phonefy(self, query, **kwargs): results = [] test = self.check_phonefy(query, kwargs) if test: r = { "type": "i3visio.phone", "value": self.platformName + " - " + query, "attributes": [] } try:...
438,386
Verifying a mailfy query in this platform. This might be redefined in any class inheriting from Platform. The only condition is that any of this should return a dictionary as defined. Args: ----- query: The element to be searched. kwargs: Dictionary with extra parameter...
def check_usufy(self, query, **kwargs): data = self.launchQueryForMode(query=query, mode="usufy") if self._somethingFound(data, mode="usufy"): return data return None
438,387
Verifying a usufy query in this platform. This might be redefined in any class inheriting from Platform. Args: ----- query: The element to be searched. Return: ------- A list of elements to be appended.
def do_usufy(self, query, **kwargs): results = [] test = self.check_usufy(query, **kwargs) if test: r = { "type": "i3visio.profile", "value": self.platformName + " - " + query, "attributes": [] } # Ap...
438,388
Method to process and extract the entities of a usufy Args: ----- data: The information from which the info will be extracted. Return: ------- A list of the entities found.
def process_usufy(self, data): mode = "usufy" info = [] try: # v2 verifier = self.modes.get(mode, {}).get("extra_fields", {}) for field in verifier.keys(): regexp = verifier[field] values = re.findall(regexp, data) ...
438,389
Auxiliar function to get the configuration paths depending on the system Args: ----- configFileName: TODO. Returns: -------- A dictionary with the following keys: appPath, appPathDefaults, appPathTransforms, appPathPlugins, appPathPatterns, appPathPatterns.
def getConfigPath(configFileName = None): paths = {} applicationPath = "./" # Returning the path of the configuration folder if sys.platform == 'win32': applicationPath = os.path.expanduser(os.path.join('~\\', 'OSRFramework')) else: applicationPath = os.path.expanduser(os.path....
438,401
Method that recovers the configuration information about each program TODO: Grab the default file from the package data instead of storing it in the main folder. Args: ----- util: Any of the utils that are contained in the framework: domainfy, entify, mailfy, phonefy, searchfy, usu...
def returnListOfConfigurationValues(util): VALUES = {} # If a api_keys.cfg has not been found, creating it by copying from default configPath = os.path.join(getConfigPath()["appPath"], "general.cfg") # Checking if the configuration file exists if not os.path.exists(configPath): # Cop...
438,402
Method to perform the search itself on the different platforms. Args: ----- platforms: List of <Platform> objects. queries: List of queries to be performed. process: Whether to process all the profiles... SLOW! Returns: -------- A list with the entities collected.
def performSearch(platformNames=[], queries=[], process=False, excludePlatformNames=[]): # Grabbing the <Platform> objects platforms = platform_selection.getPlatformsByName(platformNames, mode="searchfy", excludePlatformNames=excludePlatformNames) results = [] for q in queries: for pla in p...
438,404
Method that globally permits to generate the emails to be checked. Args: ----- nicks: List of aliases. nicksFile: The filepath to the aliases file. Returns: -------- list: list of emails to be checked.
def createEmails(nicks=None, nicksFile=None): candidate_emails = set() if nicks != None: for n in nicks: for e in email_providers.domains: candidate_emails.add("{}@{}".format(n, e)) elif nicksFile != None: with open(nicksFile, "r") as iF: nicks = ...
438,413
Verifying a mailfy query in this platform. This might be redefined in any class inheriting from Platform. The only condition is that any of this should return a dictionary as defined. Args: ----- query: The element to be searched. kwargs: Dictionary with extra p...
def check_mailfy(self, query, kwargs={}): import re import requests s = requests.Session() # Getting the first response to grab the csrf_token r1 = s.get("https://www.instagram.com") csrf_token = re.findall("csrf_token", r1.text)[0] # Launching the que...
438,421
Create a set of sequences with given lag and dimension Args: time_series: Vector or string of the sample data lag: Lag between beginning of sequences dim: Dimension (number of patterns) Returns: 2D array of vectors
def util_pattern_space(time_series, lag, dim): n = len(time_series) if lag * dim > n: raise Exception('Result matrix exceeded size limit, try to change lag or dim.') elif lag < 1: raise Exception('Lag should be greater or equal to 1.') pattern_space = np.empty((n - lag * (dim - 1)...
439,229
Extract coarse-grained time series Args: time_series: Time series scale: Scale factor Returns: Vector of coarse-grained time series with given scale factor
def util_granulate_time_series(time_series, scale): n = len(time_series) b = int(np.fix(n / scale)) temp = np.reshape(time_series[0:b*scale], (b, scale)) cts = np.mean(temp, axis = 1) return cts
439,230
Return the Shannon Entropy of the sample data. Args: time_series: Vector or string of the sample data Returns: The Shannon Entropy as float value
def shannon_entropy(time_series): # Check if string if not isinstance(time_series, str): time_series = list(time_series) # Create a frequency data data_set = list(set(time_series)) freq_list = [] for entry in data_set: counter = 0. for i in time_series: ...
439,231
Calculate the Multiscale Entropy of the given time series considering different time-scales of the time series. Args: time_series: Time series for analysis sample_length: Bandwidth or group of points tolerance: Tolerance (default = 0.1*std(time_series)) Returns: Vector cont...
def multiscale_entropy(time_series, sample_length, tolerance = None, maxscale = None): if tolerance is None: #we need to fix the tolerance at this level. If it remains 'None' it will be changed in call to sample_entropy() tolerance = 0.1*np.std(time_series) if maxscale is None: max...
439,233
Calculates the 1's complement sum for 16-bit numbers. Args: num1: 16-bit number. num2: 16-bit number. Returns: The calculated result.
def ones_comp_sum16(num1: int, num2: int) -> int: carry = 1 << 16 result = num1 + num2 return result if result < carry else result + 1 - carry
439,237
Calculates the checksum of the input bytes. RFC1071: https://tools.ietf.org/html/rfc1071 RFC792: https://tools.ietf.org/html/rfc792 Args: source: The input to be calculated. Returns: Calculated checksum.
def checksum(source: bytes) -> int: if len(source) % 2: # if the total length is odd, padding with one octet of zeros for computing the checksum source += b'\x00' sum = 0 for i in range(0, len(source), 2): sum = ones_comp_sum16(sum, (source[i + 1] << 8) + source[i]) return ~sum & 0...
439,238
Send pings to destination address with the given timeout and display the result. Args: dest_addr: The destination address. Ex. "192.168.1.1"/"example.com" count: How many pings should be sent. Default is 4, same as Windows CMD. (default 4) *args and **kwargs: And all the other arguments ava...
def verbose_ping(dest_addr: str, count: int = 4, *args, **kwargs): timeout = kwargs.get("timeout") src = kwargs.get("src") unit = kwargs.setdefault("unit", "ms") for i in range(count): output_text = "ping '{}'".format(dest_addr) output_text += " from '{}'".format(src) if src else ""...
439,242
Export the word frequency list for import in the future Args: filepath (str): The filepath to the exported dictionary encoding (str): The encoding of the resulting output gzipped (bool): Whether to gzip the dictionary or not
def export(self, filepath, encoding="utf-8", gzipped=True): data = json.dumps(self.word_frequency.dictionary, sort_keys=True) write_file(filepath, encoding, gzipped, data)
439,398
Calculate the probability of the `word` being the desired, correct word Args: word (str): The word for which the word probability is \ calculated total_words (int): The total number of words to use in the \ calculation; use the def...
def word_probability(self, word, total_words=None): if total_words is None: total_words = self._word_frequency.total_words return self._word_frequency.dictionary[word] / total_words
439,399
The most probable correct spelling for the word Args: word (str): The word to correct Returns: str: The most likely candidate
def correction(self, word): return max(self.candidates(word), key=self.word_probability)
439,400
Generate possible spelling corrections for the provided word up to an edit distance of two, if and only when needed Args: word (str): The word for which to calculate candidate spellings Returns: set: The set of words that are possible candidates
def candidates(self, word): if self.known([word]): # short-cut if word is correct already return {word} # get edit distance 1... res = [x for x in self.edit_distance_1(word)] tmp = self.known(res) if tmp: return tmp # if still not found, ...
439,401
The subset of `words` that appear in the dictionary of words Args: words (list): List of words to determine which are in the \ corpus Returns: set: The set of those words from the input that are in the \ corpus
def known(self, words): tmp = [w.lower() for w in words] return set( w for w in tmp if w in self._word_frequency.dictionary or not self._check_if_should_check(w) )
439,402
Compute all strings that are one edit away from `word` using only the letters in the corpus Args: word (str): The word for which to calculate the edit distance Returns: set: The set of strings that are edit distance one from the \ prov...
def edit_distance_1(self, word): word = word.lower() if self._check_if_should_check(word) is False: return {word} letters = self._word_frequency.letters splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [L + R[1:] for L, R in splits if R...
439,403
Compute all strings that are two edits away from `word` using only the letters in the corpus Args: word (str): The word for which to calculate the edit distance Returns: set: The set of strings that are edit distance two from the \ pro...
def edit_distance_2(self, word): word = word.lower() return [ e2 for e1 in self.edit_distance_1(word) for e2 in self.edit_distance_1(e1) ]
439,404
Compute all strings that are 1 edits away from all the words using only the letters in the corpus Args: words (list): The words for which to calculate the edit distance Returns: set: The set of strings that are edit distance two from the \ ...
def __edit_distance_alt(self, words): words = [x.lower() for x in words] return [e2 for e1 in words for e2 in self.edit_distance_1(e1)]
439,405
Remove the key and return the associated value or default if not found Args: key (str): The key to remove default (obj): The value to return if key is not present
def pop(self, key, default=None): return self._dictionary.pop(key.lower(), default)
439,408
Load in a pre-built word frequency list Args: filename (str): The filepath to the json (optionally gzipped) \ file to be loaded encoding (str): The encoding of the dictionary
def load_dictionary(self, filename, encoding="utf-8"): with load_file(filename, encoding) as data: self._dictionary.update(json.loads(data.lower(), encoding=encoding)) self._update_dictionary()
439,410
Load in a text file from which to generate a word frequency list Args: filename (str): The filepath to the text file to be loaded encoding (str): The encoding of the text file tokenizer (function): The function to use to tokenize a string
def load_text_file(self, filename, encoding="utf-8", tokenizer=None): with load_file(filename, encoding=encoding) as data: self.load_text(data, tokenizer)
439,411
Load text from which to generate a word frequency list Args: text (str): The text to be loaded tokenizer (function): The function to use to tokenize a string
def load_text(self, text, tokenizer=None): if tokenizer: words = [x.lower() for x in tokenizer(text)] else: words = self.tokenize(text) self._dictionary.update(words) self._update_dictionary()
439,412
Load a list of words from which to generate a word frequency list Args: words (list): The list of words to be loaded
def load_words(self, words): self._dictionary.update([word.lower() for word in words]) self._update_dictionary()
439,413
Remove a list of words from the word frequency list Args: words (list): The list of words to remove
def remove_words(self, words): for word in words: self._dictionary.pop(word.lower()) self._update_dictionary()
439,414
Remove a word from the word frequency list Args: word (str): The word to remove
def remove(self, word): self._dictionary.pop(word.lower()) self._update_dictionary()
439,415
Remove all words at, or below, the provided threshold Args: threshold (int): The threshold at which a word is to be \ removed
def remove_by_threshold(self, threshold=5): keys = [x for x in self._dictionary.keys()] for key in keys: if self._dictionary[key] <= threshold: self._dictionary.pop(key) self._update_dictionary()
439,416
Context manager to handle opening a gzip or text file correctly and reading all the data Args: filename (str): The filename to open encoding (str): The file encoding to use Yields: str: The string data from the file read
def load_file(filename, encoding): try: with gzip.open(filename, mode="rt") as fobj: yield fobj.read() except (OSError, IOError): with OPEN(filename, mode="r", encoding=encoding) as fobj: yield fobj.read()
439,418
Write the data to file either as a gzip file or text based on the gzipped parameter Args: filepath (str): The filename to open encoding (str): The file encoding to use gzipped (bool): Whether the file should be gzipped or not data (str): The data to be wr...
def write_file(filepath, encoding, gzipped, data): if gzipped: with gzip.open(filepath, "wt") as fobj: fobj.write(data) else: with OPEN(filepath, "w", encoding=encoding) as fobj: if sys.version_info < (3, 0): data = data.decode(encoding) f...
439,419
Convert images into the format required by our model. Our model requires that inputs be grayscale (mode 'L'), be resized to `MNIST_DIM`, and be represented as float32 numpy arrays in range [0, 1]. Args: raw_inputs (list of Images): a list of PIL Image objects Retur...
def preprocess(self, raw_inputs): image_arrays = [] for raw_im in raw_inputs: im = raw_im.convert('L') im = im.resize(MNIST_DIM, Image.ANTIALIAS) arr = np.array(im) image_arrays.append(arr) inputs = np.array(image_arrays) return i...
439,427
Create a new instance of this visualization. `BaseVisualization` is an interface and should only be instantiated via a subclass. Args: model (:obj:`.models.model.BaseModel`): NN model to be visualized.
def __init__(self, model): self._model = model # give default settings if self.ALLOWED_SETTINGS: self.update_settings({setting: self.ALLOWED_SETTINGS[setting][0] for setting in self.ALLOWED_SETTINGS})
439,433
Load graph and weight data. Args: data_dir (:obj:`str`): location of Keras checkpoint (`.hdf5`) files and model (in `.json`) structure. The default behavior is to take the latest of each, by OS timestamp.
def load(self, data_dir): # for tensorflow compatibility K.set_learning_phase(0) # find newest ckpt and graph files try: latest_ckpt = max(glob.iglob( os.path.join(data_dir, '*.h*5')), key=os.path.getctime) latest_ckpt_name = os.path.base...
439,442
Get an instance of the described model. Args: model_cls_path: Path to the module in which the model class is defined. model_cls_name: Name of the model class. model_load_args: Dictionary of args to pass to the `load` method of the model instance. Returns: ...
def load_model(model_cls_path, model_cls_name, model_load_args): spec = importlib.util.spec_from_file_location('active_model', model_cls_path) model_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(model_module) model_cls = get...
439,453
Create a new instance of this model. `BaseModel` is an interface and should only be instantiated via a subclass. Args: top_probs (int): Number of classes to display per result. For instance, VGG16 has 1000 classes, we don't want to display a visualiz...
def __init__(self, top_probs=5): self.top_probs = top_probs self._sess = None self._tf_input_var = None self._tf_predict_var = None self._model_name = None self._latest_ckpt_name = None self._latest_ckpt_time = None
439,454
The function for retrieving the information for an ASN from Cymru via port 53 (DNS). This is needed since IP to ASN mapping via Cymru DNS does not return the ASN Description like Cymru Whois does. Args: asn (:obj:`str`): The AS number (required). Returns: str: T...
def get_asn_verbose_dns(self, asn=None): if asn[0:2] != 'AS': asn = 'AS{0}'.format(asn) zone = '{0}.asn.cymru.com'.format(asn) try: log.debug('ASN verbose query for {0}'.format(zone)) data = self.dns_resolver.query(zone, 'TXT') return...
439,739
The function for retrieving ASN information for an IP address from Cymru via port 43/tcp (WHOIS). Args: retry_count (:obj:`int`): The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3. Re...
def get_asn_whois(self, retry_count=3): try: # Create the connection for the Cymru whois query. conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) conn.settimeout(self.timeout) log.debug('ASN query for {0}'.format(self.address_str)) co...
439,740
The function for generating the CLI output header. Args: query_type (:obj:`str`): The IPWhois query type. Defaults to 'RDAP'. Returns: str: The generated output.
def generate_output_header(self, query_type='RDAP'): output = '\n{0}{1}{2} query for {3}:{4}\n\n'.format( ANSI['ul'], ANSI['b'], query_type, self.obj.address_str, ANSI['end'] ) return output
439,753
The function for generating a CLI output new line. Args: line (:obj:`str`): The line number (0-4). Determines indentation. Defaults to '0'. colorize (:obj:`bool`): Colorize the console output with ANSI colors. Defaults to True. Returns: ...
def generate_output_newline(self, line='0', colorize=True): return generate_output( line=line, is_parent=True, colorize=colorize )
439,754
The function for parsing network blocks from jpnic whois data. Args: response (:obj:`str`): The response from the jpnic server. Returns: list of dict: Mapping of networks with start and end positions. :: [{ 'cidr' (str) - The ne...
def get_nets_jpnic(self, response): nets = [] # Iterate through all of the networks found, storing the CIDR value # and the start and end positions. for match in re.finditer( r'^.*?(\[Network Number\])[^\S\n]+.+?>(?P<val>.+?)</A>$', response, ...
439,777
The function for parsing the vcard address. Args: val (:obj:`list`): The value to parse.
def _parse_address(self, val): ret = { 'type': None, 'value': None } try: ret['type'] = val[1]['type'] except (KeyError, ValueError, TypeError): pass try: ret['value'] = val[1]['label'] excep...
439,786
The function for parsing the vcard phone numbers. Args: val (:obj:`list`): The value to parse.
def _parse_phone(self, val): ret = { 'type': None, 'value': None } try: ret['type'] = val[1]['type'] except (IndexError, KeyError, ValueError, TypeError): pass ret['value'] = val[3].strip() try: ...
439,787
The function for parsing the vcard email addresses. Args: val (:obj:`list`): The value to parse.
def _parse_email(self, val): ret = { 'type': None, 'value': None } try: ret['type'] = val[1]['type'] except (KeyError, ValueError, TypeError): pass ret['value'] = val[3].strip() try: self.var...
439,788
The function for summarizing RDAP links in to a unique list. https://tools.ietf.org/html/rfc7483#section-4.2 Args: links_json (:obj:`dict`): A json mapping of links from RDAP results. Returns: list of str: Unique RDAP links.
def summarize_links(self, links_json): ret = [] for link_dict in links_json: ret.append(link_dict['href']) ret = list(unique_everseen(ret)) return ret
439,791
The function to strip leading zeros in each octet of an IPv4 address. Args: address (:obj:`str`): An IPv4 address. Returns: str: The modified IPv4 address.
def ipv4_lstrip_zeros(address): # Split the octets. obj = address.strip().split('.') for x, y in enumerate(obj): # Strip leading zeros. Split / here in case CIDR is attached. obj[x] = y.split('/')[0].lstrip('0') if obj[x] in ['', None]: obj[x] = '0' return '...
439,804
The function to calculate a CIDR range(s) from a start and end IP address. Args: start_address (:obj:`str`): The starting IP address. end_address (:obj:`str`): The ending IP address. Returns: list of str: The calculated CIDR ranges.
def calculate_cidr(start_address, end_address): tmp_addrs = [] try: tmp_addrs.extend(summarize_address_range( ip_address(start_address), ip_address(end_address))) except (KeyError, ValueError, TypeError): # pragma: no cover try: tmp_addrs.exten...
439,805
The function to generate a dictionary containing ISO_3166-1 country codes to names. Args: is_legacy_xml (:obj:`bool`): Whether to use the older country code list (iso_3166-1_list_en.xml). Returns: dict: A mapping of country codes as the keys to the country names as ...
def get_countries(is_legacy_xml=False): # Initialize the countries dictionary. countries = {} # Set the data directory based on if the script is a frozen executable. if sys.platform == 'win32' and getattr(sys, 'frozen', False): data_dir = path.dirname(sys.executable) # pragma: no cover ...
439,806
The function for checking if an IPv4 address is defined (does not need to be resolved). Args: address (:obj:`str`): An IPv4 address. Returns: namedtuple: :is_defined (bool): True if given address is defined, otherwise False :ietf_name (str): IETF assignment nam...
def ipv4_is_defined(address): # Initialize the IP address object. query_ip = IPv4Address(str(address)) # Initialize the results named tuple results = namedtuple('ipv4_is_defined_results', 'is_defined, ietf_name, ' 'ietf_rfc') # This Network...
439,807
The function for checking if an IPv6 address is defined (does not need to be resolved). Args: address (:obj:`str`): An IPv6 address. Returns: namedtuple: :is_defined (bool): True if given address is defined, otherwise False :ietf_name (str): IETF assignment nam...
def ipv6_is_defined(address): # Initialize the IP address object. query_ip = IPv6Address(str(address)) # Initialize the results named tuple results = namedtuple('ipv6_is_defined_results', 'is_defined, ietf_name, ' 'ietf_rfc') # Multicast ...
439,808
The generator to list unique elements, preserving the order. Remember all elements ever seen. This was taken from the itertools recipes. Args: iterable (:obj:`iter`): An iterable to process. key (:obj:`callable`): Optional function to run when checking elements (e.g., str.lower) ...
def unique_everseen(iterable, key=None): seen = set() seen_add = seen.add if key is None: for element in filterfalse(seen.__contains__, iterable): seen_add(element) yield element else: for element in iterable: k = key(element) ...
439,809
The generator to produce random, unique IPv4 addresses that are not defined (can be looked up using ipwhois). Args: total (:obj:`int`): The total number of IPv4 addresses to generate. Yields: str: The next IPv4 address.
def ipv4_generate_random(total=100): count = 0 yielded = set() while count < total: address = str(IPv4Address(random.randint(0, 2**32-1))) if not ipv4_is_defined(address)[0] and address not in yielded: count += 1 yielded.add(address) yield address
439,811
The generator to produce random, unique IPv6 addresses that are not defined (can be looked up using ipwhois). Args: total (:obj:`int`): The total number of IPv6 addresses to generate. Yields: str: The next IPv6 address.
def ipv6_generate_random(total=100): count = 0 yielded = set() while count < total: address = str(IPv6Address(random.randint(0, 2**128-1))) if not ipv6_is_defined(address)[0] and address not in yielded: count += 1 yielded.add(address) yield addres...
439,812
Wrapper function for Bloomberg connection Args: func: function to wrap
def with_bloomberg(func): @wraps(func) def wrapper(*args, **kwargs): scope = utils.func_scope(func=func) param = inspect.signature(func).parameters port = kwargs.pop('port', _PORT_) timeout = kwargs.pop('timeout', _TIMEOUT_) restart = kwargs.pop('restart', False) ...
439,826
Find cached `BDP` / `BDS` queries Args: func: function name - bdp or bds tickers: tickers flds: fields **kwargs: other kwargs Returns: ToQuery(ticker, flds, kwargs)
def bdp_bds_cache(func, tickers, flds, **kwargs) -> ToQuery: cache_data = [] log_level = kwargs.get('log', logs.LOG_LEVEL) logger = logs.get_logger(bdp_bds_cache, level=log_level) kwargs['has_date'] = kwargs.pop('has_date', func == 'bds') kwargs['cache'] = kwargs.get('cache', True) tickers...
439,829
Bloomberg overrides Args: **kwargs: overrides Returns: list of tuples Examples: >>> proc_ovrds(DVD_Start_Dt='20180101') [('DVD_Start_Dt', '20180101')] >>> proc_ovrds(DVD_Start_Dt='20180101', cache=True, has_date=True) [('DVD_Start_Dt', '20180101')]
def proc_ovrds(**kwargs): return [ (k, v) for k, v in kwargs.items() if k not in list(ELEM_KEYS.keys()) + list(ELEM_KEYS.values()) + PRSV_COLS ]
439,834
Logging info for given tickers and fields Args: tickers: tickers flds: fields Returns: str Examples: >>> print(info_qry( ... tickers=['NVDA US Equity'], flds=['Name', 'Security_Name'] ... )) tickers: ['NVDA US Equity'] fields: ['Name', ...
def info_qry(tickers, flds) -> str: full_list = '\n'.join([f'tickers: {tickers[:8]}'] + [ f' {tickers[n:(n + 8)]}' for n in range(8, len(tickers), 8) ]) return f'{full_list}\nfields: {flds}'
439,839
Bloomberg reference data Args: tickers: tickers flds: fields to query **kwargs: bbg overrides Returns: pd.DataFrame Examples: >>> bdp('IQ US Equity', 'Crncy', raw=True) ticker field value 0 IQ US Equity Crncy USD >>> bdp('IQ US...
def bdp(tickers, flds, **kwargs): logger = logs.get_logger(bdp, level=kwargs.pop('log', logs.LOG_LEVEL)) con, _ = create_connection() ovrds = assist.proc_ovrds(**kwargs) logger.info( f'loading reference data from Bloomberg:\n' f'{assist.info_qry(tickers=tickers, flds=flds)}' ) ...
439,840
Bloomberg intraday bar data Args: ticker: ticker name dt: date to download typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK] **kwargs: batch: whether is batch process to download data log: level of logs Returns: pd.DataFrame
def bdib(ticker, dt, typ='TRADE', **kwargs) -> pd.DataFrame: from xbbg.core import missing logger = logs.get_logger(bdib, level=kwargs.pop('log', logs.LOG_LEVEL)) t_1 = pd.Timestamp('today').date() - pd.Timedelta('1D') whole_day = pd.Timestamp(dt).date() < t_1 batch = kwargs.pop('batch', Fals...
439,843
Active futures contract Args: ticker: futures ticker, i.e., ESA Index, Z A Index, CLA Comdty, etc. dt: date Returns: str: ticker name
def active_futures(ticker: str, dt) -> str: t_info = ticker.split() prefix, asset = ' '.join(t_info[:-1]), t_info[-1] info = const.market_info(f'{prefix[:-1]}1 {asset}') f1, f2 = f'{prefix[:-1]}1 {asset}', f'{prefix[:-1]}2 {asset}' fut_2 = fut_ticker(gen_ticker=f2, dt=dt, freq=info['freq']) ...
439,847
Get proper ticker from generic ticker Args: gen_ticker: generic ticker dt: date freq: futures contract frequency log: level of logs Returns: str: exact futures ticker
def fut_ticker(gen_ticker: str, dt, freq: str, log=logs.LOG_LEVEL) -> str: logger = logs.get_logger(fut_ticker, level=log) dt = pd.Timestamp(dt) t_info = gen_ticker.split() asset = t_info[-1] if asset in ['Index', 'Curncy', 'Comdty']: ticker = ' '.join(t_info[:-1]) prefix, idx,...
439,848
Check exchange hours vs local hours Args: tickers: list of tickers tz_exch: exchange timezone tz_loc: local timezone Returns: Local and exchange hours
def check_hours(tickers, tz_exch, tz_loc=DEFAULT_TZ) -> pd.DataFrame: cols = ['Trading_Day_Start_Time_EOD', 'Trading_Day_End_Time_EOD'] con, _ = create_connection() hours = con.ref(tickers=tickers, flds=cols) cur_dt = pd.Timestamp('today').strftime('%Y-%m-%d ') hours.loc[:, 'local'] = hours.val...
439,849
Load assets infomation from file Args: file_name: file name Returns: dict
def _load_yaml_(file_name): if not os.path.exists(file_name): return dict() with open(file_name, 'r', encoding='utf-8') as fp: return YAML().load(stream=fp)
439,864
Convert YAML input to hours Args: num: number in YMAL file, e.g., 900, 1700, etc. Returns: str Examples: >>> to_hour(900) '09:00' >>> to_hour(1700) '17:00'
def to_hour(num) -> str: to_str = str(int(num)) return pd.Timestamp(f'{to_str[:-2]}:{to_str[-2:]}').strftime('%H:%M')
439,865
Absolute path Args: cur_file: __file__ or file or path str parent: level of parent to look for Returns: str
def abspath(cur_file, parent=0) -> str: file_path = os.path.abspath(cur_file).replace('\\', '/') if os.path.isdir(file_path) and parent == 0: return file_path adj = 1 - os.path.isdir(file_path) return '/'.join(file_path.split('/')[:-(parent + adj)])
439,866
Make folder as well as all parent folders if not exists Args: path_name: full path name is_file: whether input is name of file
def create_folder(path_name: str, is_file=False): path_sep = path_name.replace('\\', '/').split('/') for i in range(1, len(path_sep) + (0 if is_file else 1)): cur_path = '/'.join(path_sep[:i]) if not os.path.exists(cur_path): os.mkdir(cur_path)
439,867
Search all files with criteria Returned list will be sorted by last modified Args: path_name: full path name keyword: keyword to search ext: file extensions, split by ',' full_path: whether return full path (default True) has_date: whether has date in file name (default ...
def all_files( path_name, keyword='', ext='', full_path=True, has_date=False, date_fmt=DATE_FMT ) -> list: if not os.path.exists(path=path_name): return [] path_name = path_name.replace('\\', '/') if keyword or ext: keyword = f'*{keyword}*' if keyword else '*' if not ex...
439,868
Search all folders with criteria Returned list will be sorted by last modified Args: path_name: full path name keyword: keyword to search has_date: whether has date in file name (default False) date_fmt: date format to check for has_date parameter Returns: list: all...
def all_folders( path_name, keyword='', has_date=False, date_fmt=DATE_FMT ) -> list: if not os.path.exists(path=path_name): return [] path_name = path_name.replace('\\', '/') if keyword: folders = sort_by_modified([ f.replace('\\', '/') for f in glob.iglob(f'{path_name}/*{k...
439,869
Sort files or folders by modified time Args: files_or_folders: list of files or folders Returns: list
def sort_by_modified(files_or_folders: list) -> list: return sorted(files_or_folders, key=os.path.getmtime, reverse=True)
439,870
Filter files or dates by date patterns Args: files_or_folders: list of files or folders date_fmt: date format Returns: list
def filter_by_dates(files_or_folders: list, date_fmt=DATE_FMT) -> list: r = re.compile(f'.*{date_fmt}.*') return list(filter( lambda vv: r.match(vv.replace('\\', '/').split('/')[-1]) is not None, files_or_folders, ))
439,871
Latest modified file in folder Args: path_name: full path name keyword: keyword to search ext: file extension Returns: str: latest file name
def latest_file(path_name, keyword='', ext='', **kwargs) -> str: files = all_files( path_name=path_name, keyword=keyword, ext=ext, full_path=True ) if not files: from xbbg.io import logs logger = logs.get_logger(latest_file, level=kwargs.pop('log', 'warning')) logger.d...
439,872
File modified time in python Args: file_name: file name Returns: pd.Timestamp
def file_modified_time(file_name) -> pd.Timestamp: return pd.to_datetime(time.ctime(os.path.getmtime(filename=file_name)))
439,873
Shift start time by mins Args: start_time: start time in terms of HH:MM string mins: number of minutes (+ / -) Returns: end time in terms of HH:MM string
def shift_time(start_time, mins) -> str: s_time = pd.Timestamp(start_time) e_time = s_time + np.sign(mins) * pd.Timedelta(f'00:{abs(mins)}:00') return e_time.strftime('%H:%M')
439,875
Time intervals for market open Args: session: [allday, day, am, pm, night] mins: mintues after open Returns: Session of start_time and end_time
def market_open(self, session, mins) -> Session: if session not in self.exch: return SessNA start_time = self.exch[session][0] return Session(start_time, shift_time(start_time, int(mins)))
439,877
Time intervals for market close Args: session: [allday, day, am, pm, night] mins: mintues before close Returns: Session of start_time and end_time
def market_close(self, session, mins) -> Session: if session not in self.exch: return SessNA end_time = self.exch[session][-1] return Session(shift_time(end_time, -int(mins) + 1), end_time)
439,878
Time intervals between market Args: session: [allday, day, am, pm, night] after_open: mins after open before_close: mins before close Returns: Session of start_time and end_time
def market_normal(self, session, after_open, before_close) -> Session: logger = logs.get_logger(self.market_normal) if session not in self.exch: return SessNA ss = self.exch[session] s_time = shift_time(ss[0], int(after_open) + 1) e_time = shift_time(ss[-1], -int(befor...
439,879
Explicitly specify start time and end time Args: session: predefined session start_time: start time in terms of HHMM string end_time: end time in terms of HHMM string Returns: Session of start_time and end_time
def market_exact(self, session, start_time: str, end_time: str) -> Session: if session not in self.exch: return SessNA ss = self.exch[session] same_day = ss[0] < ss[-1] if not start_time: s_time = ss[0] else: s_time = param.to_hour(start_time) i...
439,880
Convert tz from ticker / shorthands to timezone Args: tz: ticker or timezone shorthands Returns: str: Python timzone Examples: >>> get_tz('NY') 'America/New_York' >>> get_tz(TimeZone.NY) 'America/New_York' >>> get_tz('BHP AU Equity') 'Austra...
def get_tz(tz) -> str: from xbbg.const import exch_info if tz is None: return DEFAULT_TZ to_tz = tz if isinstance(tz, str): if hasattr(TimeZone, tz): to_tz = getattr(TimeZone, tz) else: exch = exch_info(ticker=tz) if 'tz' in exch.index: ...
439,881
Check whether the current component list matches all Stim types in the types argument. Args: types (Stim, list): a Stim class or iterable of Stim classes. all_ (bool): if True, all input types must match; if False, at least one input type must match. Ret...
def has_types(self, types, all_=True): func = all if all_ else any return func([self.get_stim(t) for t in listify(types)])
439,950
Save clip data to file. Args: path (str): Filename to save audio data to.
def save(self, path): self.clip.write_audiofile(path, fps=self.sampling_rate)
439,988
Scans the list of available Converters and returns an instantiation of the first one whose input and output types match those passed in. Args: in_type (type): The type of input the converter must have. out_type (type): The type of output the converter must have. args, kwargs: Optional p...
def get_converter(in_type, out_type, *args, **kwargs): convs = pliers.converters.__all__ # If config includes default converters for this combination, try them # first out_type = listify(out_type)[::-1] default_convs = config.get_option('default_converters') for ot in out_type: co...
439,992
Runs inference on an image. Args: image: Image file name. Returns: Nothing
def run_inference_on_image(image): if not tf.gfile.Exists(image): tf.logging.fatal('File does not exist %s', image) image_data = tf.gfile.FastGFile(image, 'rb').read() # Creates graph from saved GraphDef. create_graph() with tf.Session() as sess: # Some useful tensors: # 'softmax:0': A tensor...
440,016
Loads a human readable English name for each softmax node. Args: label_lookup_path: string UID to integer node ID. uid_lookup_path: string UID to human-readable string. Returns: dict from integer node ID to human-readable string.
def load(self, label_lookup_path, uid_lookup_path): if not tf.gfile.Exists(uid_lookup_path): tf.logging.fatal('File does not exist %s', uid_lookup_path) if not tf.gfile.Exists(label_lookup_path): tf.logging.fatal('File does not exist %s', label_lookup_path) # Loads mapping from string UID ...
440,019
Converts a Google API Face JSON response into a Pandas Dataframe. Args: result (ExtractorResult): Result object from which to parse out a Dataframe. handle_annotations (str): How returned face annotations should be handled in cases where there are multipl...
def _to_df(self, result, handle_annotations=None): annotations = result._data if handle_annotations == 'first': annotations = [annotations[0]] face_results = [] for i, annotation in enumerate(annotations): data_dict = {} for field, val in ann...
440,054
Returns a pandas DataFrame with the pair-wise correlations of the columns. Args: df: pandas DataFrame with columns to run diagnostics on
def correlation_matrix(df): columns = df.columns.tolist() corr = pd.DataFrame( np.corrcoef(df, rowvar=0), columns=columns, index=columns) return corr
440,077
Returns a pandas Series with eigenvalues of the correlation matrix. Args: df: pandas DataFrame with columns to run diagnostics on
def eigenvalues(df): corr = np.corrcoef(df, rowvar=0) eigvals = np.linalg.eigvals(corr) return pd.Series(eigvals, df.columns, name='Eigenvalue')
440,078
Returns a pandas Series with condition indices of the df columns. Args: df: pandas DataFrame with columns to run diagnostics on
def condition_indices(df): eigvals = eigenvalues(df) cond_idx = np.sqrt(eigvals.max() / eigvals) return pd.Series(cond_idx, df.columns, name='Condition index')
440,079
Computes the variance inflation factor (VIF) for each column in the df. Returns a pandas Series of VIFs Args: df: pandas DataFrame with columns to run diagnostics on
def variance_inflation_factors(df): corr = np.corrcoef(df, rowvar=0) corr_inv = np.linalg.inv(corr) vifs = np.diagonal(corr_inv) return pd.Series(vifs, df.columns, name='VIF')
440,080
Returns a pandas Series with Mahalanobis distances for each sample on the axis. Note: does not work well when # of observations < # of dimensions Will either return NaN in answer or (in the extreme case) fail with a Singular Matrix LinAlgError Args: df: pandas DataFrame with columns to run...
def mahalanobis_distances(df, axis=0): df = df.transpose() if axis == 1 else df means = df.mean() try: inv_cov = np.linalg.inv(df.cov()) except LinAlgError: return pd.Series([np.NAN] * len(df.index), df.index, name='Mahalanobis') dists = [] for i, sa...
440,081
Displays diagnostics to the user Args: stdout (bool): print results to the console plot (bool): use Seaborn to plot results
def summary(self, stdout=True, plot=False): if stdout: print('Collinearity summary:') print(pd.concat([self.results['Eigenvalues'], self.results['ConditionIndices'], self.results['VIFs'], self...
440,083
Returns indices of diagnostic that satisfy (return True from) the threshold predicate. Will use class-level default threshold if None provided. Args: diagnostic (str): name of the diagnostic thresh (func): threshold function (boolean predicate) to apply to ea...
def flag(self, diagnostic, thresh=None): if thresh is None: thresh = self.defaults[diagnostic] result = self.results[diagnostic] if isinstance(result, pd.DataFrame): if diagnostic == 'CorrelationMatrix': result = result.copy() np....
440,084
Returns indices of (rows, columns) that satisfy flag() on any diagnostic. Uses user-provided thresholds in thresh_dict/ Args: thresh_dict (dict): dictionary of diagnostic->threshold functions include (list): optional sublist of diagnostics to flag exclude (list): opt...
def flag_all(self, thresh_dict=None, include=None, exclude=None): if thresh_dict is None: thresh_dict = {} row_idx = set() col_idx = set() include = self.results if include is None else include include = list( set(include) - set(exclude)) if exclu...
440,085
Executes the Transformer at a specific node. Args: node (str, Node): If a string, the name of the Node in the current Graph. Otherwise the Node instance to execute. stim (str, stim, list): Any valid input to the Transformer stored at the target node.
def run_node(self, node, stim): if isinstance(node, string_types): node = self.nodes[node] result = node.transformer.transform(stim) if node.is_leaf(): return listify(result) stim = result # If result is a generator, the first child will destroy...
440,096
Render a plot of the graph via pygraphviz. Args: filename (str): Path to save the generated image to. color (bool): If True, will color graph nodes based on their type, otherwise will draw a black-and-white graph.
def draw(self, filename, color=True): verify_dependencies(['pgv']) if not hasattr(self, '_results'): raise RuntimeError("Graph cannot be drawn before it is executed. " "Try calling run() first.") g = pgv.AGraph(directed=True) g.node_at...
440,097
Writes the JSON representation of this graph to the provided filename, such that the graph can be easily reconstructed using Graph(spec=filename). Args: filename (str): Path at which to write out the json file.
def save(self, filename): with open(filename, 'w') as outfile: json.dump(self.to_json(), outfile)
440,099