INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Add metadata to an item.
def metadata(self, item, filter_classified=False): """Add metadata to an item. It adds metadata to a given item such as how and when it was fetched. The contents from the original item will be stored under the 'data' keyword. :param item: an item fetched by a backend :p...
Parse a list of arguments.
def parse(self, *args): """Parse a list of arguments. Parse argument strings needed to run a backend command. The result will be a `argparse.Namespace` object populated with the values obtained after the validation of the parameters. :param args: argument strings :resu...
Activate authentication arguments parsing
def _set_auth_arguments(self, basic_auth=True, token_auth=False): """Activate authentication arguments parsing""" group = self.parser.add_argument_group('authentication arguments') if basic_auth: group.add_argument('-u', '--backend-user', dest='user', ...
Activate archive arguments parsing
def _set_archive_arguments(self): """Activate archive arguments parsing""" group = self.parser.add_argument_group('archive arguments') group.add_argument('--archive-path', dest='archive_path', default=None, help="directory path to the archives") group.add_argu...
Activate output arguments parsing
def _set_output_arguments(self): """Activate output arguments parsing""" group = self.parser.add_argument_group('output arguments') group.add_argument('-o', '--output', type=argparse.FileType('w'), dest='outfile', default=sys.stdout, help="o...
Fetch and write items.
def run(self): """Fetch and write items. This method runs the backend to fetch the items from the given origin. Items are converted to JSON objects and written to the defined output. If `fetch-archive` parameter was given as an argument during the inizialization of the ...
Initialize archive based on the parsed parameters
def _initialize_archive(self): """Initialize archive based on the parsed parameters""" if 'archive_path' not in self.parsed_args: manager = None elif self.parsed_args.no_archive: manager = None else: if not self.parsed_args.archive_path: ...
Fetch the messages
def fetch_items(self, category, **kwargs): """Fetch the messages :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] logger.info("Looking for messages from '%s' on '...
Extracts the update time from a MBox item.
def metadata_updated_on(item): """Extracts the update time from a MBox item. The timestamp used is extracted from 'Date' field in its several forms. This date is converted to UNIX timestamp format. :param item: item generated by the backend :returns: a UNIX timestamp ...
Parse a mbox file.
def parse_mbox(filepath): """Parse a mbox file. This method parses a mbox file and returns an iterator of dictionaries. Each one of this contains an email message. :param filepath: path of the mbox to parse :returns : generator of messages; each message is stored in a ...
Fetch and parse the messages from a mailing list
def _fetch_and_parse_messages(self, mailing_list, from_date): """Fetch and parse the messages from a mailing list""" from_date = datetime_to_utc(from_date) nmsgs, imsgs, tmsgs = (0, 0, 0) for mbox in mailing_list.mboxes: tmp_path = None try: tm...
Copy the contents of a mbox to a temporary file
def _copy_mbox(self, mbox): """Copy the contents of a mbox to a temporary file""" tmp_path = tempfile.mktemp(prefix='perceval_') with mbox.container as f_in: with open(tmp_path, mode='wb') as f_out: for l in f_in: f_out.write(l) return tm...
Check if the given message has the mandatory fields
def _validate_message(self, message): """Check if the given message has the mandatory fields""" # This check is "case insensitive" because we're # using 'CaseInsensitiveDict' from requests.structures # module to store the contents of a message. if self.MESSAGE_ID_FIELD not in me...
Convert a message in CaseInsensitiveDict to dict.
def _casedict_to_dict(self, message): """Convert a message in CaseInsensitiveDict to dict. This method also converts well known problematic headers, such as Message-ID and Date to a common name. """ message_id = message.pop(self.MESSAGE_ID_FIELD) date = message.pop(self....
Return a Message representation or raise a KeyError.
def get_message(self, key): """Return a Message representation or raise a KeyError.""" start, stop = self._lookup(key) self._file.seek(start) from_line = self._file.readline().replace(mailbox.linesep, b'') string = self._file.read(stop - self._file.tell()) msg = self._me...
Get the mboxes managed by this mailing list.
def mboxes(self): """Get the mboxes managed by this mailing list. Returns the archives sorted by name. :returns: a list of `.MBoxArchive` objects """ archives = [] if os.path.isfile(self.dirpath): try: archives.append(MBoxArchive(self.dirpat...
Fetch commits.
def fetch(self, category=CATEGORY_COMMIT, from_date=DEFAULT_DATETIME, to_date=DEFAULT_LAST_DATETIME, branches=None, latest_items=False, no_update=False): """Fetch commits. The method retrieves from a Git repository or a log file a list of commits. Commits are returned in the same ...
Fetch the commits
def fetch_items(self, category, **kwargs): """Fetch the commits :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] to_date = kwargs['to_date'] branches = kwa...
Parse a Git log file.
def parse_git_log_from_file(filepath): """Parse a Git log file. The method parses the Git log file and returns an iterator of dictionaries. Each one of this, contains a commit. :param filepath: path to the log file :returns: a generator of parsed commits :raises Parse...
Initialize repositories directory path
def _pre_init(self): """Initialize repositories directory path""" if self.parsed_args.git_log: git_path = self.parsed_args.git_log elif not self.parsed_args.git_path: base_path = os.path.expanduser('~/.perceval/repositories/') processed_uri = self.parsed_args...
Returns the Git argument parser.
def setup_cmd_parser(cls): """Returns the Git argument parser.""" parser = BackendCommandArgumentParser(cls.BACKEND.CATEGORIES, from_date=True, to_date=True) # Optional arguments group = parser....
Parse the Git log stream.
def parse(self): """Parse the Git log stream.""" for line in self.stream: line = line.rstrip('\n') parsed = False self.nline += 1 while not parsed: parsed = self.handlers[self.state](line) if self.state == self.COMMIT and...
Get the old filepath of a moved/ renamed file.
def __get_old_filepath(self, f): """Get the old filepath of a moved/renamed file. Moved or renamed files can be found in the log with any of the next patterns: 'old_name => new_name' '{old_prefix => new_prefix}/name' 'name/{old_suffix => new_suffix}' This ...
Clone a Git repository.
def clone(cls, uri, dirpath): """Clone a Git repository. Make a bare copy of the repository stored in `uri` into `dirpath`. The repository would be either local or remote. :param uri: URI of the repository :param dirtpath: directory where the repository will be cloned ...
Count the objects of a repository.
def count_objects(self): """Count the objects of a repository. The method returns the total number of objects (packed and unpacked) available on the repository. :raises RepositoryError: when an error occurs counting the objects of a repository """ cmd_count ...
Check if the repo is in a detached state.
def is_detached(self): """Check if the repo is in a detached state. The repository is in a detached state when HEAD is not a symbolic reference. :returns: whether the repository is detached or not :raises RepositoryError: when an error occurs checking the state of ...
Update repository from its remote.
def update(self): """Update repository from its remote. Calling this method, the repository will be synchronized with the remote repository using 'fetch' command for 'heads' refs. Any commit stored in the local copy will be removed; refs will be overwritten. :raises Rep...
Keep the repository in sync.
def sync(self): """Keep the repository in sync. This method will synchronize the repository with its 'origin', fetching newest objects and updating references. It uses low level commands which allow to keep track of which things have changed in the repository. The metho...
Read the list commits from the repository
def rev_list(self, branches=None): """Read the list commits from the repository The list of branches is a list of strings, with the names of the branches to fetch. If the list of branches is empty, no commit is fetched. If the list of branches is None, all commits for all branch...
Read the commit log from the repository.
def log(self, from_date=None, to_date=None, branches=None, encoding='utf-8'): """Read the commit log from the repository. The method returns the Git log of the repository using the following options: git log --raw --numstat --pretty=fuller --decorate=full --all --re...
Show the data of a set of commits.
def show(self, commits=None, encoding='utf-8'): """Show the data of a set of commits. The method returns the output of Git show command for a set of commits using the following options: git show --raw --numstat --pretty=fuller --decorate=full --parents -M -C -c [<co...
Fetch changes and store them in a pack.
def _fetch_pack(self): """Fetch changes and store them in a pack.""" def prepare_refs(refs): return [ref.hash.encode('utf-8') for ref in refs if not ref.refname.endswith('^{}')] def determine_wants(refs): remote_refs = prepare_refs(self._discover_ref...
Read the commits of a pack.
def _read_commits_from_pack(self, packet_name): """Read the commits of a pack.""" filepath = 'objects/pack/pack-' + packet_name cmd_verify_pack = ['git', 'verify-pack', '-v', filepath] outs = self._exec(cmd_verify_pack, cwd=self.dirpath, env=self.gitenv) outs = outs.decode('ut...
Update references removing old ones.
def _update_references(self, refs): """Update references removing old ones.""" new_refs = [ref.refname for ref in refs] # Delete old references for old_ref in self._discover_refs(): if not old_ref.refname.startswith('refs/heads/'): continue if ol...
Get the current list of local or remote refs.
def _discover_refs(self, remote=False): """Get the current list of local or remote refs.""" if remote: cmd_refs = ['git', 'ls-remote', '-h', '-t', '--exit-code', 'origin'] sep = '\t' ignored_error_codes = [2] else: # Check first whether the local ...
Update a reference.
def _update_ref(self, ref, delete=False): """Update a reference.""" cmd = ['git', 'update-ref'] if delete: cmd.extend(['-d', ref.refname]) action = 'deleted' else: cmd.extend([ref.refname, ref.hash]) action = 'updated to %s' % ref.hash ...
Run a command with a non blocking call.
def _exec_nb(self, cmd, cwd=None, env=None, encoding='utf-8'): """Run a command with a non blocking call. Execute `cmd` command with a non blocking call. The command will be run in the directory set by `cwd`. Enviroment variables can be set using the `env` dictionary. The output data is...
Reads self. proc. stderr.
def _read_stderr(self, encoding='utf-8'): """Reads self.proc.stderr. Usually, this should be read in a thread, to prevent blocking the read from stdout of the stderr buffer is filled, and this function is not called becuase the program is busy in the stderr reading loop. ...
Run a command.
def _exec(cmd, cwd=None, env=None, ignored_error_codes=None, encoding='utf-8'): """Run a command. Execute `cmd` command in the directory set by `cwd`. Environment variables can be set using the `env` dictionary. The output data is returned as encoded bytes. Comman...
Fetch the tweets from the server.
def fetch(self, category=CATEGORY_TWEET, since_id=None, max_id=None, geocode=None, lang=None, include_entities=True, tweets_type=TWEET_TYPE_MIXED): """Fetch the tweets from the server. This method fetches tweets from the TwitterSearch API published in the last seven days. ...
Fetch the tweets
def fetch_items(self, category, **kwargs): """Fetch the tweets :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ since_id = kwargs['since_id'] max_id = kwargs['max_id'] geocode = kwargs['g...
Init client
def _init_client(self, from_archive=False): """Init client""" return TwitterClient(self.api_token, self.max_items, self.sleep_for_rate, self.min_rate_to_sleep, self.sleep_time, self.archive, from_archive)
Fetch tweets for a given query between since_id and max_id.
def tweets(self, query, since_id=None, max_id=None, geocode=None, lang=None, include_entities=True, result_type=TWEET_TYPE_MIXED): """Fetch tweets for a given query between since_id and max_id. :param query: query to fetch tweets :param since_id: if not null, it returns results w...
Fetch a resource.
def _fetch(self, url, params): """Fetch a resource. Method to fetch and to iterate over the contents of a type of resource. The method returns a generator of pages for that resource and parameters. :param url: the endpoint of the API :param params: parameters to filter ...
Returns the Twitter argument parser.
def setup_cmd_parser(cls): """Returns the Twitter argument parser.""" parser = BackendCommandArgumentParser(cls.BACKEND.CATEGORIES, token_auth=True, archive=True) # Backend token is required act...
Fetch data from Google API.
def fetch(self, category=CATEGORY_HITS): """Fetch data from Google API. The method retrieves a list of hits for some given keywords using the Google API. :param category: the category of items to fetch :returns: a generator of data """ kwargs = {} items...
Fetch Google hit items
def fetch_items(self, category, **kwargs): """Fetch Google hit items :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ logger.info("Fetching data for '%s'", self.keywords) hits_raw = self.client....
Init client
def _init_client(self, from_archive=False): """Init client""" return GoogleHitsClient(self.sleep_time, self.max_retries, archive=self.archive, from_archive=from_archive)
Parse the hits returned by the Google Search API
def __parse_hits(self, hit_raw): """Parse the hits returned by the Google Search API""" # Create the soup and get the desired div bs_result = bs4.BeautifulSoup(hit_raw, 'html.parser') hit_string = bs_result.find("div", id="resultStats").text # Remove commas or dots hit_...
Fetch information about a list of keywords.
def hits(self, keywords): """Fetch information about a list of keywords.""" if len(keywords) == 1: query_str = keywords[0] else: query_str = ' '.join([k for k in keywords]) logger.info("Fetching hits for '%s'", query_str) params = {'q': query_str} ...
Fetch the issues/ pull requests from the repository.
def fetch(self, category=CATEGORY_ISSUE, from_date=DEFAULT_DATETIME, to_date=DEFAULT_LAST_DATETIME): """Fetch the issues/pull requests from the repository. The method retrieves, from a GitHub repository, the issues/pull requests updated since the given date. :param category: the catego...
Fetch the items ( issues or pull_requests )
def fetch_items(self, category, **kwargs): """Fetch the items (issues or pull_requests) :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] to_date = kwargs['to_date'...
Extracts the update time from a GitHub item.
def metadata_updated_on(item): """Extracts the update time from a GitHub item. The timestamp used is extracted from 'updated_at' field. This date is converted to UNIX timestamp format. As GitHub dates are in UTC the conversion is straightforward. :param item: item generated by ...
Extracts the category from a GitHub item.
def metadata_category(item): """Extracts the category from a GitHub item. This backend generates two types of item which are 'issue' and 'pull_request'. """ if "base" in item: category = CATEGORY_PULL_REQUEST elif "forks_count" in item: category ...
Init client
def _init_client(self, from_archive=False): """Init client""" return GitHubClient(self.owner, self.repository, self.api_token, self.base_url, self.sleep_for_rate, self.min_rate_to_sleep, self.sleep_time, self.max_retries, ...
Fetch the issues
def __fetch_issues(self, from_date, to_date): """Fetch the issues""" issues_groups = self.client.issues(from_date=from_date) for raw_issues in issues_groups: issues = json.loads(raw_issues) for issue in issues: if str_to_datetime(issue['updated_at']) > ...
Fetch the pull requests
def __fetch_pull_requests(self, from_date, to_date): """Fetch the pull requests""" raw_pulls = self.client.pulls(from_date=from_date) for raw_pull in raw_pulls: pull = json.loads(raw_pull) if str_to_datetime(pull['updated_at']) > to_date: return ...
Get repo info about stars watchers and forks
def __fetch_repo_info(self): """Get repo info about stars, watchers and forks""" raw_repo = self.client.repo() repo = json.loads(raw_repo) fetched_on = datetime_utcnow() repo['fetched_on'] = fetched_on.timestamp() yield repo
Get issue reactions
def __get_issue_reactions(self, issue_number, total_count): """Get issue reactions""" reactions = [] if total_count == 0: return reactions group_reactions = self.client.issue_reactions(issue_number) for raw_reactions in group_reactions: for reaction i...
Get issue comments
def __get_issue_comments(self, issue_number): """Get issue comments""" comments = [] group_comments = self.client.issue_comments(issue_number) for raw_comments in group_comments: for comment in json.loads(raw_comments): comment_id = comment.get('id') ...
Get reactions on issue comments
def __get_issue_comment_reactions(self, comment_id, total_count): """Get reactions on issue comments""" reactions = [] if total_count == 0: return reactions group_reactions = self.client.issue_comment_reactions(comment_id) for raw_reactions in group_reactions: ...
Get issue assignees
def __get_issue_assignees(self, raw_assignees): """Get issue assignees""" assignees = [] for ra in raw_assignees: assignees.append(self.__get_user(ra['login'])) return assignees
Get pull request requested reviewers
def __get_pull_requested_reviewers(self, pr_number): """Get pull request requested reviewers""" requested_reviewers = [] group_requested_reviewers = self.client.pull_requested_reviewers(pr_number) for raw_requested_reviewers in group_requested_reviewers: group_requested_rev...
Get pull request commit hashes
def __get_pull_commits(self, pr_number): """Get pull request commit hashes""" hashes = [] group_pull_commits = self.client.pull_commits(pr_number) for raw_pull_commits in group_pull_commits: for commit in json.loads(raw_pull_commits): commit_hash = commit['...
Get pull request review comments
def __get_pull_review_comments(self, pr_number): """Get pull request review comments""" comments = [] group_comments = self.client.pull_review_comments(pr_number) for raw_comments in group_comments: for comment in json.loads(raw_comments): comment_id = comm...
Get pull review comment reactions
def __get_pull_review_comment_reactions(self, comment_id, total_count): """Get pull review comment reactions""" reactions = [] if total_count == 0: return reactions group_reactions = self.client.pull_review_comment_reactions(comment_id) for raw_reactions in group_...
Get user and org data for the login
def __get_user(self, login): """Get user and org data for the login""" user = {} if not login: return user user_raw = self.client.user(login) user = json.loads(user_raw) user_orgs_raw = \ self.client.user_orgs(login) user['organizations'...
Get reactions of an issue
def issue_reactions(self, issue_number): """Get reactions of an issue""" payload = { 'per_page': PER_PAGE, 'direction': 'asc', 'sort': 'updated' } path = urijoin("issues", str(issue_number), "reactions") return self.fetch_items(path, payload)
Fetch the issues from the repository.
def issues(self, from_date=None): """Fetch the issues from the repository. The method retrieves, from a GitHub repository, the issues updated since the given date. :param from_date: obtain issues updated since this date :returns: a generator of issues """ paylo...
Fetch the pull requests from the repository.
def pulls(self, from_date=None): """Fetch the pull requests from the repository. The method retrieves, from a GitHub repository, the pull requests updated since the given date. :param from_date: obtain pull requests updated since this date :returns: a generator of pull request...
Get repository data
def repo(self): """Get repository data""" path = urijoin(self.base_url, 'repos', self.owner, self.repository) r = self.fetch(path) repo = r.text return repo
Get pull requested reviewers
def pull_requested_reviewers(self, pr_number): """Get pull requested reviewers""" requested_reviewers_url = urijoin("pulls", str(pr_number), "requested_reviewers") return self.fetch_items(requested_reviewers_url, {})
Get pull request commits
def pull_commits(self, pr_number): """Get pull request commits""" payload = { 'per_page': PER_PAGE, } commit_url = urijoin("pulls", str(pr_number), "commits") return self.fetch_items(commit_url, payload)
Get pull request review comments
def pull_review_comments(self, pr_number): """Get pull request review comments""" payload = { 'per_page': PER_PAGE, 'direction': 'asc', 'sort': 'updated' } comments_url = urijoin("pulls", str(pr_number), "comments") return self.fetch_items(co...
Get reactions of a review comment
def pull_review_comment_reactions(self, comment_id): """Get reactions of a review comment""" payload = { 'per_page': PER_PAGE, 'direction': 'asc', 'sort': 'updated' } path = urijoin("pulls", "comments", str(comment_id), "reactions") return se...
Get the user information and update the user cache
def user(self, login): """Get the user information and update the user cache""" user = None if login in self._users: return self._users[login] url_user = urijoin(self.base_url, 'users', login) logging.info("Getting info for %s" % (url_user)) r = self.fetch...
Get the user public organizations
def user_orgs(self, login): """Get the user public organizations""" if login in self._users_orgs: return self._users_orgs[login] url = urijoin(self.base_url, 'users', login, 'orgs') try: r = self.fetch(url) orgs = r.text except requests.except...
Return token s remaining API points
def _get_token_rate_limit(self, token): """Return token's remaining API points""" rate_url = urijoin(self.base_url, "rate_limit") self.session.headers.update({'Authorization': 'token ' + token}) remaining = 0 try: headers = super().fetch(rate_url).headers ...
Return array of all tokens remaining API points
def _get_tokens_rate_limits(self): """Return array of all tokens remaining API points""" remainings = [0] * self.n_tokens # Turn off archiving when checking rates, because that would cause # archive key conflict (the same URLs giving different responses) arch = self.archive ...
Check all API tokens defined and choose one with most remaining API points
def _choose_best_api_token(self): """Check all API tokens defined and choose one with most remaining API points""" # Return if no tokens given if self.n_tokens == 0: return # If multiple tokens given, choose best token_idx = 0 if self.n_tokens > 1: ...
Check if we need to switch GitHub API tokens
def _need_check_tokens(self): """Check if we need to switch GitHub API tokens""" if self.n_tokens <= 1 or self.rate_limit is None: return False elif self.last_rate_limit_checked is None: self.last_rate_limit_checked = self.rate_limit return True # If...
Update rate limits data for the current token
def _update_current_rate_limit(self): """Update rate limits data for the current token""" url = urijoin(self.base_url, "rate_limit") try: # Turn off archiving when checking rates, because that would cause # archive key conflict (the same URLs giving different responses) ...
Init metadata information.
def init_metadata(self, origin, backend_name, backend_version, category, backend_params): """Init metadata information. Metatada is composed by basic information needed to identify where archived data came from and how it can be retrieved and built into Perceval it...
Store a raw item in this archive.
def store(self, uri, payload, headers, data): """Store a raw item in this archive. The method will store `data` content in this archive. The unique identifier for that item will be generated using the rest of the parameters. :param uri: request URI :param payload: reque...
Retrieve a raw item from the archive.
def retrieve(self, uri, payload, headers): """Retrieve a raw item from the archive. The method will return the `data` content corresponding to the hascode derived from the given parameters. :param uri: request URI :param payload: request payload :param headers: request ...
Create a brand new archive.
def create(cls, archive_path): """Create a brand new archive. Call this method to create a new and empty archive. It will initialize the storage file in the path defined by `archive_path`. :param archive_path: absolute path where the archive file will be created :raises Arch...
Generate a SHA1 based on the given arguments.
def make_hashcode(uri, payload, headers): """Generate a SHA1 based on the given arguments. Hashcodes created by this method will used as unique identifiers for the raw items or resources stored by this archive. :param uri: URI to the resource :param payload: payload of the requ...
Check whether the archive is valid or not.
def _verify_archive(self): """Check whether the archive is valid or not. This method will check if tables were created and if they contain valid data. """ nentries = self._count_table_rows(self.ARCHIVE_TABLE) nmetadata = self._count_table_rows(self.METADATA_TABLE) ...
Load metadata from the archive file
def _load_metadata(self): """Load metadata from the archive file""" logger.debug("Loading metadata infomation of archive %s", self.archive_path) cursor = self._db.cursor() select_stmt = "SELECT origin, backend_name, backend_version, " \ "category, backend_params, ...
Fetch the number of rows in a table
def _count_table_rows(self, table_name): """Fetch the number of rows in a table""" cursor = self._db.cursor() select_stmt = "SELECT COUNT(*) FROM " + table_name try: cursor.execute(select_stmt) row = cursor.fetchone() except sqlite3.DatabaseError as e: ...
Create a new archive.
def create_archive(self): """Create a new archive. The method creates in the filesystem a brand new archive with a random SHA1 as its name. The first byte of the hashcode will be the name of the subdirectory; the remaining bytes, the archive name. :returns: a new `Archi...
Remove an archive.
def remove_archive(self, archive_path): """Remove an archive. This method deletes from the filesystem the archive stored in `archive_path`. :param archive_path: path to the archive :raises ArchiveManangerError: when an error occurs removing the archive """ ...
Search archives.
def search(self, origin, backend_name, category, archived_after): """Search archives. Get the archives which store data based on the given parameters. These parameters define which the origin was (`origin`), how data was fetched (`backend_name`) and data type ('category'). Only ...
Search archives using filters.
def _search_archives(self, origin, backend_name, category, archived_after): """Search archives using filters.""" for archive_path in self._search_files(): try: archive = Archive(archive_path) except ArchiveError: continue match = arch...
Retrieve the file paths stored under the base path.
def _search_files(self): """Retrieve the file paths stored under the base path.""" for root, _, files in os.walk(self.dirpath): for filename in files: location = os.path.join(root, filename) yield location
Check if filename is a compressed file supported by the tool.
def check_compressed_file_type(filepath): """Check if filename is a compressed file supported by the tool. This function uses magic numbers (first four bytes) to determine the type of the file. Supported types are 'gz' and 'bz2'. When the filetype is not supported, the function returns `None`. :pa...
Generate a months range.
def months_range(from_date, to_date): """Generate a months range. Generator of months starting on `from_date` util `to_date`. Each returned item is a tuple of two datatime objects like in (month, month+1). Thus, the result will follow the sequence: ((fd, fd+1), (fd+1, fd+2), ..., (td-2, td-1), ...
Convert an email message into a dictionary.
def message_to_dict(msg): """Convert an email message into a dictionary. This function transforms an `email.message.Message` object into a dictionary. Headers are stored as key:value pairs while the body of the message is stored inside `body` key. Body may have two other keys inside, 'plain', for p...
Remove control and invalid characters from an xml stream.
def remove_invalid_xml_chars(raw_xml): """Remove control and invalid characters from an xml stream. Looks for invalid characters and subtitutes them with whitespaces. This solution is based on these two posts: Olemis Lang's reponse on StackOverflow (http://stackoverflow.com/questions/1707890) and l...
Convert a XML stream into a dictionary.
def xml_to_dict(raw_xml): """Convert a XML stream into a dictionary. This function transforms a xml stream into a dictionary. The attributes are stored as single elements while child nodes are stored into lists. The text node is stored using the special key '__text__'. This code is based on Wi...