code
stringlengths
1
18.2k
def isUTF8Strict(data): # pragma: no cover - Only used when cchardet is missing. ''' Check if all characters in a bytearray are decodable using UTF-8. ''' try: decoded = data.decode('UTF-8') except UnicodeDecodeError: return False else: for ch in decoded: if 0xD800 <= ord(ch) <= 0xDFFF: return False return True
def decode_headers(header_list): ''' Decode a list of headers. Takes a list of bytestrings, returns a list of unicode strings. The character set for each bytestring is individually decoded. ''' decoded_headers = [] for header in header_list: if cchardet: inferred = cchardet.detect(header) if inferred and inferred['conf...
def parse_headers(fp, _class=http.client.HTTPMessage): """Parses only RFC2822 headers from a file pointer. email Parser wants to see strings rather than bytes. But a TextIOWrapper around self.rfile would buffer too many bytes from the stream, bytes which we later need to read as bytes. So we read the correct bytes here...
def push(tool, slug, config_loader, prompt=lambda included, excluded: True): """ Push to github.com/org/repo=username/slug if tool exists. Returns username, commit hash """ check_dependencies() org, (included, excluded) = connect(slug, config_loader) with authenticate(org) as user, prepare(tool, slug, user, included): ...
def local(tool, slug, config_loader, offline=False): """ Create/update local copy of github.com/org/repo/branch. Returns path to local copy """ # Parse slug slug = Slug(slug, offline=offline) local_path = Path(LOCAL_PATH).expanduser() / slug.org / slug.repo git = Git(f"-C {shlex.quote(str(local_path))}") if not local_p...
mean something else?")) return problem_path
def working_area(files, name=""): """ Copy all files to a temporary directory (the working area) Optionally names the working area name Returns path to the working area """ with tempfile.TemporaryDirectory() as dir: dir = Path(Path(dir) / name) dir.mkdir(exist_ok=True) for f in files: dest = (dir / f).absolute() dest.p...
def cd(dest): """ Temporarily cd into a directory""" origin = os.getcwd() try: os.chdir(dest) yield dest finally: os.chdir(origin)
def files(patterns, require_tags=("require",), include_tags=("include",), exclude_tags=("exclude",), root=".", always_exclude=("**/.git*", "**/.lfs*", "**/.c9*", "**/.~c9*")): """ Takes a list of lib50._config.TaggedValue returns which files should be included and excluded from `root`. Any pattern tagged with a tag fro...
pattern in patterns: # Include all files that are tagged with !require if pattern.tag in require_tags: file = str(Path(pattern.value)) if not Path(file).exists(): missing_files.append(file) else: try: excluded.remove(file) except KeyError: pass else: included.add(file) # Include all files that are tagged with !include ...
def connect(slug, config_loader): """ Ensure .cs50.yaml and tool key exists, raises Error otherwise Check that all required files as per .cs50.yaml are present Returns tool specific portion of .cs50.yaml """ with ProgressBar(_("Connecting")): # Parse slug slug = Slug(slug) # Get .cs50.yaml try: config = config_loader.l...
return org, (included, excluded)
def authenticate(org): """ Authenticate with GitHub via SSH if possible Otherwise authenticate via HTTPS Returns an authenticated User """ with ProgressBar(_("Authenticating")) as progress_bar: user = _authenticate_ssh(org) progress_bar.stop() if user is None: # SSH auth failed, fallback to HTTPS with _authenticate_htt...
def prepare(tool, branch, user, included): """ Prepare git for pushing Check that there are no permission errors Add necessities to git config Stage files Stage files via lfs if necessary Check that atleast one file is staged """ with ProgressBar(_("Preparing")) as progress_bar, working_area(included) as area: Git.work...
included files for f in included: _run(git(f"add {f}")) # Remove gitattributes from included if Path(".gitattributes").exists() and ".gitattributes" in included: included.remove(".gitattributes") # Add any oversized files through git-lfs _lfs_add(included, git) progress_bar.stop() yield
def upload(branch, user, tool): """ Commit + push to branch Returns username, commit hash """ with ProgressBar(_("Uploading")): language = os.environ.get("LANGUAGE") commit_message = [_("automated commit by {}").format(tool)] # If LANGUAGE environment variable is set, we need to communicate # this to any remote tool vi...
def check_dependencies(): """ Check that dependencies are installed: - require git 2.7+, so that credential-cache--daemon ignores SIGHUP https://github.com/git/git/blob/v2.7.0/credential-cache--daemon.c """ # Check that git is installed if not shutil.which("git"): raise Error(_("You don't have git. Install git, then re...
def _run(command, quiet=False, timeout=None): """Run a command, returns command output.""" try: with _spawn(command, quiet, timeout) as child: command_output = child.read().strip().replace("\r\n", "\n") except pexpect.TIMEOUT: logger.info(f"command {command} timed out") raise Error() return command_output
def _glob(pattern, skip_dirs=False): """Glob pattern, expand directories, return all files that matched.""" # Implicit recursive iff no / in pattern and starts with * if "/" not in pattern and pattern.startswith("*"): files = glob.glob(f"**/{pattern}", recursive=True) else: files = glob.glob(pattern, recursive=True) # ...
def _get_content(org, repo, branch, filepath): """Get all content from org/repo/branch/filepath at GitHub.""" url = "https://github.com/{}/{}/raw/{}/{}".format(org, repo, branch, filepath) r = requests.get(url) if not r.ok: if r.status_code == 404: raise InvalidSlugError(_("Invalid slug. Did you mean to submit somethin...
def _lfs_add(files, git): """ Add any oversized files with lfs. Throws error if a file is bigger than 2GB or git-lfs is not installed. """ # Check for large files > 100 MB (and huge files > 2 GB) # https://help.github.com/articles/conditions-for-large-files/ # https://help.github.com/articles/about-git-large-file-stora...
are too large to be submitted:\n{}\n" "Install git-lfs (or remove these files from your directory) " "and then re-run!").format("\n".join(larges))) # Install git-lfs for this repo _run(git("lfs install --local")) # For pre-push hook _run(git("config credential.helper cache")) # Rm previously added file, have lfs track ...
def _authenticate_ssh(org): """Try authenticating via ssh, if succesful yields a User, otherwise raises Error.""" # Try to get username from git config username = os.environ.get(f"{org.upper()}_USERNAME") # Require ssh-agent child = pexpect.spawn("ssh -T git@github.com", encoding="utf8") # GitHub prints 'Hi {username}!...
def _authenticate_https(org): """Try authenticating via HTTPS, if succesful yields User, otherwise raises Error.""" _CREDENTIAL_SOCKET.parent.mkdir(mode=0o700, exist_ok=True) try: Git.cache = f"-c credential.helper= -c credential.helper='cache --socket {_CREDENTIAL_SOCKET}'" git = Git(Git.cache) # Get credentials from ...
and use it as your password." " See https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line for more info.") if res.status_code != 200: logger.info(res.headers) logger.info(res.text) raise Error(_("Invalid username and/or password.") if res.status_code == 401 else _("Could not authenticat...
def _prompt_username(prompt="Username: ", prefill=None): """Prompt the user for username.""" if prefill: readline.set_startup_hook(lambda: readline.insert_text(prefill)) try: return input(prompt).strip() except EOFError: print() finally: readline.set_startup_hook()
def _prompt_password(prompt="Password: "): """Prompt the user for password, printing asterisks for each character""" fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) tty.setraw(fd) print(prompt, end="", flush=True) password = [] try: while True: ch = sys.stdin.buffer.read(1)[0] if ch in (ord("\r"), ord("\n"...
def _check_endings(self): """Check begin/end of slug, raises Error if malformed.""" if self.slug.startswith("/") and self.slug.endswith("/"): raise InvalidSlugError( _("Invalid slug. Did you mean {}, without the leading and trailing slashes?".format(self.slug.strip("/")))) elif self.slug.startswith("/"): raise InvalidS...
def _get_branches(self): """Get branches from org/repo.""" if self.offline: local_path = Path(LOCAL_PATH).expanduser() / self.org / self.repo get_refs = f"git -C {shlex.quote(str(local_path))} show-ref --heads" else: get_refs = f"git ls-remote --heads https://github.com/{self.org}/{self.repo}" try: # Parse get_refs out...
def stop(self): """Stop the progress bar.""" if self._progressing: self._progressing = False self._thread.join()
def make_url(path, protocol=None, hosts=None): """Make an URL given a path, and optionally, a protocol and set of hosts to select from randomly. :param path: The Archive.org path. :type path: str :param protocol: (optional) The HTTP protocol to use. "https://" is used by default. :type protocol: str :param hosts: (opti...
def metadata_urls(identifiers, protocol=None, hosts=None): """An Archive.org metadata URL generator. :param identifiers: A set of Archive.org identifiers for which to make metadata URLs. :type identifiers: iterable :param protocol: (optional) The HTTP protocol to use. "https://" is used by default. :type protocol: str ...
def lang_direction(request): """ Sets lang_direction context variable to whether the language is RTL or LTR """ if lang_direction.rtl_langs is None: lang_direction.rtl_langs = getattr(settings, "RTL_LANGUAGES", set()) return {"lang_direction": "rtl" if request.LANGUAGE_CODE in lang_direction.rtl_langs else "ltr"}
def lists(self, **kwargs): """Gets the top-level lists available from the API. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('lists') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
def movie_lists(self, **kwargs): """Gets the movie lists available from the API. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('movie_lists') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
def movies_box_office(self, **kwargs): """Gets the top box office earning movies from the API. Sorted by most recent weekend gross ticket sales. Args: limit (optional): limits the number of movies returned, default=10 country (optional): localized data for selected country, default="us" Returns: A dict respresentation ...
def movies_in_theaters(self, **kwargs): """Gets the movies currently in theaters from the API. Args: page_limit (optional): number of movies to show per page, default=16 page (optional): results page number, default=1 country (optional): localized data for selected country, default="us" Returns: A dict respresentation ...
def movies_opening(self, **kwargs): """Gets the current opening movies from the API. Args: limit (optional): limits the number of movies returned, default=10 country (optional): localized data for selected country, default="us" Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path...
def movies_upcoming(self, **kwargs): """Gets the upcoming movies from the API. Args: page_limit (optional): number of movies to show per page, default=16 page (optional): results page number, default=1 country (optional): localized data for selected country, default="us" Returns: A dict respresentation of the JSON retu...
def dvd_lists(self, **kwargs): """Gets the dvd lists available from the API. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('dvd_lists') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
def dvds_top_rentals(self, **kwargs): """Gets the current opening movies from the API. Args: limit (optional): limits the number of movies returned, default=10 country (optional): localized data for selected country, default="us" Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_pa...
def dvds_current_releases(self, **kwargs): """Gets the upcoming movies from the API. Args: page_limit (optional): number of movies to show per page, default=16 page (optional): results page number, default=1 country (optional): localized data for selected country, default="us" Returns: A dict respresentation of the JSO...
def dvds_new_releases(self, **kwargs): """Gets the upcoming movies from the API. Args: page_limit (optional): number of movies to show per page, default=16 page (optional): results page number, default=1 country (optional): localized data for selected country, default="us" Returns: A dict respresentation of the JSON re...
def dvds_upcoming(self, **kwargs): """Gets the upcoming movies from the API. Args: page_limit (optional): number of movies to show per page, default=16 page (optional): results page number, default=1 country (optional): localized data for selected country, default="us" Returns: A dict respresentation of the JSON return...
def code_to_unicode(code): u"""Convert character code(hex) to unicode""" def utf32chr(n): """utf32char for narrow build python""" return eval("u\'\\U%08X\'" % n) def lazy_unichr(n): try: return unichr(n) except ValueError: warnings.warn("Your python it built as narrow python. Make with " "'--enable-unicode=ucs4' config...
def code_to_sjis(code): u"""Convert character code(hex) to string""" if code and isinstance(code, basestring): clean_code = code.replace('>', '') if clean_code: _code_to_sjis_char = lambda c: ''.join([chr(int("%c%c"%(a, b), 16)) for a, b in izip(c[0::2], c[1::2])]) return ''.join([_code_to_sjis_char(code_char) for code...
def create_regex_patterns(symbols): u"""create regex patterns for text, google, docomo, kddi and softbank via `symbols` create regex patterns for finding emoji character from text. the pattern character use `unicode` formatted character so you have to decode text which is not decoded. """ pattern_unicode = [] pattern_g...
% u'|'.join(pattern_softbank)) return { # forward reverse 'text': (None, pattern_unicode), 'docomo_img': (None, pattern_unicode), 'kddi_img': (None, pattern_unicode), 'softbank_img': (None, pattern_unicode), 'google': (pattern_google, pattern_unicode), 'docomo': (pattern_docomo, pattern_unicode), 'kddi': (pattern_kddi,...
def create_translate_dictionaries(symbols): u"""create translate dictionaries for text, google, docomo, kddi and softbank via `symbols` create dictionaries for translate emoji character to carrier from unicode (forward) or to unicode from carrier (reverse). method return dictionary instance which key is carrier name an...
unicode formatted is `usjis` attribute.) """ unicode_to_text = {} unicode_to_docomo_img = {} unicode_to_kddi_img = {} unicode_to_softbank_img = {} unicode_to_google = {} unicode_to_docomo = {} unicode_to_kddi = {} unicode_to_softbank = {} google_to_unicode = {} docomo_to_unicode = {} kddi_to_unicode = {} softbank_to_un...
def vtquery(apikey, checksums): """Performs the query dealing with errors and throttling requests.""" data = {'apikey': apikey, 'resource': isinstance(checksums, str) and checksums or ', '.join(checksums)} while 1: response = requests.post(VT_REPORT_URL, data=data) response.raise_for_status() if response.status_code ==...
def chunks(iterable, size=1): """Splits iterator in chunks.""" iterator = iter(iterable) for element in iterator: yield chain([element], islice(iterator, size - 1))
def scan(self, filetypes=None): """Iterates over the content of the disk and queries VirusTotal to determine whether it's malicious or not. filetypes is a list containing regular expression patterns. If given, only the files which type will match with one or more of the given patterns will be queried against VirusTotal...
response)
def compute_training_sizes(train_perc, class_sizes, stratified=True): """Computes the maximum training size that the smallest class can provide """ size_per_class = np.int64(np.around(train_perc * class_sizes)) if stratified: print("Different classes in training set are stratified to match smallest class!") # per-class...
def _load(self, dataset_spec): """Actual loading of datasets""" for idx, ds in enumerate(dataset_spec): self.append(ds, idx)
def append(self, dataset, identifier): """ Adds a dataset, if compatible with the existing ones. Parameters ---------- dataset : MLDataset or compatible identifier : hashable String or integer or another hashable to uniquely identify this dataset """ dataset = dataset if isinstance(dataset, MLDataset) else MLDataset(da...
for IDs differ in the two datasets.') if identifier not in self._modalities: self._modalities[identifier] = dataset.data self._num_features.append(dataset.num_features) else: raise KeyError('{} already exists in MultiDataset'.format(identifier)) # each addition should be counted, if successful self._modality_count += 1
def holdout(self, train_perc=0.7, num_rep=50, stratified=True, return_ids_only=False, format='MLDataset'): """ Builds a generator for train and test sets for cross-validation. """ ids_in_class = {cid: self._dataset.sample_ids_in_class(cid) for cid in self._class_sizes.keys()} sizes_numeric = np.array([len(ids_in_class[...
tuples to prevent accidental changes yield tuple(train_set), tuple(test_set) else: yield self._get_data(train_set, format), self._get_data(test_set, format)
def _get_data(self, id_list, format='MLDataset'): """Returns the data, from all modalities, for a given list of IDs""" format = format.lower() features = list() # returning a dict would be better if AutoMKL() can handle it for modality, data in self._modalities.items(): if format in ('ndarray', 'data_matrix'): # turnin...
def _build_package_finder(options, index_urls, session): """ Create a package finder appropriate to this list command. """ return PackageFinder( find_links=options.get('find_links'), index_urls=index_urls, allow_all_prereleases=options.get('pre'), trusted_hosts=options.get('trusted_hosts'), session=session, )
def can_be_updated(cls, dist, latest_version): """Determine whether package can be updated or not.""" scheme = get_scheme('default') name = dist.project_name dependants = cls.get_dependants(name) for dependant in dependants: requires = dependant.requires() for requirement in cls.get_requirement(name, requires): req = p...
def get_dependants(cls, dist): """Yield dependant user packages for a given package name.""" for package in cls.installed_distributions: for requirement_package in package.requires(): requirement_name = requirement_package.project_name # perform case-insensitive matching if requirement_name.lower() == dist.lower(): yie...
def get_requirement(name, requires): """ Yield matching requirement strings. The strings are presented in the format demanded by pip._vendor.distlib.util.parse_requirement. Hopefully I'll be able to figure out a better way to handle this in the future. Perhaps figure out how pip does it's version satisfaction tests and...
def output_package(dist): """Return string displaying package information.""" if dist_is_editable(dist): return '%s (%s, %s)' % ( dist.project_name, dist.version, dist.location, ) return '%s (%s)' % (dist.project_name, dist.version)
def run_outdated(cls, options): """Print outdated user packages.""" latest_versions = sorted( cls.find_packages_latest_versions(cls.options), key=lambda p: p[0].project_name.lower()) for dist, latest_version, typ in latest_versions: if latest_version > dist.parsed_version: if options.all: pass elif options.pinned: if c...
def softmax(x): """Can be replaced once scipy 1.3 is released, although numeric stability should be checked.""" e_x = np.exp(x - np.max(x)) return e_x / e_x.sum(axis=1)[:, None]
def fit(self, X, y, eval_set=None): """Fit a gradient boosting procedure to a dataset. Args: X (array-like or sparse matrix of shape (n_samples, n_features)): The training input samples. Sparse matrices are accepted only if they are supported by the weak model. y (array-like of shape (n_samples,)): The training target ...
loss.default_init_estimator) eval_metric = self.eval_metric or loss line_searcher = self.line_searcher if line_searcher is None and base_estimator_is_tree: line_searcher = loss.tree_line_searcher self._rng = utils.check_random_state(self.random_state) # At this point we assume the input data has been checked if y.ndim ...
1 then we only use a subset of the features cols = None if self.col_sampling < 1: n_cols = int(X.shape[1] * self.col_sampling) cols = self._rng.choice(X.shape[1], n_cols, replace=False) # Subset X X_fit = X if rows is not None: X_fit = X_fit[rows, :] if cols is not None: X_fit = X_fit[:, cols] # Compute the gradients o...
cols is None else X[:, cols]) # Apply line search if a line searcher has been provided if line_searcher: ls = copy.copy(line_searcher) ls = ls.fit(y[:, i], y_pred[:, i], gradient, direction) line_searchers.append(ls) direction = ls.update(direction) # Move the predictions along the estimated descent direction y_pred[:,...
def iter_predict(self, X, include_init=False): """Returns the predictions for ``X`` at every stage of the boosting procedure. Args: X (array-like or sparse matrix of shape (n_samples, n_features): The input samples. Sparse matrices are accepted only if they are supported by the weak model. include_init (bool, default=F...
sure the columns of X are arranged # in the correct order if cols is None: direction = estimator.predict(X) else: direction = estimator.predict(X[:, cols]) if line_searcher: direction = line_searcher.update(direction) y_pred[:, i] += self.learning_rate * direction yield y_pred
def predict(self, X): """Returns the predictions for ``X``. Under the hood this method simply goes through the outputs of ``iter_predict`` and returns the final one. Arguments: X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples. Sparse matrices are accepted only if they are supported by...
def iter_predict_proba(self, X, include_init=False): """Returns the predicted probabilities for ``X`` at every stage of the boosting procedure. Arguments: X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples. Sparse matrices are accepted only if they are supported by the weak model. inclu...
def iter_predict(self, X, include_init=False): """Returns the predicted classes for ``X`` at every stage of the boosting procedure. Arguments: X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples. Sparse matrices are accepted only if they are supported by the weak model. include_init (boo...
def predict_proba(self, X): """Returns the predicted probabilities for ``X``. Arguments: X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples. Sparse matrices are accepted only if they are supported by the weak model. Returns: array of shape (n_samples, n_classes) containing the predicted...
def parse_pandoc(self, attrs): """Read pandoc attributes.""" id = attrs[0] classes = attrs[1] kvs = OrderedDict(attrs[2]) return id, classes, kvs
def parse_markdown(self, attr_string): """Read markdown attributes.""" attr_string = attr_string.strip('{}') splitter = re.compile(self.split_regex(separator=self.spnl)) attrs = splitter.split(attr_string)[1::2] # match single word attributes e.g. ```python if len(attrs) == 1 \ and not attr_string.startswith(('#', '.')...
def parse_html(self, attr_string): """Read a html string to attributes.""" splitter = re.compile(self.split_regex(separator=self.spnl)) attrs = splitter.split(attr_string)[1::2] idre = re.compile(r'''id=["']?([\w ]*)['"]?''') clsre = re.compile(r'''class=["']?([\w ]*)['"]?''') id_matches = [idre.search(a) for a in attr...
def parse_dict(self, attrs): """Read a dict to attributes.""" attrs = attrs or {} ident = attrs.get("id", "") classes = attrs.get("classes", []) kvs = OrderedDict((k, v) for k, v in attrs.items() if k not in ("classes", "id")) return ident, classes, kvs
def to_markdown(self, format='{id} {classes} {kvs}', surround=True): """Returns attributes formatted as markdown with optional format argument to determine order of attribute contents. """ id = '#' + self.id if self.id else '' classes = ' '.join('.' + cls for cls in self.classes) kvs = ' '.join('{}={}'.format(k, v) for...
def to_html(self): """Returns attributes formatted as html.""" id, classes, kvs = self.id, self.classes, self.kvs id_str = 'id="{}"'.format(id) if id else '' class_str = 'class="{}"'.format(' '.join(classes)) if classes else '' key_str = ' '.join('{}={}'.format(k, v) for k, v in kvs.items()) return ' '.join((id_str, cl...
def to_dict(self): """Returns attributes formatted as a dictionary.""" d = {'id': self.id, 'classes': self.classes} d.update(self.kvs) return d
def watch_pending_transactions(self, callback): ''' Callback will receive one argument: the transaction object just observed This is equivalent to `eth.filter('pending')` ''' self.pending_tx_watchers.append(callback) if len(self.pending_tx_watchers) == 1: eth.filter('pending').watch(self._new_pending_tx)
def _start_watching_blocks(self): ''' Internal: call immediately after registering a block watcher If the new watcher is the first, then start watching web3 remotely ''' if sum(map(len, (self.solid_watchers, self.block_watchers))) == 1: eth.filter('latest').watch(self._new_block)
def from_files(controller, track_path, log_level=logging.ERROR): """Create rocket instance using project file connector""" rocket = Rocket(controller, track_path=track_path, log_level=log_level) rocket.connector = FilesConnector(track_path, controller=controller, tracks=rocket.tracks) return rocket
def from_project_file(controller, project_file, track_path=None, log_level=logging.ERROR): """Create rocket instance using project file connector""" rocket = Rocket(controller, track_path=track_path, log_level=log_level) rocket.connector = ProjectFileConnector(project_file, controller=controller, tracks=rocket.tracks) ...
def from_socket(controller, host=None, port=None, track_path=None, log_level=logging.ERROR): """Create rocket instance using socket connector""" rocket = Rocket(controller, track_path=track_path, log_level=log_level) rocket.connector = SocketConnector(controller=controller, tracks=rocket.tracks, host=host, port=port) r...
def value(self, name): """get value of a track at the current time""" return self.tracks.get(name).row_value(self.controller.row)
def compare_filesystems(fs0, fs1, concurrent=False): """Compares the two given filesystems. fs0 and fs1 are two mounted GuestFS instances containing the two disks to be compared. If the concurrent flag is True, two processes will be used speeding up the comparison on multiple CPUs. Returns a dictionary containing files...
def file_comparison(files0, files1): """Compares two dictionaries of files returning their difference. {'created_files': [<files in files1 and not in files0>], 'deleted_files': [<files in files0 and not in files1>], 'modified_files': [<files in both files0 and files1 but different>]} """ comparison = {'created_files': ...
def extract_files(filesystem, files, path): """Extracts requested files. files must be a list of files in the format {"C:\\Windows\\System32\\NTUSER.DAT": "sha1_hash"} for windows {"/home/user/text.txt": "sha1_hash"} for other FS. files will be extracted into path which must exist beforehand. Returns two dictionaries: ...
def compare_registries(fs0, fs1, concurrent=False): """Compares the Windows Registry contained within the two File Systems. If the concurrent flag is True, two processes will be used speeding up the comparison on multiple CPUs. Returns a dictionary. {'created_keys': {'\\Reg\\Key': (('Key', 'Type', 'Value'), ...)} 'dele...
def registry_comparison(registry0, registry1): """Compares two dictionaries of registry keys returning their difference.""" comparison = {'created_keys': {}, 'deleted_keys': [], 'created_values': {}, 'deleted_values': {}, 'modified_values': {}} for key, info in registry1.items(): if key in registry0: if info[1] != regi...
def compare_values(values0, values1): """Compares all the values of a single registry key.""" values0 = {v[0]: v[1:] for v in values0} values1 = {v[0]: v[1:] for v in values1} created = [(k, v[0], v[1]) for k, v in values1.items() if k not in values0] deleted = [(k, v[0], v[1]) for k, v in values0.items() if k not in v...
def compare_hives(fs0, fs1): """Compares all the windows registry hive files returning those which differ. """ registries = [] for path in chain(registries_path(fs0.fsroot), user_registries(fs0, fs1)): if fs0.checksum(path) != fs1.checksum(path): registries.append(path) return registries
def user_registries(fs0, fs1): """Returns the list of user registries present on both FileSystems.""" for user in fs0.ls('{}Users'.format(fs0.fsroot)): for path in user_registries_path(fs0.fsroot, user): if fs1.exists(path): yield path
def files_type(fs0, fs1, files): """Inspects the file type of the given files.""" for file_meta in files['deleted_files']: file_meta['type'] = fs0.file(file_meta['path']) for file_meta in files['created_files'] + files['modified_files']: file_meta['type'] = fs1.file(file_meta['path']) return files