Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def wosParser(isifile): plst = set() error = None try: with open(isifile, 'r', encoding='utf-8-sig') as openfile: f = enumerate(openfile, start = 0) while "VR 1.0" not in f.__next__()[1]: pass notEn...
[ "This is a function that is used to create [RecordCollections](../classes/RecordCollection.html#metaknowledge.RecordCollection) from files.\n\n **wosParser**() reads the file given by the path isifile, checks that the header is correct then reads until it reaches EF. All WOS records it encounters are parsed with...
Please provide a description of the function:def isScopusFile(infile, checkedLines = 2, maxHeaderDiff = 3): try: with open(infile, 'r', encoding='utf-8') as openfile: if openfile.read(1) != "\ufeff": return False for i in range(checkedLines): if l...
[ "Determines if _infile_ is the path to a Scopus csv file. A file is considerd to be a Scopus file if it has the correct encoding (`utf-8` with BOM (Byte Order Mark)) and within the first _checkedLines_ a line contains the complete header, the list of all header entries in order is found in [`scopus.scopusHeader`](#...
Please provide a description of the function:def scopusParser(scopusFile): #assumes the file is Scopus recSet = set() error = None lineNum = 0 try: with open(scopusFile, 'r', encoding = 'utf-8') as openfile: #Get rid of the BOM openfile.read(1) header...
[ "Parses a scopus file, _scopusFile_, to extract the individual lines as [ScopusRecords](../classes/ScopusRecord.html#metaknowledge.scopus.ScopusRecord).\n\n A Scopus file is a csv (Comma-separated values) with a complete header, see [`scopus.scopusHeader`](#metaknowledge.scopus) for the entries, and each line af...
Please provide a description of the function:def make_grid(rect, cells={}, num_rows=0, num_cols=0, padding=None, inner_padding=None, outer_padding=None, row_heights={}, col_widths={}, default_row_height='expand', default_col_width='expand'): grid = Grid( bounding_rect=rect, ...
[ "\n Return rectangles for each cell in the specified grid. The rectangles are \n returned in a dictionary where the keys are (row, col) tuples.\n " ]
Please provide a description of the function:def lorem_ipsum(num_sentences=None, num_paragraphs=None): paragraphs = [ 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam justo sem, malesuada ut ultricies ac, bibendum eu neque. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean at...
[ "\n Return the given amount of \"Lorem ipsum...\" text.\n " ]
Please provide a description of the function:def relay_events_from(self, originator, event_type, *more_event_types): handlers = { event_type: lambda *args, **kwargs: \ self.dispatch_event(event_type, *args, **kwargs) for event_type in (event_type,) + ...
[ "\n Configure this handler to re-dispatch events from another handler.\n\n This method configures this handler dispatch an event of type \n *event_type* whenever *originator* dispatches events of the same type \n or any of the types in *more_event_types*. Any arguments passed to the \n ...
Please provide a description of the function:def start_event(self, event_type, *args, dt=1/60): # Don't bother scheduling a timer if nobody's listening. This isn't # great from a general-purpose perspective, because a long-lived event # could have listeners attach and detach in the m...
[ "\n Begin dispatching the given event at the given frequency.\n\n Calling this method will cause an event of type *event_type* with \n arguments *args* to be dispatched every *dt* seconds. This will \n continue until `stop_event()` is called for the same event.\n\n These continuo...
Please provide a description of the function:def stop_event(self, event_type): if event_type in self.__timers: pyglet.clock.unschedule(self.__timers[event_type])
[ "\n Stop dispatching the given event.\n\n It is not an error to attempt to stop an event that was never started, \n the request will just be silently ignored.\n " ]
Please provide a description of the function:def __yield_handlers(self, event_type): if event_type not in self.event_types: raise ValueError("%r not found in %r.event_types == %r" % (event_type, self, self.event_types)) # Search handler stack for matching event handlers for...
[ "\n Yield all the handlers registered for the given event type.\n " ]
Please provide a description of the function:def _filter_pending_updates(self): from more_itertools import unique_everseen as unique yield from reversed(list(unique(reversed(self._pending_updates))))
[ "\n Return all the updates that need to be applied, from a list of all the \n updates that were called while the hold was active. This method is \n meant to be overridden by subclasses that want to customize how held \n updates are applied.\n\n The `self._pending_updates` member ...
Please provide a description of the function:def main(): # Create command line parser. parser = argparse.ArgumentParser() # Adding command line arguments. parser.add_argument("username", help="Github Username", default=None) parser.add_argument( "--deep_dive", help=" ".join( ...
[ "Starting point for the program execution." ]
Please provide a description of the function:def get_html(self): here = path.abspath(path.dirname(__file__)) env = Environment(loader=FileSystemLoader(path.join(here, "res/"))) suggest = env.get_template("suggest.htm.j2") return suggest.render( logo=path.join(here,...
[ "Method to convert the repository list to a search results page." ]
Please provide a description of the function:def to_html(self, write_to): page_html = self.get_html() with open(write_to, "wb") as writefile: writefile.write(page_html.encode("utf-8"))
[ "Method to convert the repository list to a search results page and\n write it to a HTML file.\n\n :param write_to: File/Path to write the html file to.\n " ]
Please provide a description of the function:def get_unique_repositories(repo_list): unique_list = list() included = defaultdict(lambda: False) for repo in repo_list: if not included[repo.full_name]: unique_list.append(repo) included[repo.full...
[ "Method to create unique list of repositories from the list of\n repositories given.\n\n :param repo_list: List of repositories which might contain duplicates.\n :return: List of repositories with no duplicate in them.\n " ]
Please provide a description of the function:def minus(repo_list_a, repo_list_b): included = defaultdict(lambda: False) for repo in repo_list_b: included[repo.full_name] = True a_minus_b = list() for repo in repo_list_a: if not included[repo.full_name]:...
[ "Method to create a list of repositories such that the repository\n belongs to repo list a but not repo list b.\n\n In an ideal scenario we should be able to do this by set(a) - set(b)\n but as GithubRepositories have shown that set() on them is not reliable\n resort to this until it is ...
Please provide a description of the function:def __populate_repositories_of_interest(self, username): # Handle to the user to whom repositories need to be suggested. user = self.github.get_user(username) # Procure repositories starred by the user. self.user_starred_repositories...
[ "Method to populate repositories which will be used to suggest\n repositories for the user. For this purpose we use two kinds of\n repositories.\n\n 1. Repositories starred by user him/herself.\n 2. Repositories starred by the users followed by the user.\n\n :param username: Usern...
Please provide a description of the function:def __get_interests(self): # All repositories of interest. repos_of_interest = itertools.chain( self.user_starred_repositories, self.user_following_starred_repositories, ) # Extract descriptions out of reposit...
[ "Method to procure description of repositories the authenticated user\n is interested in.\n\n We currently attribute interest to:\n 1. The repositories the authenticated user has starred.\n 2. The repositories the users the authenticated user follows have\n starred.\n\n :re...
Please provide a description of the function:def __get_words_to_ignore(self): # Stop words in English. english_stopwords = stopwords.words("english") here = path.abspath(path.dirname(__file__)) # Languages in git repositories. git_languages = [] with open(path....
[ "Compiles list of all words to ignore.\n\n :return: List of words to ignore.\n " ]
Please provide a description of the function:def __clean_and_tokenize(self, doc_list): # Some repositories fill entire documentation in description. We ignore # such repositories for cleaner tokens. doc_list = filter( lambda x: x is not None and len(x) <= GitSuggest.MAX_DESC...
[ "Method to clean and tokenize the document list.\n\n :param doc_list: Document list to clean and tokenize.\n :return: Cleaned and tokenized document list.\n " ]
Please provide a description of the function:def __construct_lda_model(self): # Fetch descriptions of repos of interest to authenticated user. repos_of_interest = self.__get_interests() # Procure clean tokens from the descriptions. cleaned_tokens = self.__clean_and_tokenize(rep...
[ "Method to create LDA model to procure list of topics from.\n\n We do that by first fetching the descriptions of repositories user has\n shown interest in. We tokenize the hence fetched descriptions to\n procure list of cleaned tokens by dropping all the stop words and\n language names f...
Please provide a description of the function:def __get_query_for_repos(self, term_count=5): repo_query_terms = list() for term in self.lda_model.get_topic_terms(0, topn=term_count): repo_query_terms.append(self.lda_model.id2word[term[0]]) return " ".join(repo_query_terms)
[ "Method to procure query based on topics authenticated user is\n interested in.\n\n :param term_count: Count of terms in query.\n :return: Query string.\n " ]
Please provide a description of the function:def get_suggested_repositories(self): if self.suggested_repositories is None: # Procure repositories to suggest to user. repository_set = list() for term_count in range(5, 2, -1): query = self.__get_query_f...
[ "Method to procure suggested repositories for the user.\n\n :return: Iterator to procure suggested repositories for the user.\n " ]
Please provide a description of the function:def guess_type(s): sc = s.replace(',', '') # remove comma from potential numbers try: return int(sc) except ValueError: pass try: return float(sc) except ValueError: pass return s
[ " attempt to convert string value into numeric type " ]
Please provide a description of the function:def parse(self, node): self._attrs = {} vals = [] yielded = False for x in self._read_parts(node): if isinstance(x, Field): yielded = True x.attrs = self._attrs yield x ...
[ "\n Return generator yielding Field objects for a given node\n " ]
Please provide a description of the function:def parse(self, *nodes): for n in nodes: if not n.contents: continue row = self._parse(n) if not row.is_null: yield row
[ "\n Parse one or more `tr` nodes, yielding wikitables.Row objects\n " ]
Please provide a description of the function:def _find_header_flat(self): nodes = self._node.contents.filter_tags( matches=ftag('th'), recursive=False) if not nodes: return self._log('found header outside rows (%d <th> elements)' % len(nodes)) ret...
[ "\n Find header elements in a table, if possible. This case handles\n situations where '<th>' elements are not within a row('<tr>')\n " ]
Please provide a description of the function:def _find_header_row(self): th_max = 0 header_idx = 0 for idx, tr in enumerate(self._tr_nodes): th_count = len(tr.contents.filter_tags(matches=ftag('th'))) if th_count > th_max: th_max = th_count ...
[ "\n Evaluate all rows and determine header position, based on\n greatest number of 'th' tagged elements\n " ]
Please provide a description of the function:def _make_default_header(self): td_max = 0 for idx, tr in enumerate(self._tr_nodes): td_count = len(tr.contents.filter_tags(matches=ftag('td'))) if td_count > td_max: td_max = td_count self._log('crea...
[ "\n Return a generic placeholder header based on the tables column count\n " ]
Please provide a description of the function:def fetch_page(self, title, method='GET'): params = { 'prop': 'revisions', 'format': 'json', 'action': 'query', 'explaintext': '', 'titles': title, 'rvprop': 'cont...
[ " Query for page by title " ]
Please provide a description of the function:def print_stack(pid, include_greenlet=False, debugger=None, verbose=False): # TextIOWrapper of Python 3 is so strange. sys_stdout = getattr(sys.stdout, 'buffer', sys.stdout) sys_stderr = getattr(sys.stderr, 'buffer', sys.stderr) make_args = make_gdb_arg...
[ "Executes a file in a running Python process." ]
Please provide a description of the function:def cli_main(pid, include_greenlet, debugger, verbose): '''Print stack of python process. $ pystack <pid> ''' try: print_stack(pid, include_greenlet, debugger, verbose) except DebuggerNotFound as e: click.echo('DebuggerNotFound: %s' % e.a...
[]
Please provide a description of the function:def forward_algo(self,observations): # Store total number of observations total_stages = len(observations) total_stages = len(observations) # Alpha[i] stores the probability of reaching state 'i' in stage 'j' where 'j' is the iteration num...
[ " Finds the probability of an observation sequence for given model parameters\n\n **Arguments**:\n\n :param observations: The observation sequence, where each element belongs to 'observations' variable declared with __init__ object. \n :type observations: A list or tuple\n\n :return: The...
Please provide a description of the function:def viterbi(self,observations): # Find total states,observations total_stages = len(observations) num_states = len(self.states) # initialize data # Path stores the state sequence giving maximum probability old_path =...
[ " The probability of occurence of the observation sequence\n\n **Arguments**:\n\n :param observations: The observation sequence, where each element belongs to 'observations' variable declared with __init__ object. \n :type observations: A list or tuple\n\n :return: Returns a list of hidd...
Please provide a description of the function:def train_hmm(self,observation_list, iterations, quantities): obs_size = len(observation_list) prob = float('inf') q = quantities # Train the model 'iteration' number of times # store em_prob and trans_prob copies since you ...
[ " Runs the Baum Welch Algorithm and finds the new model parameters\n\n **Arguments**:\n\n :param observation_list: A nested list, or a list of lists \n :type observation_list: Contains a list multiple observation sequences.\n\n :param iterations: Maximum number of iterations for the al...
Please provide a description of the function:def log_prob(self,observations_list, quantities): prob = 0 for q,obs in enumerate(observations_list): temp,c_scale = self._alpha_cal(obs) prob = prob + -1 * quantities[q] * np.sum(np.log(c_scale)) return prob
[ " Finds Weighted log probability of a list of observation sequences\n\n **Arguments**:\n\n :param observation_list: A nested list, or a list of lists \n :type observation_list: Contains a list multiple observation sequences.\n\n :param quantities: Number of times, each corresponding it...
Please provide a description of the function:def __fetch_data(self, url): url += '&api_key=' + self.api_key try: response = urlopen(url) root = ET.fromstring(response.read()) except HTTPError as exc: root = ET.fromstring(exc.read()) raise ...
[ "\n helper function for fetching data given a request URL\n " ]
Please provide a description of the function:def _parse(self, date_str, format='%Y-%m-%d'): rv = pd.to_datetime(date_str, format=format) if hasattr(rv, 'to_pydatetime'): rv = rv.to_pydatetime() return rv
[ "\n helper function for parsing FRED date string into datetime\n " ]
Please provide a description of the function:def get_series_info(self, series_id): url = "%s/series?series_id=%s" % (self.root_url, series_id) root = self.__fetch_data(url) if root is None or not len(root): raise ValueError('No info exists for series id: ' + series_id) ...
[ "\n Get information about a series such as its title, frequency, observation start/end dates, units, notes, etc.\n\n Parameters\n ----------\n series_id : str\n Fred series id such as 'CPIAUCSL'\n\n Returns\n -------\n info : Series\n a pandas S...
Please provide a description of the function:def get_series(self, series_id, observation_start=None, observation_end=None, **kwargs): url = "%s/series/observations?series_id=%s" % (self.root_url, series_id) if observation_start is not None: observation_start = pd.to_datetime(observa...
[ "\n Get data for a Fred series id. This fetches the latest known data, and is equivalent to get_series_latest_release()\n\n Parameters\n ----------\n series_id : str\n Fred series id such as 'CPIAUCSL'\n observation_start : datetime or datetime-like str such as '7/1/201...
Please provide a description of the function:def get_series_first_release(self, series_id): df = self.get_series_all_releases(series_id) first_release = df.groupby('date').head(1) data = first_release.set_index('date')['value'] return data
[ "\n Get first-release data for a Fred series id. This ignores any revision to the data series. For instance,\n The US GDP for Q1 2014 was first released to be 17149.6, and then later revised to 17101.3, and 17016.0.\n This will ignore revisions after the first release.\n\n Parameters\n ...
Please provide a description of the function:def get_series_as_of_date(self, series_id, as_of_date): as_of_date = pd.to_datetime(as_of_date) df = self.get_series_all_releases(series_id) data = df[df['realtime_start'] <= as_of_date] return data
[ "\n Get latest data for a Fred series id as known on a particular date. This includes any revision to the data series\n before or on as_of_date, but ignores any revision on dates after as_of_date.\n\n Parameters\n ----------\n series_id : str\n Fred series id such as 'G...
Please provide a description of the function:def get_series_all_releases(self, series_id): url = "%s/series/observations?series_id=%s&realtime_start=%s&realtime_end=%s" % (self.root_url, series_id, ...
[ "\n Get all data for a Fred series id including first releases and all revisions. This returns a DataFrame\n with three columns: 'date', 'realtime_start', and 'value'. For instance, the US GDP for Q4 2013 was first released\n to be 17102.5 on 2014-01-30, and then revised to 17080.7 on 2014-02-2...
Please provide a description of the function:def get_series_vintage_dates(self, series_id): url = "%s/series/vintagedates?series_id=%s" % (self.root_url, series_id) root = self.__fetch_data(url) if root is None: raise ValueError('No vintage date exists for series id: ' + ser...
[ "\n Get a list of vintage dates for a series. Vintage dates are the dates in history when a\n series' data values were revised or new data values were released.\n\n Parameters\n ----------\n series_id : str\n Fred series id such as 'CPIAUCSL'\n\n Returns\n ...
Please provide a description of the function:def __do_series_search(self, url): root = self.__fetch_data(url) series_ids = [] data = {} num_results_returned = 0 # number of results returned in this HTTP request num_results_total = int(root.get('count')) # total numbe...
[ "\n helper function for making one HTTP request for data, and parsing the returned results into a DataFrame\n " ]
Please provide a description of the function:def __get_search_results(self, url, limit, order_by, sort_order, filter): order_by_options = ['search_rank', 'series_id', 'title', 'units', 'frequency', 'seasonal_adjustment', 'realtime_start', 'realtime_end', 'last_updated', ...
[ "\n helper function for getting search results up to specified limit on the number of results. The Fred HTTP API\n truncates to 1000 results per request, so this may issue multiple HTTP requests to obtain more available data.\n " ]
Please provide a description of the function:def search(self, text, limit=1000, order_by=None, sort_order=None, filter=None): url = "%s/series/search?search_text=%s&" % (self.root_url, quote_plus(text)) info = self.__get_search_results(url, li...
[ "\n Do a fulltext search for series in the Fred dataset. Returns information about matching series in a DataFrame.\n\n Parameters\n ----------\n text : str\n text to do fulltext search on, e.g., 'Real GDP'\n limit : int, optional\n limit the number of results...
Please provide a description of the function:def search_by_release(self, release_id, limit=0, order_by=None, sort_order=None, filter=None): url = "%s/release/series?release_id=%d" % (self.root_url, release_id) info = self.__get_search_results(url, limit, order_by, sort_order, filter) if...
[ "\n Search for series that belongs to a release id. Returns information about matching series in a DataFrame.\n\n Parameters\n ----------\n release_id : int\n release id, e.g., 151\n limit : int, optional\n limit the number of results to this value. If limit ...
Please provide a description of the function:def search_by_category(self, category_id, limit=0, order_by=None, sort_order=None, filter=None): url = "%s/category/series?category_id=%d&" % (self.root_url, category_id) info = self.__get_search_...
[ "\n Search for series that belongs to a category id. Returns information about matching series in a DataFrame.\n\n Parameters\n ----------\n category_id : int\n category id, e.g., 32145\n limit : int, optional\n limit the number of results to this value. If l...
Please provide a description of the function:def init(self, name, subject, expires=None, algorithm=None, parent=None, pathlen=None, issuer_url=None, issuer_alt_name='', crl_url=None, ocsp_url=None, ca_issuer_url=None, ca_crl_url=None, ca_ocsp_url=None, name_constraints=None, passw...
[ "Create a new certificate authority.\n\n Parameters\n ----------\n\n name : str\n The name of the CA. This is a human-readable string and is used for administrative purposes only.\n subject : dict or str or :py:class:`~django_ca.subject.Subject`\n Subject string, e....
Please provide a description of the function:def sign_cert(self, ca, csr, expires=None, algorithm=None, subject=None, cn_in_san=True, csr_format=Encoding.PEM, subject_alternative_name=None, key_usage=None, extended_key_usage=None, tls_feature=None, ocsp_no_check=False, extra_extensio...
[ "Create a signed certificate from a CSR.\n\n **PLEASE NOTE:** This function creates the raw certificate and is usually not invoked directly. It is\n called by :py:func:`Certificate.objects.init() <django_ca.managers.CertificateManager.init>`, which\n passes along all parameters unchanged and sa...
Please provide a description of the function:def init(self, ca, csr, **kwargs): c = self.model(ca=ca) c.x509, csr = self.sign_cert(ca, csr, **kwargs) c.csr = csr.public_bytes(Encoding.PEM).decode('utf-8') c.save() post_issue_cert.send(sender=self.model, cert=c) ...
[ "Create a signed certificate from a CSR and store it to the database.\n\n All parameters are passed on to :py:func:`Certificate.objects.sign_cert()\n <django_ca.managers.CertificateManager.sign_cert>`.\n " ]
Please provide a description of the function:def download_bundle_view(self, request, pk): return self._download_response(request, pk, bundle=True)
[ "A view that allows the user to download a certificate bundle in PEM format." ]
Please provide a description of the function:def get_actions(self, request): actions = super(CertificateMixin, self).get_actions(request) actions.pop('delete_selected', '') return actions
[ "Disable the \"delete selected\" admin action.\n\n Otherwise the action is present even though has_delete_permission is False, it just doesn't\n work.\n " ]
Please provide a description of the function:def get_cert_profile_kwargs(name=None): if name is None: name = ca_settings.CA_DEFAULT_PROFILE profile = deepcopy(ca_settings.CA_PROFILES[name]) kwargs = { 'cn_in_san': profile['cn_in_san'], 'subject': get_default_subject(name=name)...
[ "Get kwargs suitable for get_cert X509 keyword arguments from the given profile." ]
Please provide a description of the function:def format_name(subject): if isinstance(subject, x509.Name): subject = [(OID_NAME_MAPPINGS[s.oid], s.value) for s in subject] return '/%s' % ('/'.join(['%s=%s' % (force_text(k), force_text(v)) for k, v in subject]))
[ "Convert a subject into the canonical form for distinguished names.\n\n This function does not take care of sorting the subject in any meaningful order.\n\n Examples::\n\n >>> format_name([('CN', 'example.com'), ])\n '/CN=example.com'\n >>> format_name([('CN', 'example.com'), ('O', \"My O...
Please provide a description of the function:def format_general_name(name): if isinstance(name, x509.DirectoryName): value = format_name(name.value) else: value = name.value return '%s:%s' % (SAN_NAME_MAPPINGS[type(name)], value)
[ "Format a single general name.\n\n >>> import ipaddress\n >>> format_general_name(x509.DNSName('example.com'))\n 'DNS:example.com'\n >>> format_general_name(x509.IPAddress(ipaddress.IPv4Address('127.0.0.1')))\n 'IP:127.0.0.1'\n " ]
Please provide a description of the function:def add_colons(s): return ':'.join([s[i:i + 2] for i in range(0, len(s), 2)])
[ "Add colons after every second digit.\n\n This function is used in functions to prettify serials.\n\n >>> add_colons('teststring')\n 'te:st:st:ri:ng'\n " ]
Please provide a description of the function:def int_to_hex(i): s = hex(i)[2:].upper() if six.PY2 is True and isinstance(i, long): # pragma: only py2 # NOQA # Strip the "L" suffix, since hex(1L) -> 0x1L. # NOTE: Do not convert to int earlier. int(<very-large-long>) is still long s...
[ "Create a hex-representation of the given serial.\n\n >>> int_to_hex(12345678)\n 'BC:61:4E'\n " ]
Please provide a description of the function:def parse_name(name): name = name.strip() if not name: # empty subjects are ok return [] try: items = [(NAME_CASE_MAPPINGS[t[0].upper()], force_text(t[2])) for t in NAME_RE.findall(name)] except KeyError as e: raise ValueError('...
[ "Parses a subject string as used in OpenSSLs command line utilities.\n\n The ``name`` is expected to be close to the subject format commonly used by OpenSSL, for example\n ``/C=AT/L=Vienna/CN=example.com/emailAddress=user@example.com``. The function does its best to be lenient\n on deviations from the form...
Please provide a description of the function:def x509_name(name): if isinstance(name, six.string_types): name = parse_name(name) return x509.Name([x509.NameAttribute(NAME_OID_MAPPINGS[typ], force_text(value)) for typ, value in name])
[ "Parses a subject into a :py:class:`x509.Name <cg:cryptography.x509.Name>`.\n\n If ``name`` is a string, :py:func:`parse_name` is used to parse it.\n\n >>> x509_name('/C=AT/CN=example.com')\n <Name(C=AT,CN=example.com)>\n >>> x509_name([('C', 'AT'), ('CN', 'example.com')])\n <Name(C=AT,CN=example.com...
Please provide a description of the function:def validate_email(addr): if '@' not in addr: raise ValueError('Invalid email address: %s' % addr) node, domain = addr.split('@', 1) try: domain = idna.encode(force_text(domain)) except idna.core.IDNAError: raise ValueError('Inva...
[ "Validate an email address.\n\n This function raises ``ValueError`` if the email address is not valid.\n\n >>> validate_email('foo@bar.com')\n 'foo@bar.com'\n >>> validate_email('foo@bar com')\n Traceback (most recent call last):\n ...\n ValueError: Invalid domain: bar com\n\n " ]
Please provide a description of the function:def parse_general_name(name): name = force_text(name) typ = None match = GENERAL_NAME_RE.match(name) if match is not None: typ, name = match.groups() typ = typ.lower() if typ is None: if re.match('[a-z0-9]{2,}://', name): # ...
[ "Parse a general name from user input.\n\n This function will do its best to detect the intended type of any value passed to it:\n\n >>> parse_general_name('example.com')\n <DNSName(value='example.com')>\n >>> parse_general_name('*.example.com')\n <DNSName(value='*.example.com')>\n >>> parse_gener...
Please provide a description of the function:def parse_hash_algorithm(value=None): if value is None: return ca_settings.CA_DIGEST_ALGORITHM elif isinstance(value, type) and issubclass(value, hashes.HashAlgorithm): return value() elif isinstance(value, hashes.HashAlgorithm): retu...
[ "Parse a hash algorithm value.\n\n The most common use case is to pass a str naming a class in\n :py:mod:`~cg:cryptography.hazmat.primitives.hashes`.\n\n For convenience, passing ``None`` will return the value of :ref:`CA_DIGEST_ALGORITHM\n <settings-ca-digest-algorithm>`, and passing an\n :py:class:...
Please provide a description of the function:def parse_encoding(value=None): if value is None: return ca_settings.CA_DEFAULT_ENCODING elif isinstance(value, Encoding): return value elif isinstance(value, six.string_types): if value == 'ASN1': value = 'DER' t...
[ "Parse a value to a valid encoding.\n\n This function accepts either a member of\n :py:class:`~cg:cryptography.hazmat.primitives.serialization.Encoding` or a string describing a member. If\n no value is passed, it will assume ``PEM`` as a default value. Note that ``\"ASN1\"`` is treated as an alias\n fo...
Please provide a description of the function:def parse_key_curve(value=None): if isinstance(value, ec.EllipticCurve): return value # name was already parsed if value is None: return ca_settings.CA_DEFAULT_ECC_CURVE curve = getattr(ec, value.strip(), type) if not issubclass(curve, ...
[ "Parse an elliptic curve value.\n\n This function uses a value identifying an elliptic curve to return an\n :py:class:`~cg:cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve` instance. The name must match a\n class name of one of the classes named under \"Elliptic Curves\" in\n :any:`cg:hazmat/p...
Please provide a description of the function:def get_cert_builder(expires): now = datetime.utcnow().replace(second=0, microsecond=0) if expires is None: expires = get_expires(expires, now=now) expires = expires.replace(second=0, microsecond=0) builder = x509.CertificateBuilder() build...
[ "Get a basic X509 cert builder object.\n\n Parameters\n ----------\n\n expires : datetime\n When this certificate will expire.\n " ]
Please provide a description of the function:def wrap_file_exceptions(): try: yield except (PermissionError, FileNotFoundError): # pragma: only py3 # In py3, we want to raise Exception unchanged, so there would be no need for this block. # BUT (IOError, OSError) - see below - also ...
[ "Contextmanager to wrap file exceptions into identicaly exceptions in py2 and py3.\n\n This should be removed once py2 support is dropped.\n " ]
Please provide a description of the function:def read_file(path): if os.path.isabs(path): with wrap_file_exceptions(): with open(path, 'rb') as stream: return stream.read() with wrap_file_exceptions(): stream = ca_storage.open(path) try: return stre...
[ "Read the file from the given path.\n\n If ``path`` is an absolute path, reads a file from the local filesystem. For relative paths, read the file\n using the storage backend configured using :ref:`CA_FILE_STORAGE <settings-ca-file-storage>`.\n " ]
Please provide a description of the function:def get_extension_name(ext): # In cryptography 2.2, SCTs return "Unknown OID" if ext.oid == ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS: return 'SignedCertificateTimestampList' # Until at least cryptography 2.6.1, PrecertPoison has no name ...
[ "Function to get the name of an extension." ]
Please provide a description of the function:def shlex_split(s, sep): lex = shlex.shlex(s, posix=True) lex.whitespace = sep lex.whitespace_split = True return [l for l in lex]
[ "Split a character on the given set of characters.\n\n Example::\n\n >>> shlex_split('foo,bar', ', ')\n ['foo', 'bar']\n >>> shlex_split('foo\\\\\\\\,bar1', ',') # escape a separator\n ['foo,bar1']\n >>> shlex_split('\"foo,bar\", bla', ', ')\n ['foo,bar', 'bla']\n ...
Please provide a description of the function:def get_revocation_reason(self): if self.revoked is False: return if self.revoked_reason == '' or self.revoked_reason is None: return x509.ReasonFlags.unspecified else: return getattr(x509.ReasonFlags, sel...
[ "Get the revocation reason of this certificate." ]
Please provide a description of the function:def get_revocation_time(self): if self.revoked is False: return if timezone.is_aware(self.revoked_date): # convert datetime object to UTC and make it naive return timezone.make_naive(self.revoked_date, pytz.utc) ...
[ "Get the revocation time as naive datetime.\n\n Note that this method is only used by cryptography>=2.4.\n " ]
Please provide a description of the function:def x509(self): if self._x509 is None: backend = default_backend() self._x509 = x509.load_pem_x509_certificate(force_bytes(self.pub), backend) return self._x509
[ "The underlying :py:class:`cg:cryptography.x509.Certificate`." ]
Please provide a description of the function:def issuer(self): return Subject([(s.oid, s.value) for s in self.x509.issuer])
[ "The certificate issuer field as :py:class:`~django_ca.subject.Subject`." ]
Please provide a description of the function:def subject(self): return Subject([(s.oid, s.value) for s in self.x509.subject])
[ "The certificates subject as :py:class:`~django_ca.subject.Subject`." ]
Please provide a description of the function:def authority_key_identifier(self): try: ext = self.x509.extensions.get_extension_for_oid(ExtensionOID.AUTHORITY_KEY_IDENTIFIER) except x509.ExtensionNotFound: return None return AuthorityKeyIdentifier(ext)
[ "The :py:class:`~django_ca.extensions.AuthorityKeyIdentifier` extension, or ``None`` if it doesn't\n exist." ]
Please provide a description of the function:def key_usage(self): try: ext = self.x509.extensions.get_extension_for_oid(ExtensionOID.KEY_USAGE) except x509.ExtensionNotFound: return None return KeyUsage(ext)
[ "The :py:class:`~django_ca.extensions.KeyUsage` extension, or ``None`` if it doesn't exist." ]
Please provide a description of the function:def extended_key_usage(self): try: ext = self.x509.extensions.get_extension_for_oid(ExtensionOID.EXTENDED_KEY_USAGE) except x509.ExtensionNotFound: return None return ExtendedKeyUsage(ext)
[ "The :py:class:`~django_ca.extensions.ExtendedKeyUsage` extension, or ``None`` if it doesn't\n exist." ]
Please provide a description of the function:def subject_key_identifier(self): try: ext = self.x509.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_KEY_IDENTIFIER) except x509.ExtensionNotFound: return None return SubjectKeyIdentifier(ext)
[ "The :py:class:`~django_ca.extensions.SubjectKeyIdentifier` extension, or ``None`` if it doesn't\n exist." ]
Please provide a description of the function:def tls_feature(self): try: ext = self.x509.extensions.get_extension_for_oid(ExtensionOID.TLS_FEATURE) except x509.ExtensionNotFound: return None return TLSFeature(ext)
[ "The :py:class:`~django_ca.extensions.TLSFeature` extension, or ``None`` if it doesn't exist." ]
Please provide a description of the function:def get_authority_key_identifier(self): try: ski = self.x509.extensions.get_extension_for_class(x509.SubjectKeyIdentifier) except x509.ExtensionNotFound: return x509.AuthorityKeyIdentifier.from_issuer_public_key(self.x509.pub...
[ "Return the AuthorityKeyIdentifier extension used in certificates signed by this CA." ]
Please provide a description of the function:def get_crl(self, expires=86400, encoding=None, algorithm=None, password=None, scope=None, **kwargs): if scope is not None and scope not in ['ca', 'user', 'attribute']: raise ValueError('Scope must be either None, "ca", "user" or "attribute"') ...
[ "Generate a Certificate Revocation List (CRL).\n\n The ``full_name`` and ``relative_name`` parameters describe how to retrieve the CRL and are used in\n the `Issuing Distribution Point extension <https://tools.ietf.org/html/rfc5280.html#section-5.2.5>`_.\n The former defaults to the ``crl_url``...
Please provide a description of the function:def pathlen(self): try: ext = self.x509.extensions.get_extension_for_oid(ExtensionOID.BASIC_CONSTRAINTS) except x509.ExtensionNotFound: # pragma: no cover - extension should always be present return None return ext.v...
[ "The ``pathlen`` attribute of the ``BasicConstraints`` extension (either an ``int`` or ``None``)." ]
Please provide a description of the function:def max_pathlen(self): pathlen = self.pathlen if self.parent is None: return pathlen max_parent = self.parent.max_pathlen if max_parent is None: return pathlen elif pathlen is None: retur...
[ "The maximum pathlen for any intermediate CAs signed by this CA.\n\n This value is either ``None``, if this and all parent CAs don't have a ``pathlen`` attribute, or an\n ``int`` if any parent CA has the attribute.\n " ]
Please provide a description of the function:def bundle(self): ca = self bundle = [ca] while ca.parent is not None: bundle.append(ca.parent) ca = ca.parent return bundle
[ "A list of any parent CAs, including this CA.\n\n The list is ordered so the Root CA will be the first.\n " ]
Please provide a description of the function:def valid(self): now = timezone.now() return self.filter(revoked=False, expires__gt=now, valid_from__lt=now)
[ "Return valid certificates." ]
Please provide a description of the function:def as_extension(self): return x509.extensions.Extension(oid=self.oid, critical=self.critical, value=self.extension_type)
[ "This extension as :py:class:`~cg:cryptography.x509.ExtensionType`." ]
Please provide a description of the function:def add_algorithm(self, parser): help = 'The HashAlgorithm that will be used to generate the signature (default: %(default)s).' % { 'default': ca_settings.CA_DIGEST_ALGORITHM.name, } parser.add_argument( '--algorithm', metav...
[ "Add the --algorithm option." ]
Please provide a description of the function:def add_format(self, parser, default=Encoding.PEM, help_text=None, opts=None): if opts is None: opts = ['-f', '--format'] if help_text is None: help_text = 'The format to use ("ASN1" is an alias for "DER", default: %(default)...
[ "Add the --format option." ]
Please provide a description of the function:def process_module(self, node): ''' process a module ''' for listing in self.config.fileperms_ignore_paths: if node.file.split('{0}/'.format(os.getcwd()))[-1] in glob.glob(listing): # File is ignored, no checking s...
[]
Please provide a description of the function:def _parse_requirements_file(requirements_file): ''' Parse requirements.txt and return list suitable for passing to ``install_requires`` parameter in ``setup()``. ''' parsed_requirements = [] with open(requirements_file) as rfh: for line in rf...
[]
Please provide a description of the function:def _release_version(): ''' Returns release version ''' with io.open(os.path.join(SETUP_DIRNAME, 'saltpylint', 'version.py'), encoding='utf-8') as fh_: exec_locals = {} exec_globals = {} contents = fh_.read() if not isinstance(...
[]
Please provide a description of the function:def process_module(self, node): ''' process a module ''' # Patch lib2to3.fixer_util.touch_import! fixer_util.touch_import = salt_lib2to3_touch_import flags = {} if self.config.modernize_print_function: fl...
[]
Please provide a description of the function:def visit_functiondef(self, node): ''' Verifies no logger statements inside __virtual__ ''' if (not isinstance(node, astroid.FunctionDef) or node.is_method() or node.type != 'function' or not node.body ...
[]
Please provide a description of the function:def process_module(self, node): ''' process a module the module's content is accessible via node.file_stream object ''' pep263 = re.compile(six.b(self.RE_PEP263)) try: file_stream = node.file_stream except...
[]
Please provide a description of the function:def get_versions(source): tree = compiler.parse(source) checker = compiler.walk(tree, NodeChecker()) return checker.vers
[ "Return information about the Python versions required for specific features.\n\n The return value is a dictionary with keys as a version number as a tuple\n (for example Python 2.6 is (2,6)) and the value are a list of features that\n require the indicated Python version.\n " ]
Please provide a description of the function:def register(linter): '''required method to auto register this checker ''' linter.register_checker(StringCurlyBracesFormatIndexChecker(linter)) linter.register_checker(StringLiteralChecker(linter))
[]
Please provide a description of the function:def process_non_raw_string_token(self, prefix, string_body, start_row): ''' check for bad escapes in a non-raw string. prefix: lowercase string of eg 'ur' string prefix markers. string_body: the un-parsed body of the string, not including the...
[]
Please provide a description of the function:def register(linter): ''' Required method to auto register this checker ''' linter.register_checker(ResourceLeakageChecker(linter)) linter.register_checker(BlacklistedImportsChecker(linter)) linter.register_checker(MovedTestCaseClassChecker(linter)) ...
[]
Please provide a description of the function:def visit_import(self, node): '''triggered when an import statement is seen''' module_filename = node.root().file if fnmatch.fnmatch(module_filename, '__init__.py*') and \ not fnmatch.fnmatch(module_filename, 'test_*.py*'): ...
[]