docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Args: main_type: sub_type: unique_id: params: Return:
def escalatees(self, main_type, sub_type, unique_id, params=None): params = params or {} url = '/v2/{}/{}/{}/escalatees'.format(main_type, sub_type, unique_id) for e in self._iterate(url, params, 'escalatee'): yield e
542,394
Args: main_type: sub_type: unique_id: escalatee_id: action: params: Return:
def escalatee(self, main_type, sub_type, unique_id, escalatee_id, action='GET', params=None): params = params or {} url = '/v2/{}/{}/{}/escalatees/{}'.format(main_type, sub_type, unique_id, escalatee_id) if action == 'GET': return self.tcex.session.get(url, params=params) ...
542,395
Args: main_type: sub_type: unique_id: escalatee_id: params: Return:
def get_escalatee(self, main_type, sub_type, unique_id, escalatee_id, params=None): params = params or {} return self.escalatee(main_type, sub_type, unique_id, escalatee_id, params=params)
542,396
Initialize default class values. .. Note:: The method only supports one level of nesting in the provided data. Args: tcex (obj): Instance of TcEx. data (list): List of Dictionary.
def __init__(self, tcex, data): self._data = data # self._filtered_results = () # the filtered results self._indexes = {} self._master_index = {} # bcs - is this needed? self._tcex = tcex # build the indexes self._build_indexes()
542,400
Validate field **IN** string or list. Args: filter_value (string | list): A string or list of values. Returns: (boolean): Results of check
def _in(field, filter_value): valid = False if field in filter_value: valid = True return valid
542,402
Post Filter Args: index_data (dictionary): The indexed data for the provided field. field (string): The field to filter on. filter_value (string | list): The value to match. filter_operator (string): The operator for comparison. field_converter (metho...
def _index_filter(index_data, filter_value, filter_operator, field_converter=None): filtered_data = [] if filter_operator == operator.eq: if field_converter is not None: filter_value = field_converter(filter_value) # for data_obj in index_data: ...
542,403
Validate field **NOT IN** string or list. Args: filter_value (string | list): A string or list of values. Returns: (boolean): Results of validation
def _ni(field, filter_value): valid = False if field not in filter_value: valid = True return valid
542,404
Validate field starts with provided value. Args: filter_value (string): A string or list of values. Returns: (boolean): Results of validation
def _starts_with(field, filter_value): valid = False if field.startswith(filter_value): valid = True return valid
542,405
Filter the data given the provided. Args: field (string): The field to filter on. filter_value (string | list): The value to match. filter_operator (string): The operator for comparison. field_converter (method): A method used to convert the field before comparis...
def filter_data(self, field, filter_value, filter_operator, field_converter=None): data = [] if self._indexes.get(field) is not None: data = self._index_filter( self._indexes.get(field), filter_value, filter_operator, field_converter ) # else: ...
542,406
Initialize Class Properties. Args: group_type (str): The ThreatConnect define Group type. name (str): The name for this Group. xid (str, kwargs): The external id for this Group.
def __init__(self, tcex, name): self._name = name self._tcex = tcex self._type = 'tags' self._api_sub_type = None self._api_type = None self._api_entity = 'tag' self._utils = TcExUtils() self._tc_requests = TiTcRequest(self._tcex)
542,409
Gets all groups from a tag. Args: filters: params: group_type:
def groups(self, group_type=None, filters=None, params=None): group = self._tcex.ti.group(group_type) for g in self.tc_requests.groups_from_tag(group, self.name, filters=filters, params=params): yield g
542,410
Gets all indicators from a tag. Args: params: filters: indicator_type:
def indicators(self, indicator_type=None, filters=None, params=None): indicator = self._tcex.ti.indicator(indicator_type) for i in self.tc_requests.indicators_from_tag( indicator, self.name, filters=filters, params=params ): yield i
542,411
Initialize Class Properties. Args: name (str): The value for this tag. formatter (method, optional): A method that take a tag value and returns a formatted tag.
def __init__(self, name, formatter=None): if formatter is not None: name = formatter(name) self._tag_data = {'name': name} # is tag not null or '' self._valid = True if not name: self._valid = False
542,429
Delete an object from the JSS. In general, it is better to use a higher level interface for deleting objects, namely, using a JSSObject's delete method. Args: url_path: String API endpoint path to DEL, with ID (e.g. "/packages/id/<object ID>") Raises: ...
def delete(self, url_path, data=None): request_url = "%s%s" % (self._url, url_path) if data: response = self.session.delete(request_url, data=data) else: response = self.session.delete(request_url) if response.status_code == 200 and self.verbose: ...
542,436
Get a list of objects as JSSObjectList. Args: obj_class: The JSSObject subclass type to search for. data: None subset: Some objects support a subset for listing; namely Computer, with subset="basic". Returns: JSSObjectList
def get_list(self, obj_class, data, subset): url = obj_class.get_url(data) if obj_class.can_list and obj_class.can_get: if (subset and len(subset) == 1 and subset[0].upper() == "BASIC") and obj_class is jssobjects.Computer: url += "/subset/basic" ...
542,455
Loop over entering input until it is a valid bool-ish response. Args: prompt: Text presented to user. Returns: The bool value equivalent of what was entered.
def loop_until_valid_response(prompt): responses = {"Y": True, "YES": True, "TRUE": True, "N": False, "NO": False, "FALSE": False} response = "" while response.upper() not in responses: response = raw_input(prompt) return responses[response.upper()]
542,460
Indent an xml element object to prepare for pretty printing. To avoid changing the contents of the original Element, it is recommended that a copy is made to send to this function. Args: elem: Element to indent. level: Int indent level (default is 0) more_sibs: Bool, whether to ant...
def indent_xml(elem, level=0, more_sibs=False): i = "\n" pad = " " if level: i += (level - 1) * pad num_kids = len(elem) if num_kids: if not elem.text or not elem.text.strip(): elem.text = i + pad if level: elem.text += pad coun...
542,461
Return a list of all JSSListData elements as full JSSObjects. This can take a long time given a large number of objects, and depending on the size of each object. Subsetting to only include the data you need can improve performance. Args: subset: For objects which support i...
def retrieve_all(self, subset=None): # Attempt to speed this procedure up as much as can be done. get_object = self.factory.get_object obj_class = self.obj_class full_objects = [get_object(obj_class, list_obj.id, subset) for list_obj in self] re...
542,470
Initialize a new JSSObject Args: jss: JSS object. data: xml.etree.ElementTree.Element data to use for creating the object OR a string name to use for creating a new object (provided it has an implemented _new() method.
def __init__(self, jss, data, **kwargs): self.jss = jss if isinstance(data, basestring): super(JSSObject, self).__init__(tag=self.list_type) self._new(data, **kwargs) elif isinstance(data, ElementTree.Element): super(JSSObject, self).__init__(tag=data...
542,477
Return an element located at location with flexible args. Args: location: String xpath to use in an Element.find search OR an Element (which is simply returned). Returns: The found Element. Raises: ValueError if the location is a string that...
def _handle_location(self, location): if not isinstance(location, ElementTree.Element): element = self.find(location) if element is None: raise ValueError("Invalid path!") else: element = location return element
542,484
Set a boolean value. Casper booleans in XML are string literals of "true" or "false". This method sets the text value of "location" to the correct string representation of a boolean. Args: location: Element or a string path argument to find() value: Boolean or s...
def set_bool(self, location, value): element = self._handle_location(location) if isinstance(value, basestring): value = True if value.upper() == "TRUE" else False elif not isinstance(value, bool): raise ValueError if value is True: element.te...
542,485
Remove an object from a list element. Args: obj: Accepts JSSObjects, id's, and names list_element: Accepts an Element or a string path to that element
def remove_object_from_list(self, obj, list_element): list_element = self._handle_location(list_element) if isinstance(obj, JSSObject): results = [item for item in list_element.getchildren() if item.findtext("id") == obj.id] elif isinstance(obj, (int,...
542,487
Create a new JSSObject from an external XML file. Args: jss: A JSS object. filename: String path to an XML file.
def from_file(cls, jss, filename): tree = ElementTree.parse(filename) root = tree.getroot() return cls(jss, root)
542,488
Creates a new JSSObject from an UTF-8 XML string. Args: jss: A JSS object. xml_string: String XML file data used to create object.
def from_string(cls, jss, xml_string): root = ElementTree.fromstring(xml_string.encode('utf-8')) return cls(jss, root)
542,489
Write object XML to path. Args: path: String file path to the file you wish to (over)write. Path will have ~ expanded prior to opening.
def to_file(self, path): with open(os.path.expanduser(path), "w") as ofile: ofile.write(self.__repr__())
542,490
Set group is_smart property to value. Args: value: Boolean.
def is_smart(self, value): self.set_bool("is_smart", value) if value is True: if self.find("criteria") is None: # pylint: disable=attribute-defined-outside-init self.criteria = ElementTree.SubElement(self, "criteria")
542,493
Add a device to a group. Wraps JSSObject.add_object_to_path. Args: device: A JSSObject to add (as list data), to this object. location: Element or a string path argument to find()
def add_device(self, device, container): # There is a size tag which the JSS manages for us, so we can # ignore it. if self.findtext("is_smart") == "false": self.add_object_to_path(device, container) else: # Technically this isn't true. It will strangely ...
542,494
Return bool whether group has a device as a member. Args: device_object (Computer or MobileDevice). Membership is determined by ID, as names can be shared amongst devices.
def has_member(self, device_object): if device_object.tag == "computer": container_search = "computers/computer" elif device_object.tag == "mobile_device": container_search = "mobile_devices/mobile_device" else: raise ValueError return len([d...
542,495
Copy a pkg, dmg, or zip to all repositories. Args: filename: String path to the local file to copy. id_: Integer ID you wish to associate package with for a JDS or CDP only. Default is -1, which is used for creating a new package object in the database.
def copy_pkg(self, filename, id_=-1): for repo in self._children: repo.copy_pkg(filename, id_)
542,500
Copy a script to all repositories. Takes into account whether a JSS has been migrated. See the individual DistributionPoint types for more information. Args: filename: String path to the local file to copy. id_: Integer ID you wish to associate script with for a JDS ...
def copy_script(self, filename, id_=-1): for repo in self._children: repo.copy_script(filename, id_)
542,501
Delete a file from all repositories which support it. Individual repositories will determine correct location to delete from (Scripts vs. Packages). This will not remove the corresponding Package or Script object from the JSS's database! Args: filename: The filenam...
def delete(self, filename): for repo in self._children: if hasattr(repo, "delete"): repo.delete(filename)
542,502
Report whether a file exists on all distribution points. Determines file type by extension. Args: filename: Filename you wish to check. (No path! e.g.: "AdobeFlashPlayer-14.0.0.176.pkg") Returns: Boolean
def exists(self, filename): result = True for repo in self._children: if not repo.exists(filename): result = False return result
542,504
Initialize a Casper object. Args: jss: A JSS object to request the casper page from.
def __init__(self, jss): self.jss = jss self.url = "%s/casper.jxml" % self.jss.base_url self.auth = urllib.urlencode({"username": self.jss.user, "password": self.jss.password}) super(Casper, self).__init__(tag="Casper") self.update()
542,513
Mounts a share at /Volumes Args: share_path: String URL with all auth info to connect to file share. Returns: The mount point or raises an error.
def mount_share(share_path): sh_url = CFURLCreateWithString(None, share_path, None) # Set UI to reduced interaction open_options = {NetFS.kNAUIOptionKey: NetFS.kNAUIOptionNoUI} # Allow mounting sub-directories of root shares mount_options = {NetFS.kNetFSAllowSubMountsKey: True} # Build our ...
542,515
Mounts a share at the specified path Args: share_path: String URL with all auth info to connect to file share. mount_path: Path to mount share on. Returns: The mount point or raises an error
def mount_share_at_path(share_path, mount_path): sh_url = CFURLCreateWithString(None, share_path, None) mo_url = CFURLCreateWithString(None, mount_path, None) # Set UI to reduced interaction open_options = {NetFS.kNAUIOptionKey: NetFS.kNAUIOptionNoUI} # Allow mounting sub-directories of root sh...
542,516
Copy a package to the repo's Package subdirectory. Args: filename: Path for file to copy. _: Ignored. Used for compatibility with JDS repos.
def copy_pkg(self, filename, _): basename = os.path.basename(filename) self._copy(filename, os.path.join(self.connection["mount_point"], "Packages", basename))
542,520
Copy a script to the repo's Script subdirectory. Scripts are copied as files to a path, or, on a "migrated" JSS, are POSTed to the JSS (pass an id if you wish to associate the script with an existing Script object). Args: filename: Path for file to copy. id_: In...
def copy_script(self, filename, id_=-1): if ("jss" in self.connection.keys() and self.connection["jss"].jss_migrated): self._copy_script_migrated(filename, id_, SCRIPT_FILE_TYPE) else: basename = os.path.basename(filename) self._copy(filename,...
542,521
Upload a script to a migrated JSS's database. On a "migrated" JSS, scripts are POSTed to the JSS. Pass an id if you wish to associate the script with an existing Script object, otherwise, it will create a new Script object. Args: filename: Path to script file. i...
def _copy_script_migrated(self, filename, id_=-1, file_type=SCRIPT_FILE_TYPE): basefname = os.path.basename(filename) resource = open(filename, "rb") headers = {"DESTINATION": "1", "OBJECT_ID": str(id_), "FILE_TYPE": file_type, "FILE_NAM...
542,522
Copy a file or folder to the repository. Will mount if needed. Args: filename: Path to copy. destination: Remote path to copy file to.
def _copy(self, filename, destination): # pylint: disable=no-self-use full_filename = os.path.abspath(os.path.expanduser(filename)) if os.path.isdir(full_filename): shutil.copytree(full_filename, destination) elif os.path.isfile(full_filename): shutil.copyfile...
542,523
Delete a file from the repository. This method will not delete a script from a migrated JSS. Please remove migrated scripts with jss.Script.delete. Args: filename: String filename only (i.e. no path) of file to delete. Will handle deleting scripts vs. packages ...
def delete(self, filename): folder = "Packages" if is_package(filename) else "Scripts" path = os.path.join(self.connection["mount_point"], folder, filename) if os.path.isdir(path): shutil.rmtree(path) elif os.path.isfile(path): os.remove(path)
542,524
Report whether a file exists on the distribution point. Determines file type by extension. Args: filename: Filename you wish to check. (No path! e.g.: "AdobeFlashPlayer-14.0.0.176.pkg")
def exists(self, filename): if is_package(filename): filepath = os.path.join(self.connection["mount_point"], "Packages", filename) else: filepath = os.path.join(self.connection["mount_point"], "Scrip...
542,525
Try to unmount our mount point. Defaults to using forced method. If OS is Linux, it will not delete the mount point. Args: forced: Bool whether to force the unmount. Default is True.
def umount(self, forced=True): if self.is_mounted(): if is_osx(): cmd = ["/usr/sbin/diskutil", "unmount", self.connection["mount_point"]] if forced: cmd.insert(2, "force") subprocess.check_call(cmd) ...
542,528
Copy a file or folder to the repository. Will mount if needed. Args: filename: Path to copy. destination: Remote path to copy file to.
def _copy(self, filename, destination): super(MountedRepository, self)._copy(filename, destination)
542,531
Set up a connection to a distribution server. Args: connection_args: Dict, with required key: jss: A JSS Object.
def __init__(self, **connection_args): super(DistributionServer, self).__init__(**connection_args) self.connection["url"] = self.connection["jss"].base_url
542,538
Copy a package to the distribution server. Bundle-style packages must be zipped prior to copying. Args: filename: Full path to file to upload. id_: ID of Package object to associate with, or -1 for new packages (default).
def copy_pkg(self, filename, id_=-1): self._copy(filename, id_=id_, file_type=PKG_FILE_TYPE)
542,540
Copy a script to the distribution server. Args: filename: Full path to file to upload. id_: ID of Script object to associate with, or -1 for new Script (default).
def copy_script(self, filename, id_=-1): self._copy(filename, id_=id_, file_type=SCRIPT_FILE_TYPE)
542,541
Delete a pkg from the distribution server. Args: pkg: Can be a jss.Package object, an int ID of a package, or a filename.
def delete_with_casper_admin_save(self, pkg): # The POST needs the package ID. if pkg.__class__.__name__ == "Package": package_to_delete = pkg.id elif isinstance(pkg, int): package_to_delete = pkg elif isinstance(pkg, str): package_to_delete =...
542,543
Delete a package or script from the distribution server. This method simply finds the Package or Script object from the database with the API GET call and then deletes it. This will remove the file from the database blob. For setups which have file share distribution points, you will ...
def delete(self, filename): if is_package(filename): self.connection["jss"].Package(filename).delete() else: self.connection["jss"].Script(filename).delete()
542,544
Search for LDAP users. Args: user: User to search for. It is not entirely clear how the JSS determines the results- are regexes allowed, or globbing? Returns: LDAPUsersResult object. Raises: Will raise a JSSGetError if no res...
def search_users(self, user): user_url = "%s/%s/%s" % (self.url, "user", user) response = self.jss.get(user_url) return LDAPUsersResults(self.jss, response)
542,553
Search for LDAP groups. Args: group: Group to search for. It is not entirely clear how the JSS determines the results- are regexes allowed, or globbing? Returns: LDAPGroupsResult object. Raises: JSSGetError if no results are ...
def search_groups(self, group): group_url = "%s/%s/%s" % (self.url, "group", group) response = self.jss.get(group_url) return LDAPGroupsResults(self.jss, response)
542,554
Test for whether a user is in a group. There is also the ability in the API to test for whether multiple users are members of an LDAP group, but you should just call is_user_in_group over an enumerated list of users. Args: user: String username. group: String gr...
def is_user_in_group(self, user, group): search_url = "%s/%s/%s/%s/%s" % (self.url, "group", group, "user", user) response = self.jss.get(search_url) # Sanity check length = len(response) result = False if length == 1: ...
542,555
Set package category Args: category: String of an existing category's name, or a Category object.
def set_category(self, category): # For some reason, packages only have the category name, not the # ID. if isinstance(category, Category): name = category.name else: name = category self.find("category").text = name
542,560
Add an object to the appropriate scope block. Args: obj: JSSObject to add to scope. Accepted subclasses are: Computer ComputerGroup Building Department Raises: TypeError if invalid obj type is provided.
def add_object_to_scope(self, obj): if isinstance(obj, Computer): self.add_object_to_path(obj, "scope/computers") elif isinstance(obj, ComputerGroup): self.add_object_to_path(obj, "scope/computer_groups") elif isinstance(obj, Building): self.add_objec...
542,562
Add a Package object to the policy with action=install. Args: pkg: A Package object to add. action_type (str, optional): One of "Install", "Cache", or "Install Cached". Defaults to "Install".
def add_package(self, pkg, action_type="Install"): if isinstance(pkg, Package): if action_type not in ("Install", "Cache", "Install Cached"): raise ValueError package = self.add_object_to_path( pkg, "package_configuration/packages") # ...
542,563
Set the policy's category. Args: category: A category object.
def set_category(self, category): pcategory = self.find("general/category") pcategory.clear() name = ElementTree.SubElement(pcategory, "name") if isinstance(category, Category): id_ = ElementTree.SubElement(pcategory, "id") id_.text = category.id ...
542,564
Verify that the OCSP response is trusted. Args: verify_locations: The file path to a trust store containing pem-formatted certificates, to be used for validating the OCSP response. Raises OcspResponseNotTrustedError if the validation failed ie. the OCSP response is not trusted.
def verify(self, verify_locations: str) -> None: # Ensure the file exists with open(verify_locations): pass try: self._ocsp_response.basic_verify(verify_locations) except _nassl.OpenSSLError as e: if 'certificate verify error' in str(e): ...
542,573
Recursively inspect all files under a directory and return the most recent Args: path (str): the path of the directory to traverse startswith (str): the file name start with (optional) endswith (str): the file name ends with (optional) Returns: the most r...
def most_recent(path, startswith=None, endswith=None): candidate_files = [] for filename in all_files_in_directory(path): if startswith and not os.path.basename(filename).startswith(startswith): continue if endswith and not filename.endswith(endswith): continue ...
543,688
Convert the dataframe to a matrix (numpy ndarray) Args: input_df (dataframe): The dataframe to convert normalize (bool): Boolean flag to normalize numeric columns (default=True)
def fit_transform(self, input_df, normalize=True): # Shallow copy the dataframe (we'll be making changes to some columns) _df = input_df.copy(deep=False) # Set class variables that will be used both now and later for transform self.normalize = normalize # Convert colum...
543,693
Convert the dataframe to a matrix (numpy ndarray) Args: input_df (dataframe): The dataframe to convert
def transform(self, input_df): # Shallow copy the dataframe (we'll be making changes to some columns) _df = input_df.copy(deep=False) # Convert all columns that are/should be categorical for column in self.cat_columns: # Sanity check if column not in _...
543,694
Run a heuristic on the columns of the dataframe to determine whether it contains categorical values if the heuristic decides it's categorical then the type of the column is changed Args: df (dataframe): The dataframe to check for categorical data
def convert_to_categorical(df): might_be_categorical = df.select_dtypes(include=[object]).columns.tolist() for column in might_be_categorical: if df[column].nunique() < 20: # Convert the column print('Changing column {:s} to category...'.format(colum...
543,695
write_to_parquet: Converts a Pandas DataFrame into a Parquet file Args: df (pandas dataframe): The Pandas Dataframe to be saved as parquet file filename (string): The full path to the filename for the Parquet file
def df_to_parquet(df, filename, compression='SNAPPY'): # Right now there are two open Parquet issues # Timestamps in Spark: https://issues.apache.org/jira/browse/ARROW-1499 # TimeDelta Support: https://issues.apache.org/jira/browse/ARROW-835 for column in df.columns: if(df[column].dtype ==...
543,697
parquet_to_df: Reads a Parquet file into a Pandas DataFrame Args: filename (string): The full path to the filename for the Parquet file ntreads (int): The number of threads to use (defaults to 1)
def parquet_to_df(filename, use_threads=1): try: return pq.read_table(filename, use_threads=use_threads).to_pandas() except pa.lib.ArrowIOError: print('Could not read parquet file {:s}'.format(filename)) return None
543,698
Initialization for the LiveSimulator Class Args: eps (int): Events Per Second that the simulator will emit events (default = 10) max_rows (int): The maximum number of rows to generate (default = None (go forever))
def __init__(self, filepath, eps=10, max_rows=None): # Compute EPS timer # Logic: # - Normal distribution centered around 1.0/eps # - Make sure never less than 0 # - Precompute 1000 deltas and then just cycle around self.eps_timer = itertools.cycle([...
543,701
Convert a readable string to a MAC address Args: mac_string (str): a readable string (e.g. '01:02:03:04:05:06') Returns: str: a MAC address in hex form
def str_to_mac(mac_string): sp = mac_string.split(':') mac_string = ''.join(sp) return binascii.unhexlify(mac_string)
543,709
Convert inet object to a string Args: inet (inet struct): inet network address Returns: str: Printable/readable IP address
def inet_to_str(inet): # First try ipv4 and then ipv6 try: return socket.inet_ntop(socket.AF_INET, inet) except ValueError: return socket.inet_ntop(socket.AF_INET6, inet)
543,710
Convert an a string IP address to a inet struct Args: address (str): String representation of address Returns: inet: Inet network address
def str_to_inet(address): # First try ipv4 and then ipv6 try: return socket.inet_pton(socket.AF_INET, address) except socket.error: return socket.inet_pton(socket.AF_INET6, address)
543,711
Contingency Table (also called Cross Tabulation) - Table in a matrix format that displays the (multivariate) frequency distribution of the variables - http://en.wikipedia.org/wiki/Contingency_table Args: rownames: the column name or list of columns names that make the keys of the rows ...
def contingency_table(dataframe, rownames, colnames, margins=True): # Taking just the rownames + colnames of the dataframe sub_set = [rownames, colnames] _sub_df = dataframe[sub_set] return _sub_df.pivot_table(index=rownames, columns=colnames, margins=margins, aggfunc=len, fill_value=0)
543,716
Joint Distribution Table - The Continguency Table normalized by the total number of observations Args: rownames: the column name or list of columns names that make the keys of the rows colnames: the column name or list of columns names that make the keys of the columns
def joint_distribution(dataframe, rownames, colnames): cont_table = contingency_table(dataframe, rownames=rownames, colnames=colnames, margins=True) total_observations = cont_table['All']['All'] return cont_table/total_observations
543,717
Expected counts of the multivariate frequency distribution of the variables given the null hypothesis of complete independence between variables. Args: rownames: the column name or list of columns names that make the keys of the rows colnames: the column name or list of columns names...
def expected_counts(dataframe, rownames, colnames): cont_table = contingency_table(dataframe, rownames=rownames, colnames=colnames, margins=True) row_counts = cont_table['All'] column_counts = cont_table.loc['All'] total_observations = cont_table['All']['All'] # There didn't seem to be a good ...
543,718
Compute NGrams in the word_list from [S-T) Args: word_list (list): A list of words to compute ngram set from S (int): The smallest NGram (default=3) T (int): The biggest NGram (default=3)
def compute_ngrams(word_list, S=3, T=3): _ngrams = [] if isinstance(word_list, str): word_list = [word_list] for word in word_list: for n in range(S, T+1): _ngrams += zip(*(word[i:] for i in range(n))) return [''.join(_ngram) for _ngram in _ngrams]
543,731
Add an item to the cache Args: key: item key value: the value associated with this key
def set(self, key, value): self._check_limit() _expire = time.time() + self._timeout if self._timeout else None self._store[key] = (value, _expire)
543,735
Get an item from the cache Args: key: item key Returns: the value of the item or None if the item isn't in the cache
def get(self, key): data = self._store.get(key) if not data: return None value, expire = data if expire and time.time() > expire: del self._store[key] return None return value
543,736
Generate a numeric column with random data Args: min_value (float): Minimum value (default = 0) max_value (float): Maximum value (default = 1) num_rows (int): The number of rows to generate (default = 100)
def df_numeric_column(min_value=0, max_value=1, num_rows=100): # Generate numeric column return pd.Series(np.random.uniform(min_value, max_value, num_rows))
543,741
Generate a categorical column with random data Args: category_values (list): A list of category values (e.g. ['red', 'blue', 'green']) num_rows (int): The number of rows to generate (default = 100) probabilities (list): A list of probabilities of each value (e.g. [0.6, 0.2, ...
def df_categorical_column(category_values, num_rows=100, probabilities=None): splitter = np.random.choice(range(len(category_values)), num_rows, p=probabilities) return pd.Series(pd.Categorical.from_codes(splitter, categories=category_values))
543,742
Query the VirusTotal Service Args: file_sha (str): The file sha1 or sha256 hash url (str): The domain/url to be queried (default=None)
def query_file(self, file_sha, verbose=False): # Sanity check sha hash input if len(file_sha) not in [64, 40]: # sha256 and sha1 lengths print('File sha looks malformed: {:s}'.format(file_sha)) return {'file_sha': file_sha, 'malformed': True} # Call and return...
543,747
Internal query method for the VirusTotal Service Args: query_type(str): The type of query (either 'file' or 'url') query_str (str): The file hash or domain/url to be queried
def _query(self, query_type, query_str, verbose=False): # First check query cache cached = self.query_cache.get(query_str) if cached: if verbose: print('Returning Cached VT Query Results') return cached # Not in cache so make the actual q...
543,748
Initialize ScriptWorkerTaskException. Args: *args: These are passed on via super(). exit_code (int, optional): The exit_code we should exit with when this exception is raised. Defaults to 1 (failure). **kwargs: These are passed on via super().
def __init__(self, *args, exit_code=1, **kwargs): self.exit_code = exit_code super(ScriptWorkerTaskException, self).__init__(*args, **kwargs)
543,759
Initialize Download404. Args: msg (string): the error message
def __init__(self, msg): super(BaseDownloadError, self).__init__( msg, exit_code=STATUSES['resource-unavailable'] )
543,760
Initialize CoTError. Args: msg (string): the error message
def __init__(self, msg): super(CoTError, self).__init__( msg, exit_code=STATUSES['malformed-payload'] )
543,761
Create a taskcluster queue. Args: credentials (dict): taskcluster credentials.
def create_queue(self, credentials): if credentials: session = self.session or aiohttp.ClientSession(loop=self.event_loop) return Queue( options={ 'credentials': credentials, 'rootUrl': self.config['taskcluster_root_url'], ...
543,764
Write json to disk. Args: path (str): the path to write to contents (dict): the contents of the json blob message (str): the message to log
def write_json(self, path, contents, message): log.debug(message.format(path=path)) makedirs(os.path.dirname(path)) with open(path, "w") as fh: json.dump(contents, fh, indent=2, sort_keys=True)
543,767
Download the ``projects.yml`` file and populate ``self.projects``. This only sets it once, unless ``force`` is set. Args: force (bool, optional): Re-run the download, even if ``self.projects`` is already defined. Defaults to False.
async def populate_projects(self, force=False): if force or not self.projects: with tempfile.TemporaryDirectory() as tmpdirname: self.projects = await load_json_or_yaml_from_url( self, self.config['project_configuration_url'], os.path....
543,769
Run the task logic. Returns the integer status of the task. args: context (scriptworker.context.Context): the scriptworker context. run_cancellable (typing.Callable): wraps future such that it'll cancel upon worker shutdown to_cancellable_process (typing.Callable): wraps ``TaskProcess`...
async def do_run_task(context, run_cancellable, to_cancellable_process): status = 0 try: if context.config['verify_chain_of_trust']: chain = ChainOfTrust(context, context.config['cot_job_type']) await run_cancellable(verify_chain_of_trust(chain)) status = await run_t...
543,770
Upload artifacts and return status. Returns the integer status of the upload. args: context (scriptworker.context.Context): the scriptworker context. files (list of str): list of files to be uploaded as artifacts Raises: Exception: on unexpected exception. Returns: in...
async def do_upload(context, files): status = 0 try: await upload_artifacts(context, files) except ScriptWorkerException as e: status = worst_level(status, e.exit_code) log.error("Hit ScriptWorkerException: {}".format(e)) except aiohttp.ClientError as e: status = wor...
543,771
Run any tasks returned by claimWork. Returns the integer status of the task that was run, or None if no task was run. args: context (scriptworker.context.Context): the scriptworker context. Raises: Exception: on unexpected exception. Returns: int: exit status None...
async def run_tasks(context): running_tasks = RunTasks() context.running_tasks = running_tasks status = await running_tasks.invoke(context) context.running_tasks = None return status
543,772
Set up and run tasks for this iteration. http://docs.taskcluster.net/queue/worker-interaction/ Args: context (scriptworker.context.Context): the scriptworker context.
async def async_main(context, credentials): conn = aiohttp.TCPConnector(limit=context.config['aiohttp_max_connections']) async with aiohttp.ClientSession(connector=conn) as session: context.session = session context.credentials = credentials await run_tasks(context)
543,773
Scriptworker entry point: get everything set up, then enter the main loop. Args: event_loop (asyncio.BaseEventLoop, optional): the event loop to use. If None, use ``asyncio.get_event_loop()``. Defaults to None.
def main(event_loop=None): context, credentials = get_context_from_cmdln(sys.argv[1:]) log.info("Scriptworker starting up at {} UTC".format(arrow.utcnow().format())) cleanup(context) context.event_loop = event_loop or asyncio.get_event_loop() done = False async def _handle_sigterm(): ...
543,774
Claims and processes Taskcluster work. Args: context (scriptworker.context.Context): context of worker Returns: status code of build
async def invoke(self, context): try: # Note: claim_work(...) might not be safely interruptible! See # https://bugzilla.mozilla.org/show_bug.cgi?id=1524069 tasks = await self._run_cancellable(claim_work(context)) if not tasks or not tasks.get('tasks', [])...
543,775
Retry the ``request`` function. Args: *args: the args to send to request() through retry_async(). retry_exceptions (list, optional): the exceptions to retry on. Defaults to (ScriptWorkerRetryException, ). retry_async_kwargs (dict, optional): the kwargs for retry_async. ...
async def retry_request(*args, retry_exceptions=(asyncio.TimeoutError, ScriptWorkerRetryException), retry_async_kwargs=None, **kwargs): retry_async_kwargs = retry_async_kwargs or {} return await retry_async(request, retry_exceptions=r...
543,780
Equivalent to mkdir -p. Args: path (str): the path to mkdir -p Raises: ScriptWorkerException: if path exists already and the realpath is not a dir.
def makedirs(path): if path: if not os.path.exists(path): log.debug("makedirs({})".format(path)) os.makedirs(path) else: realpath = os.path.realpath(path) if not os.path.isdir(realpath): raise ScriptWorkerException( ...
543,781
Equivalent to rm -rf. Make sure ``path`` doesn't exist after this call. If it's a dir, shutil.rmtree(); if it's a file, os.remove(); if it doesn't exist, ignore. Args: path (str): the path to nuke.
def rm(path): if path and os.path.exists(path): if os.path.isdir(path): shutil.rmtree(path) else: os.remove(path)
543,782
Clean up the work_dir and artifact_dir between task runs, then recreate. Args: context (scriptworker.context.Context): the scriptworker context.
def cleanup(context): for name in 'work_dir', 'artifact_dir', 'task_log_dir': path = context.config[name] if os.path.exists(path): log.debug("rm({})".format(path)) rm(path) makedirs(path)
543,783
Find all files in a directory, and return the relative paths to those files. Args: path (str): the directory path to walk Returns: list: the list of relative paths to all files inside of ``path`` or its subdirectories.
def filepaths_in_dir(path): filepaths = [] for root, directories, filenames in os.walk(path): for filename in filenames: filepath = os.path.join(root, filename) filepath = filepath.replace(path, '').lstrip('/') filepaths.append(filepath) return filepaths
543,788
Get the hash of the file at ``path``. I'd love to make this async, but evidently file i/o is always ready Args: path (str): the path to the file to hash. hash_alg (str, optional): the algorithm to use. Defaults to 'sha256'. Returns: str: the hexdigest of the hash.
def get_hash(path, hash_alg="sha256"): h = hashlib.new(hash_alg) with open(path, "rb") as f: for chunk in iter(functools.partial(f.read, 4096), b''): h.update(chunk) return h.hexdigest()
543,789
Download a file, async. Args: context (scriptworker.context.Context): the scriptworker context. url (str): the url to download abs_filename (str): the path to download to session (aiohttp.ClientSession, optional): the session to use. If None, use context.session. Defau...
async def download_file(context, url, abs_filename, session=None, chunk_size=128): session = session or context.session loggable_url = get_loggable_url(url) log.info("Downloading %s", loggable_url) parent_dir = os.path.dirname(abs_filename) async with session.get(url) as resp: if resp.s...
543,794
Strip out secrets from taskcluster urls. Args: url (str): the url to strip Returns: str: the loggable url
def get_loggable_url(url): loggable_url = url or "" for secret_string in ("bewit=", "AWSAccessKeyId=", "access_token="): parts = loggable_url.split(secret_string) loggable_url = parts[0] if loggable_url != url: loggable_url = "{}<snip>".format(loggable_url) return loggable_u...
543,795
Given a url, take out the path part and split it by '/'. Args: url (str): the url slice returns list: parts after the domain name of the URL
def get_parts_of_url_path(url): parsed = urlparse(url) path = unquote(parsed.path).lstrip('/') parts = path.split('/') return parts
543,796
Retry a json/yaml file download, load it, then return its data. Args: context (scriptworker.context.Context): the scriptworker context. url (str): the url to download path (str): the path to download to overwrite (bool, optional): if False and path exists, don't download. ...
async def load_json_or_yaml_from_url(context, url, path, overwrite=True): if path.endswith("json"): file_type = 'json' else: file_type = 'yaml' if not overwrite or not os.path.exists(path): await retry_async( download_file, args=(context, url, path), retr...
543,797
Recursively remove key/value pairs where the value is in ``remove``. This is targeted at comparing json-e rebuilt task definitions, since json-e drops key/value pairs with empty values. Args: values (dict/list): the dict or list to remove empty keys from. Returns: values (dict/list): ...
def remove_empty_keys(values, remove=({}, None, [], 'null')): if isinstance(values, dict): return {key: remove_empty_keys(value, remove=remove) for key, value in deepcopy(values).items() if value not in remove} if isinstance(values, list): return [remove_empty_keys(value, re...
543,800
Read the task.json from work_dir. Args: config (dict): the running config, to find work_dir. Returns: dict: the contents of task.json Raises: ScriptWorkerTaskException: on error.
def get_task(config): path = os.path.join(config['work_dir'], "task.json") message = "Can't read task from {}!\n%(exc)s".format(path) contents = load_json_or_yaml(path, is_path=True, message=message) return contents
543,802