Search is not available for this dataset
text stringlengths 75 104k |
|---|
def sign(self, pkey, digest):
"""
Sign the certificate with this key and digest type.
:param pkey: The key to sign with.
:type pkey: :py:class:`PKey`
:param digest: The name of the message digest to use.
:type digest: :py:class:`bytes`
:return: :py:data:`None`
... |
def get_signature_algorithm(self):
"""
Return the signature algorithm used in the certificate.
:return: The name of the algorithm.
:rtype: :py:class:`bytes`
:raises ValueError: If the signature algorithm is undefined.
.. versionadded:: 0.13
"""
algor = ... |
def digest(self, digest_name):
"""
Return the digest of the X509 object.
:param digest_name: The name of the digest algorithm to use.
:type digest_name: :py:class:`bytes`
:return: The digest of the object, formatted as
:py:const:`b":"`-delimited hex pairs.
:... |
def set_serial_number(self, serial):
"""
Set the serial number of the certificate.
:param serial: The new serial number.
:type serial: :py:class:`int`
:return: :py:data`None`
"""
if not isinstance(serial, _integer_types):
raise TypeError("serial must... |
def get_serial_number(self):
"""
Return the serial number of this certificate.
:return: The serial number.
:rtype: int
"""
asn1_serial = _lib.X509_get_serialNumber(self._x509)
bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL)
try:
... |
def gmtime_adj_notAfter(self, amount):
"""
Adjust the time stamp on which the certificate stops being valid.
:param int amount: The number of seconds by which to adjust the
timestamp.
:return: ``None``
"""
if not isinstance(amount, int):
raise Typ... |
def gmtime_adj_notBefore(self, amount):
"""
Adjust the timestamp on which the certificate starts being valid.
:param amount: The number of seconds by which to adjust the timestamp.
:return: ``None``
"""
if not isinstance(amount, int):
raise TypeError("amount ... |
def has_expired(self):
"""
Check whether the certificate has expired.
:return: ``True`` if the certificate has expired, ``False`` otherwise.
:rtype: bool
"""
time_string = _native(self.get_notAfter())
not_after = datetime.datetime.strptime(time_string, "%Y%m%d%H%... |
def get_issuer(self):
"""
Return the issuer of this certificate.
This creates a new :class:`X509Name` that wraps the underlying issuer
name field on the certificate. Modifying it will modify the underlying
certificate, and will have the effect of modifying any other
:cla... |
def set_issuer(self, issuer):
"""
Set the issuer of this certificate.
:param issuer: The issuer.
:type issuer: :py:class:`X509Name`
:return: ``None``
"""
self._set_name(_lib.X509_set_issuer_name, issuer)
self._issuer_invalidator.clear() |
def get_subject(self):
"""
Return the subject of this certificate.
This creates a new :class:`X509Name` that wraps the underlying subject
name field on the certificate. Modifying it will modify the underlying
certificate, and will have the effect of modifying any other
:... |
def set_subject(self, subject):
"""
Set the subject of this certificate.
:param subject: The subject.
:type subject: :py:class:`X509Name`
:return: ``None``
"""
self._set_name(_lib.X509_set_subject_name, subject)
self._subject_invalidator.clear() |
def add_extensions(self, extensions):
"""
Add extensions to the certificate.
:param extensions: The extensions to add.
:type extensions: An iterable of :py:class:`X509Extension` objects.
:return: ``None``
"""
for ext in extensions:
if not isinstance(e... |
def get_extension(self, index):
"""
Get a specific extension of the certificate by index.
Extensions on a certificate are kept in order. The index
parameter selects which extension will be returned.
:param int index: The index of the extension to retrieve.
:return: The ... |
def add_cert(self, cert):
"""
Adds a trusted certificate to this store.
Adding a certificate with this method adds this certificate as a
*trusted* certificate.
:param X509 cert: The certificate to add to this store.
:raises TypeError: If the certificate is not an :clas... |
def add_crl(self, crl):
"""
Add a certificate revocation list to this store.
The certificate revocation lists added to a store will only be used if
the associated flags are configured to check certificate revocation
lists.
.. versionadded:: 16.1.0
:param CRL cr... |
def set_time(self, vfy_time):
"""
Set the time against which the certificates are verified.
Normally the current time is used.
.. note::
For example, you can determine if a certificate was valid at a given
time.
.. versionadded:: 17.0.0
:param dat... |
def _init(self):
"""
Set up the store context for a subsequent verification operation.
Calling this method more than once without first calling
:meth:`_cleanup` will leak memory.
"""
ret = _lib.X509_STORE_CTX_init(
self._store_ctx, self._store._store, self._c... |
def _exception_from_context(self):
"""
Convert an OpenSSL native context error failure into a Python
exception.
When a call to native OpenSSL X509_verify_cert fails, additional
information about the failure can be obtained from the store context.
"""
errors = [
... |
def verify_certificate(self):
"""
Verify a certificate in a context.
.. versionadded:: 0.15
:raises X509StoreContextError: If an error occurred when validating a
certificate in the context. Sets ``certificate`` attribute to
indicate which certificate caused the erro... |
def set_serial(self, hex_str):
"""
Set the serial number.
The serial number is formatted as a hexadecimal number encoded in
ASCII.
:param bytes hex_str: The new serial number.
:return: ``None``
"""
bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free)
... |
def get_serial(self):
"""
Get the serial number.
The serial number is formatted as a hexadecimal number encoded in
ASCII.
:return: The serial number.
:rtype: bytes
"""
bio = _new_mem_buf()
asn1_int = _lib.X509_REVOKED_get0_serialNumber(self._rev... |
def set_reason(self, reason):
"""
Set the reason of this revocation.
If :data:`reason` is ``None``, delete the reason instead.
:param reason: The reason string.
:type reason: :class:`bytes` or :class:`NoneType`
:return: ``None``
.. seealso::
:meth... |
def get_reason(self):
"""
Get the reason of this revocation.
:return: The reason, or ``None`` if there is none.
:rtype: bytes or NoneType
.. seealso::
:meth:`all_reasons`, which gives you a list of all supported
reasons this method might return.
... |
def set_rev_date(self, when):
"""
Set the revocation timestamp.
:param bytes when: The timestamp of the revocation,
as ASN.1 TIME.
:return: ``None``
"""
dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
return _set_asn1_time(dt, when) |
def to_cryptography(self):
"""
Export as a ``cryptography`` CRL.
:rtype: ``cryptography.x509.CertificateRevocationList``
.. versionadded:: 17.1.0
"""
from cryptography.hazmat.backends.openssl.x509 import (
_CertificateRevocationList
)
backend... |
def from_cryptography(cls, crypto_crl):
"""
Construct based on a ``cryptography`` *crypto_crl*.
:param crypto_crl: A ``cryptography`` certificate revocation list
:type crypto_crl: ``cryptography.x509.CertificateRevocationList``
:rtype: CRL
.. versionadded:: 17.1.0
... |
def get_revoked(self):
"""
Return the revocations in this certificate revocation list.
These revocations will be provided by value, not by reference.
That means it's okay to mutate them: it won't affect this CRL.
:return: The revocations in this CRL.
:rtype: :class:`tup... |
def add_revoked(self, revoked):
"""
Add a revoked (by value not reference) to the CRL structure
This revocation will be added by value, not by reference. That
means it's okay to mutate it after adding: it won't affect
this CRL.
:param Revoked revoked: The new revocation... |
def get_issuer(self):
"""
Get the CRL's issuer.
.. versionadded:: 16.1.0
:rtype: X509Name
"""
_issuer = _lib.X509_NAME_dup(_lib.X509_CRL_get_issuer(self._crl))
_openssl_assert(_issuer != _ffi.NULL)
_issuer = _ffi.gc(_issuer, _lib.X509_NAME_free)
... |
def sign(self, issuer_cert, issuer_key, digest):
"""
Sign the CRL.
Signing a CRL enables clients to associate the CRL itself with an
issuer. Before a CRL is meaningful to other OpenSSL functions, it must
be signed by an issuer.
This method implicitly sets the issuer's n... |
def export(self, cert, key, type=FILETYPE_PEM, days=100,
digest=_UNSPECIFIED):
"""
Export the CRL as a string.
:param X509 cert: The certificate used to sign the CRL.
:param PKey key: The key used to sign the CRL.
:param int type: The export format, either :data:`... |
def get_type_name(self):
"""
Returns the type name of the PKCS7 structure
:return: A string with the typename
"""
nid = _lib.OBJ_obj2nid(self._pkcs7.type)
string_type = _lib.OBJ_nid2sn(nid)
return _ffi.string(string_type) |
def set_certificate(self, cert):
"""
Set the certificate in the PKCS #12 structure.
:param cert: The new certificate, or :py:const:`None` to unset it.
:type cert: :py:class:`X509` or :py:const:`None`
:return: ``None``
"""
if not isinstance(cert, X509):
... |
def set_privatekey(self, pkey):
"""
Set the certificate portion of the PKCS #12 structure.
:param pkey: The new private key, or :py:const:`None` to unset it.
:type pkey: :py:class:`PKey` or :py:const:`None`
:return: ``None``
"""
if not isinstance(pkey, PKey):
... |
def set_ca_certificates(self, cacerts):
"""
Replace or set the CA certificates within the PKCS12 object.
:param cacerts: The new CA certificates, or :py:const:`None` to unset
them.
:type cacerts: An iterable of :py:class:`X509` or :py:const:`None`
:return: ``None``
... |
def set_friendlyname(self, name):
"""
Set the friendly name in the PKCS #12 structure.
:param name: The new friendly name, or :py:const:`None` to unset.
:type name: :py:class:`bytes` or :py:const:`None`
:return: ``None``
"""
if name is None:
self._fr... |
def export(self, passphrase=None, iter=2048, maciter=1):
"""
Dump a PKCS12 object as a string.
For more information, see the :c:func:`PKCS12_create` man page.
:param passphrase: The passphrase used to encrypt the structure. Unlike
some other passphrase arguments, this *must... |
def sign(self, pkey, digest):
"""
Sign the certificate request with this key and digest type.
:param pkey: The private key to sign with.
:type pkey: :py:class:`PKey`
:param digest: The message digest to use.
:type digest: :py:class:`bytes`
:return: ``None``
... |
def verify(self, key):
"""
Verifies a signature on a certificate request.
:param PKey key: The public key that signature is supposedly from.
:return: ``True`` if the signature is correct.
:rtype: bool
:raises OpenSSL.crypto.Error: If the signature is invalid, or there ... |
def b64_encode(self):
"""
Generate a base64 encoded representation of this SPKI object.
:return: The base64 encoded string.
:rtype: :py:class:`bytes`
"""
encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)
result = _ffi.string(encoded)
_lib.OPENSSL_free(e... |
def get_pubkey(self):
"""
Get the public key of this certificate.
:return: The public key.
:rtype: :py:class:`PKey`
"""
pkey = PKey.__new__(PKey)
pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki)
_openssl_assert(pkey._pkey != _ffi.NULL)
pkey.... |
def set_pubkey(self, pkey):
"""
Set the public key of the certificate
:param pkey: The public key
:return: ``None``
"""
set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey)
_openssl_assert(set_result == 1) |
def exception_from_error_queue(exception_type):
"""
Convert an OpenSSL library failure into a Python exception.
When a call to the native OpenSSL library fails, this is usually signalled
by the return value, and an error code is stored in an error queue
associated with the current thread. The err l... |
def native(s):
"""
Convert :py:class:`bytes` or :py:class:`unicode` to the native
:py:class:`str` type, using UTF-8 encoding if conversion is necessary.
:raise UnicodeError: The input string is not UTF-8 decodeable.
:raise TypeError: The input is neither :py:class:`bytes` nor
:py:class:`un... |
def path_string(s):
"""
Convert a Python string to a :py:class:`bytes` string identifying the same
path and which can be passed into an OpenSSL API accepting a filename.
:param s: An instance of :py:class:`bytes` or :py:class:`unicode`.
:return: An instance of :py:class:`bytes`.
"""
if isi... |
def text_to_bytes_and_warn(label, obj):
"""
If ``obj`` is text, emit a warning that it should be bytes instead and try
to convert it to bytes automatically.
:param str label: The name of the parameter from which ``obj`` was taken
(so a developer can easily find the source of the problem and cor... |
def add(buffer, entropy):
"""
Mix bytes from *string* into the PRNG state.
The *entropy* argument is (the lower bound of) an estimate of how much
randomness is contained in *string*, measured in bytes.
For more information, see e.g. :rfc:`1750`.
This function is only relevant if you are forki... |
def accept(self):
"""
This is the other part of the shutdown() workaround.
Since servers create new sockets, we have to infect
them with our magic. :)
"""
c, a = self.__dict__["conn"].accept()
return (SSLWrapper(c), a) |
def setup(self):
"""
We need to use socket._fileobject Because SSL.Connection
doesn't have a 'dup'. Not exactly sure WHY this is, but
this is backed up by comments in socket.py and SSL/connection.c
"""
self.connection = self.request # for doPOST
self.rfile = sock... |
def main():
"""
Run an SNI-enabled server which selects between a few certificates in a
C{dict} based on the handshake request it receives from a client.
"""
port = socket()
port.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
port.bind(('', 8443))
port.listen(3)
print('Accepting...', end="... |
def _print_token_factory(col):
"""Internal helper to provide color names."""
def _helper(msg):
style = style_from_dict({
Token.Color: col,
})
tokens = [
(Token.Color, msg)
]
print_tokens(tokens, style=style)
def _helper_no_terminal(msg):
... |
def get_service_metadata(self):
"""
Return extra config options to be passed to the TrelloIssue class
"""
return {
'import_labels_as_tags':
self.config.get('import_labels_as_tags', False, asbool),
'label_template':
self.config.get('label_te... |
def issues(self):
"""
Returns a list of dicts representing issues from a remote service.
"""
for board in self.get_boards():
for lst in self.get_lists(board['id']):
listextra = dict(boardname=board['name'], listname=lst['name'])
for card in sel... |
def annotations(self, card_json):
""" A wrapper around get_comments that build the taskwarrior
annotations. """
comments = self.get_comments(card_json['id'])
annotations = self.build_annotations(
((c['memberCreator']['username'], c['data']['text']) for c in comments),
... |
def get_boards(self):
"""
Get the list of boards to pull cards from. If the user gave a value to
trello.include_boards use that, otherwise ask the Trello API for the
user's boards.
"""
if 'include_boards' in self.config:
for boardid in self.config.get('includ... |
def get_lists(self, board):
"""
Returns a list of the filtered lists for the given board
This filters the trello lists according to the configuration values of
trello.include_lists and trello.exclude_lists.
"""
lists = self.api_request(
"/1/boards/{board_id}/l... |
def get_cards(self, list_id):
""" Returns an iterator for the cards in a given list, filtered
according to configuration values of trello.only_if_assigned and
trello.also_unassigned """
params = {'fields': 'name,idShort,shortLink,shortUrl,url,labels,due'}
member = self.config.get... |
def get_comments(self, card_id):
""" Returns an iterator for the comments on a certain card. """
params = {'filter': 'commentCard', 'memberCreator_fields': 'username'}
comments = self.api_request(
"/1/cards/{card_id}/actions".format(card_id=card_id),
**params)
for... |
def api_request(self, url, **params):
"""
Make a trello API request. This takes an absolute url (without protocol
and host) and a list of argumnets and return a GET request with the
key and token from the configuration
"""
params['key'] = self.config.get('api_key'),
... |
def get_issues(self, repo, keys):
""" Grab all the issues """
key1, key2 = keys
key3 = key1[:-1] # Just the singular form of key1
url = self.base_url + "/api/0/" + repo + "/" + key1
response = self.session.get(url, params=dict(status='Open'))
if not bool(response):
... |
def get_issue_generator(self, user_id, project_id, project_name):
"""
Approach:
1. Get user ID from bugwarriorrc file
2. Get list of tickets from /user-tasks for a given project
3. For each ticket/task returned from #2, get ticket/task info and
check if logged-in user... |
def _api_url(self, path, **context):
""" Build the full url to the API endpoint """
if self.host == 'github.com':
baseurl = "https://api.github.com"
else:
baseurl = "https://{}/api/v3".format(self.host)
return baseurl + path.format(**context) |
def get_query(self, query):
"""Run a generic issue/PR query"""
url = self._api_url(
"/search/issues?q={query}&per_page=100", query=query)
return self._getter(url, subkey='items') |
def _getter(self, url, subkey=None):
""" Pagination utility. Obnoxious. """
kwargs = {}
if 'basic' in self.auth:
kwargs['auth'] = self.auth['basic']
results = []
link = dict(next=url)
while 'next' in link:
response = self.session.get(link['next... |
def _link_field_to_dict(field):
""" Utility for ripping apart github's Link header field.
It's kind of ugly.
"""
if not field:
return dict()
return dict([
(
part.split('; ')[1][5:-1],
part.split('; ')[0][1:-1],
... |
def get_owned_repo_issues(self, tag):
""" Grab all the issues """
issues = {}
for issue in self.client.get_issues(*tag.split('/')):
issues[issue['url']] = (tag, issue)
return issues |
def get_query(self, query):
""" Grab all issues matching a github query """
issues = {}
for issue in self.client.get_query(query):
url = issue['html_url']
try:
repo = self.get_repository_from_issue(issue)
except ValueError as e:
... |
def _reqs(self, tag):
""" Grab all the pull requests """
return [
(tag, i) for i in
self.client.get_pulls(*tag.split('/'))
] |
def _aggregate_issues(conf, main_section, target, queue, service_name):
""" This worker function is separated out from the main
:func:`aggregate_issues` func only so that we can use multiprocessing
on it for speed reasons.
"""
start = time.time()
try:
service = get_service(service_name... |
def aggregate_issues(conf, main_section, debug):
""" Return all issues from every target. """
log.info("Starting to aggregate remote issues.")
# Create and call service objects for every target in the config
targets = aslist(conf.get(main_section, 'targets'))
queue = multiprocessing.Queue()
l... |
def _get_config_or_default(self, key, default, as_type=lambda x: x):
"""Return a main config value, or default if it does not exist."""
if self.main_config.has_option(self.main_section, key):
return as_type(self.main_config.get(self.main_section, key))
return default |
def get_templates(self):
""" Get any defined templates for configuration values.
Users can override the value of any Taskwarrior field using
this feature on a per-key basis. The key should be the name of
the field to you would like to configure the value of, followed
by '_templ... |
def validate_config(cls, service_config, target):
""" Validate generic options for a particular target """
if service_config.has_option(target, 'only_if_assigned'):
die("[%s] has an 'only_if_assigned' option. Should be "
"'%s.only_if_assigned'." % (target, cls.CONFIG_PREFIX)... |
def include(self, issue):
""" Return true if the issue in question should be included """
only_if_assigned = self.config.get('only_if_assigned', None)
if only_if_assigned:
owner = self.get_owner(issue)
include_owners = [only_if_assigned]
if self.config.get('... |
def make_table(grid):
""" Make a RST-compatible table
From http://stackoverflow.com/a/12539081
"""
cell_width = 2 + max(
reduce(
lambda x, y: x+y, [[len(item) for item in row] for row in grid], []
)
)
num_cols = len(grid[0])
rst = table_div(num_cols, cell_width,... |
def get_service_password(service, username, oracle=None, interactive=False):
"""
Retrieve the sensitive password for a service by:
* retrieving password from a secure store (@oracle:use_keyring, default)
* asking the password from the user (@oracle:ask_password, interactive)
* executing a com... |
def oracle_eval(command):
""" Retrieve password from the given command """
p = subprocess.Popen(
command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
if p.returncode == 0:
return p.stdout.readline().strip().decode('utf-8')
else:
die(
"Erro... |
def get_config_path():
"""
Determine the path to the config file. This will return, in this order of
precedence:
- the value of $BUGWARRIORRC if set
- $XDG_CONFIG_HOME/bugwarrior/bugwarriorc if exists
- ~/.bugwarriorrc if exists
- <dir>/bugwarrior/bugwarriorc if exists, for dir in $XDG_CONFI... |
def fix_logging_path(config, main_section):
"""
Expand environment variables and user home (~) in the log.file and return
as relative path.
"""
log_file = config.get(main_section, 'log.file')
if log_file:
log_file = os.path.expanduser(os.path.expandvars(log_file))
if os.path.isab... |
def getint(self, section, option):
""" Accepts both integers and empty values. """
try:
return super(BugwarriorConfigParser, self).getint(section, option)
except ValueError:
if self.get(section, option) == u'':
return None
else:
... |
def _get_bug_attr(bug, attr):
"""Default longdescs/flags case to [] since they may not be present."""
if attr in ("longdescs", "flags"):
return getattr(bug, attr, [])
return getattr(bug, attr) |
def pull(dry_run, flavor, interactive, debug):
""" Pull down tasks from forges and add them to your taskwarrior tasks.
Relies on configuration in bugwarriorrc
"""
try:
main_section = _get_section_name(flavor)
config = _try_load_config(main_section, interactive)
lockfile_path =... |
def get_data(self, url):
""" Perform a request to the fully qualified url and return json. """
return self.json_response(requests.get(url, **self.requests_kwargs)) |
def get_collection(self, url):
""" Pages through an object collection from the bitbucket API.
Returns an iterator that lazily goes through all the 'values'
of all the pages in the collection. """
url = self.BASE_API2 + url
while url is not None:
response = self.get_da... |
def hamdist(str1, str2):
"""Count the # of differences between equal length strings str1 and str2"""
diffs = 0
for ch1, ch2 in zip(str1, str2):
if ch1 != ch2:
diffs += 1
return diffs |
def find_local_uuid(tw, keys, issue, legacy_matching=False):
""" For a given issue issue, find its local UUID.
Assembles a list of task IDs existing in taskwarrior
matching the supplied issue (`issue`) on the combination of any
set of supplied unique identifiers (`keys`) or, optionally,
the task's ... |
def merge_left(field, local_task, remote_issue, hamming=False):
""" Merge array field from the remote_issue into local_task
* Local 'left' entries are preserved without modification
* Remote 'left' are appended to task if not present in local.
:param `field`: Task field to merge.
:param `local_tas... |
def build_uda_config_overrides(targets):
""" Returns a list of UDAs defined by given targets
For all targets in `targets`, build a dictionary of configuration overrides
representing the UDAs defined by the passed-in services (`targets`).
Given a hypothetical situation in which you have two services, t... |
def _parse_sprint_string(sprint):
""" Parse the big ugly sprint string stored by JIRA.
They look like:
com.atlassian.greenhopper.service.sprint.Sprint@4c9c41a5[id=2322,rapid
ViewId=1173,state=ACTIVE,name=Sprint 1,startDate=2016-09-06T16:08:07.4
55Z,endDate=2016-09-23T16:08:00.000Z,compl... |
def get_credentials(self):
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
with ... |
def multi_rouge_n(sequences, scores_ids, n=2):
"""
Efficient way to compute highly repetitive scoring
i.e. sequences are involved multiple time
Args:
sequences(list[str]): list of sequences (either hyp or ref)
scores_ids(list[tuple(int)]): list of pairs (hyp_id, ref_id)
ie. ... |
def rouge_n(evaluated_sentences, reference_sentences, n=2):
"""
Computes ROUGE-N of two text collections of sentences.
Sourece: http://research.microsoft.com/en-us/um/people/cyl/download/
papers/rouge-working-note-v1.3.1.pdf
Args:
evaluated_sentences: The sentences that have been picked by th... |
def _union_lcs(evaluated_sentences, reference_sentence, prev_union=None):
"""
Returns LCS_u(r_i, C) which is the LCS score of the union longest common
subsequence between reference sentence ri and candidate summary C.
For example:
if r_i= w1 w2 w3 w4 w5, and C contains two sentences: c1 = w1 w2 w6 w... |
def rouge_l_summary_level(evaluated_sentences, reference_sentences):
"""
Computes ROUGE-L (summary level) of two text collections of sentences.
http://research.microsoft.com/en-us/um/people/cyl/download/papers/
rouge-working-note-v1.3.1.pdf
Calculated according to:
R_lcs = SUM(1, u)[LCS<union>(... |
def get_scores(self, avg=False, ignore_empty=False):
"""Calculate ROUGE scores between each pair of
lines (hyp_file[i], ref_file[i]).
Args:
* hyp_path: hypothesis file path
* ref_path: references file path
* avg (False): whether to get an average scores or a list
... |
def calc_pvalues(query, gene_sets, background=20000, **kwargs):
""" calculate pvalues for all categories in the graph
:param set query: set of identifiers for which the p value is calculated
:param dict gene_sets: gmt file dict after background was set
:param set background: total number of genes in yo... |
def fdrcorrection(pvals, alpha=0.05):
""" benjamini hocheberg fdr correction. inspired by statsmodels
"""
# Implement copy from GOATools.
pvals = np.asarray(pvals)
pvals_sortind = np.argsort(pvals)
pvals_sorted = np.take(pvals, pvals_sortind)
ecdffactor = _ecdf(pvals_sorted)
reject = p... |
def zscore(data2d, axis=0):
"""Standardize the mean and variance of the data axis Parameters.
:param data2d: DataFrame to normalize.
:param axis: int, Which axis to normalize across. If 0, normalize across rows,
if 1, normalize across columns. If None, don't change data
... |
def heatmap(df, z_score=None, title='', figsize=(5,5), cmap='RdBu_r',
xticklabels=True, yticklabels=True, ofname=None, **kwargs):
"""Visualize the dataframe.
:param df: DataFrame from expression table.
:param z_score: z_score axis{0, 1}. If None, don't normalize data.
:param title: gene se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.