repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
idlesign/dbf_light | dbf_light/cli.py | show | def show(db, encoding, no_limit, zip, case_insensitive):
"""Show .dbf file contents (rows)."""
limit = 15
if no_limit:
limit = float('inf')
with open_db(db, zip, encoding=encoding, case_sensitive=not case_insensitive) as dbf:
for idx, row in enumerate(dbf, 1):
click.secho('')
for key, val in row._asdict().items():
click.secho(' %s: %s' % (key, val))
if idx == limit:
click.secho(
'Note: Output is limited to %s rows. Use --no-limit option to bypass.' % limit, fg='red')
break | python | def show(db, encoding, no_limit, zip, case_insensitive):
"""Show .dbf file contents (rows)."""
limit = 15
if no_limit:
limit = float('inf')
with open_db(db, zip, encoding=encoding, case_sensitive=not case_insensitive) as dbf:
for idx, row in enumerate(dbf, 1):
click.secho('')
for key, val in row._asdict().items():
click.secho(' %s: %s' % (key, val))
if idx == limit:
click.secho(
'Note: Output is limited to %s rows. Use --no-limit option to bypass.' % limit, fg='red')
break | [
"def",
"show",
"(",
"db",
",",
"encoding",
",",
"no_limit",
",",
"zip",
",",
"case_insensitive",
")",
":",
"limit",
"=",
"15",
"if",
"no_limit",
":",
"limit",
"=",
"float",
"(",
"'inf'",
")",
"with",
"open_db",
"(",
"db",
",",
"zip",
",",
"encoding",... | Show .dbf file contents (rows). | [
"Show",
".",
"dbf",
"file",
"contents",
"(",
"rows",
")",
"."
] | train | https://github.com/idlesign/dbf_light/blob/59487bcdf92893a8a4b24239371dc0e4722c4c37/dbf_light/cli.py#L26-L44 |
idlesign/dbf_light | dbf_light/cli.py | describe | def describe(db, zip, case_insensitive):
"""Show .dbf file statistics."""
with open_db(db, zip, case_sensitive=not case_insensitive) as dbf:
click.secho('Rows count: %s' % (dbf.prolog.records_count))
click.secho('Fields:')
for field in dbf.fields:
click.secho(' %s: %s' % (field.type, field)) | python | def describe(db, zip, case_insensitive):
"""Show .dbf file statistics."""
with open_db(db, zip, case_sensitive=not case_insensitive) as dbf:
click.secho('Rows count: %s' % (dbf.prolog.records_count))
click.secho('Fields:')
for field in dbf.fields:
click.secho(' %s: %s' % (field.type, field)) | [
"def",
"describe",
"(",
"db",
",",
"zip",
",",
"case_insensitive",
")",
":",
"with",
"open_db",
"(",
"db",
",",
"zip",
",",
"case_sensitive",
"=",
"not",
"case_insensitive",
")",
"as",
"dbf",
":",
"click",
".",
"secho",
"(",
"'Rows count: %s'",
"%",
"(",... | Show .dbf file statistics. | [
"Show",
".",
"dbf",
"file",
"statistics",
"."
] | train | https://github.com/idlesign/dbf_light/blob/59487bcdf92893a8a4b24239371dc0e4722c4c37/dbf_light/cli.py#L51-L58 |
mozilla/funfactory | funfactory/cmd.py | clone_repo | def clone_repo(pkg, dest, repo, repo_dest, branch):
"""Clone the Playdoh repo into a custom path."""
git(['clone', '--recursive', '-b', branch, repo, repo_dest]) | python | def clone_repo(pkg, dest, repo, repo_dest, branch):
"""Clone the Playdoh repo into a custom path."""
git(['clone', '--recursive', '-b', branch, repo, repo_dest]) | [
"def",
"clone_repo",
"(",
"pkg",
",",
"dest",
",",
"repo",
",",
"repo_dest",
",",
"branch",
")",
":",
"git",
"(",
"[",
"'clone'",
",",
"'--recursive'",
",",
"'-b'",
",",
"branch",
",",
"repo",
",",
"repo_dest",
"]",
")"
] | Clone the Playdoh repo into a custom path. | [
"Clone",
"the",
"Playdoh",
"repo",
"into",
"a",
"custom",
"path",
"."
] | train | https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/cmd.py#L28-L30 |
mozilla/funfactory | funfactory/cmd.py | init_pkg | def init_pkg(pkg, repo_dest):
"""
Initializes a custom named package module.
This works by replacing all instances of 'project' with a custom module
name.
"""
vars = {'pkg': pkg}
with dir_path(repo_dest):
patch("""\
diff --git a/manage.py b/manage.py
index 40ebb0a..cdfe363 100755
--- a/manage.py
+++ b/manage.py
@@ -3,7 +3,7 @@ import os
import sys
# Edit this if necessary or override the variable in your environment.
-os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
+os.environ.setdefault('DJANGO_SETTINGS_MODULE', '%(pkg)s.settings')
try:
# For local development in a virtualenv:
diff --git a/project/settings/base.py b/project/settings/base.py
index 312f280..c75e673 100644
--- a/project/settings/base.py
+++ b/project/settings/base.py
@@ -7,7 +7,7 @@ from funfactory.settings_base import *
# If you did not install Playdoh with the funfactory installer script
# you may need to edit this value. See the docs about installing from a
# clone.
-PROJECT_MODULE = 'project'
+PROJECT_MODULE = '%(pkg)s'
# Bundles is a dictionary of two dictionaries, css and js, which list css files
# and js files that can be bundled together by the minify app.
diff --git a/setup.py b/setup.py
index 58dbd93..9a38628 100644
--- a/setup.py
+++ b/setup.py
@@ -3,7 +3,7 @@ import os
from setuptools import setup, find_packages
-setup(name='project',
+setup(name='%(pkg)s',
version='1.0',
description='Django application.',
long_description='',
""" % vars)
git(['mv', 'project', pkg])
git(['commit', '-a', '-m', 'Renamed project module to %s' % pkg]) | python | def init_pkg(pkg, repo_dest):
"""
Initializes a custom named package module.
This works by replacing all instances of 'project' with a custom module
name.
"""
vars = {'pkg': pkg}
with dir_path(repo_dest):
patch("""\
diff --git a/manage.py b/manage.py
index 40ebb0a..cdfe363 100755
--- a/manage.py
+++ b/manage.py
@@ -3,7 +3,7 @@ import os
import sys
# Edit this if necessary or override the variable in your environment.
-os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
+os.environ.setdefault('DJANGO_SETTINGS_MODULE', '%(pkg)s.settings')
try:
# For local development in a virtualenv:
diff --git a/project/settings/base.py b/project/settings/base.py
index 312f280..c75e673 100644
--- a/project/settings/base.py
+++ b/project/settings/base.py
@@ -7,7 +7,7 @@ from funfactory.settings_base import *
# If you did not install Playdoh with the funfactory installer script
# you may need to edit this value. See the docs about installing from a
# clone.
-PROJECT_MODULE = 'project'
+PROJECT_MODULE = '%(pkg)s'
# Bundles is a dictionary of two dictionaries, css and js, which list css files
# and js files that can be bundled together by the minify app.
diff --git a/setup.py b/setup.py
index 58dbd93..9a38628 100644
--- a/setup.py
+++ b/setup.py
@@ -3,7 +3,7 @@ import os
from setuptools import setup, find_packages
-setup(name='project',
+setup(name='%(pkg)s',
version='1.0',
description='Django application.',
long_description='',
""" % vars)
git(['mv', 'project', pkg])
git(['commit', '-a', '-m', 'Renamed project module to %s' % pkg]) | [
"def",
"init_pkg",
"(",
"pkg",
",",
"repo_dest",
")",
":",
"vars",
"=",
"{",
"'pkg'",
":",
"pkg",
"}",
"with",
"dir_path",
"(",
"repo_dest",
")",
":",
"patch",
"(",
"\"\"\"\\\n diff --git a/manage.py b/manage.py\n index 40ebb0a..cdfe363 100755\n ---... | Initializes a custom named package module.
This works by replacing all instances of 'project' with a custom module
name. | [
"Initializes",
"a",
"custom",
"named",
"package",
"module",
"."
] | train | https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/cmd.py#L33-L85 |
mozilla/funfactory | funfactory/cmd.py | create_settings | def create_settings(pkg, repo_dest, db_user, db_name, db_password, db_host,
db_port):
"""
Creates a local settings file out of the distributed template.
This also fills in database settings and generates a secret key, etc.
"""
vars = {'pkg': pkg,
'db_user': db_user,
'db_name': db_name,
'db_password': db_password or '',
'db_host': db_host or '',
'db_port': db_port or '',
'hmac_date': datetime.now().strftime('%Y-%m-%d'),
'hmac_key': generate_key(32),
'secret_key': generate_key(32)}
with dir_path(repo_dest):
shutil.copyfile('%s/settings/local.py-dist' % pkg,
'%s/settings/local.py' % pkg)
patch("""\
--- a/%(pkg)s/settings/local.py
+++ b/%(pkg)s/settings/local.py
@@ -9,11 +9,11 @@ from . import base
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
- 'NAME': 'playdoh_app',
- 'USER': 'root',
- 'PASSWORD': '',
- 'HOST': '',
- 'PORT': '',
+ 'NAME': '%(db_name)s',
+ 'USER': '%(db_user)s',
+ 'PASSWORD': '%(db_password)s',
+ 'HOST': '%(db_host)s',
+ 'PORT': '%(db_port)s',
'OPTIONS': {
'init_command': 'SET storage_engine=InnoDB',
'charset' : 'utf8',
@@ -51,14 +51,14 @@ DEV = True
# Playdoh ships with Bcrypt+HMAC by default because it's the most secure.
# To use bcrypt, fill in a secret HMAC key. It cannot be blank.
HMAC_KEYS = {
- #'2012-06-06': 'some secret',
+ '%(hmac_date)s': '%(hmac_key)s',
}
from django_sha2 import get_password_hashers
PASSWORD_HASHERS = get_password_hashers(base.BASE_PASSWORD_HASHERS, HMAC_KEYS)
# Make this unique, and don't share it with anybody. It cannot be blank.
-SECRET_KEY = ''
+SECRET_KEY = '%(secret_key)s'
# Uncomment these to activate and customize Celery:
# CELERY_ALWAYS_EAGER = False # required to activate celeryd
""" % vars) | python | def create_settings(pkg, repo_dest, db_user, db_name, db_password, db_host,
db_port):
"""
Creates a local settings file out of the distributed template.
This also fills in database settings and generates a secret key, etc.
"""
vars = {'pkg': pkg,
'db_user': db_user,
'db_name': db_name,
'db_password': db_password or '',
'db_host': db_host or '',
'db_port': db_port or '',
'hmac_date': datetime.now().strftime('%Y-%m-%d'),
'hmac_key': generate_key(32),
'secret_key': generate_key(32)}
with dir_path(repo_dest):
shutil.copyfile('%s/settings/local.py-dist' % pkg,
'%s/settings/local.py' % pkg)
patch("""\
--- a/%(pkg)s/settings/local.py
+++ b/%(pkg)s/settings/local.py
@@ -9,11 +9,11 @@ from . import base
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
- 'NAME': 'playdoh_app',
- 'USER': 'root',
- 'PASSWORD': '',
- 'HOST': '',
- 'PORT': '',
+ 'NAME': '%(db_name)s',
+ 'USER': '%(db_user)s',
+ 'PASSWORD': '%(db_password)s',
+ 'HOST': '%(db_host)s',
+ 'PORT': '%(db_port)s',
'OPTIONS': {
'init_command': 'SET storage_engine=InnoDB',
'charset' : 'utf8',
@@ -51,14 +51,14 @@ DEV = True
# Playdoh ships with Bcrypt+HMAC by default because it's the most secure.
# To use bcrypt, fill in a secret HMAC key. It cannot be blank.
HMAC_KEYS = {
- #'2012-06-06': 'some secret',
+ '%(hmac_date)s': '%(hmac_key)s',
}
from django_sha2 import get_password_hashers
PASSWORD_HASHERS = get_password_hashers(base.BASE_PASSWORD_HASHERS, HMAC_KEYS)
# Make this unique, and don't share it with anybody. It cannot be blank.
-SECRET_KEY = ''
+SECRET_KEY = '%(secret_key)s'
# Uncomment these to activate and customize Celery:
# CELERY_ALWAYS_EAGER = False # required to activate celeryd
""" % vars) | [
"def",
"create_settings",
"(",
"pkg",
",",
"repo_dest",
",",
"db_user",
",",
"db_name",
",",
"db_password",
",",
"db_host",
",",
"db_port",
")",
":",
"vars",
"=",
"{",
"'pkg'",
":",
"pkg",
",",
"'db_user'",
":",
"db_user",
",",
"'db_name'",
":",
"db_name... | Creates a local settings file out of the distributed template.
This also fills in database settings and generates a secret key, etc. | [
"Creates",
"a",
"local",
"settings",
"file",
"out",
"of",
"the",
"distributed",
"template",
"."
] | train | https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/cmd.py#L103-L159 |
mozilla/funfactory | funfactory/cmd.py | create_virtualenv | def create_virtualenv(pkg, repo_dest, python):
"""Creates a virtualenv within which to install your new application."""
workon_home = os.environ.get('WORKON_HOME')
venv_cmd = find_executable('virtualenv')
python_bin = find_executable(python)
if not python_bin:
raise EnvironmentError('%s is not installed or not '
'available on your $PATH' % python)
if workon_home:
# Can't use mkvirtualenv directly here because relies too much on
# shell tricks. Simulate it:
venv = os.path.join(workon_home, pkg)
else:
venv = os.path.join(repo_dest, '.virtualenv')
if venv_cmd:
if not verbose:
log.info('Creating virtual environment in %r' % venv)
args = ['--python', python_bin, venv]
if not verbose:
args.insert(0, '-q')
subprocess.check_call([venv_cmd] + args)
else:
raise EnvironmentError('Could not locate the virtualenv. Install with '
'pip install virtualenv.')
return venv | python | def create_virtualenv(pkg, repo_dest, python):
"""Creates a virtualenv within which to install your new application."""
workon_home = os.environ.get('WORKON_HOME')
venv_cmd = find_executable('virtualenv')
python_bin = find_executable(python)
if not python_bin:
raise EnvironmentError('%s is not installed or not '
'available on your $PATH' % python)
if workon_home:
# Can't use mkvirtualenv directly here because relies too much on
# shell tricks. Simulate it:
venv = os.path.join(workon_home, pkg)
else:
venv = os.path.join(repo_dest, '.virtualenv')
if venv_cmd:
if not verbose:
log.info('Creating virtual environment in %r' % venv)
args = ['--python', python_bin, venv]
if not verbose:
args.insert(0, '-q')
subprocess.check_call([venv_cmd] + args)
else:
raise EnvironmentError('Could not locate the virtualenv. Install with '
'pip install virtualenv.')
return venv | [
"def",
"create_virtualenv",
"(",
"pkg",
",",
"repo_dest",
",",
"python",
")",
":",
"workon_home",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'WORKON_HOME'",
")",
"venv_cmd",
"=",
"find_executable",
"(",
"'virtualenv'",
")",
"python_bin",
"=",
"find_executabl... | Creates a virtualenv within which to install your new application. | [
"Creates",
"a",
"virtualenv",
"within",
"which",
"to",
"install",
"your",
"new",
"application",
"."
] | train | https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/cmd.py#L162-L186 |
mozilla/funfactory | funfactory/cmd.py | install_reqs | def install_reqs(venv, repo_dest):
"""Installs all compiled requirements that can't be shipped in vendor."""
with dir_path(repo_dest):
args = ['-r', 'requirements/compiled.txt']
if not verbose:
args.insert(0, '-q')
subprocess.check_call([os.path.join(venv, 'bin', 'pip'), 'install'] +
args) | python | def install_reqs(venv, repo_dest):
"""Installs all compiled requirements that can't be shipped in vendor."""
with dir_path(repo_dest):
args = ['-r', 'requirements/compiled.txt']
if not verbose:
args.insert(0, '-q')
subprocess.check_call([os.path.join(venv, 'bin', 'pip'), 'install'] +
args) | [
"def",
"install_reqs",
"(",
"venv",
",",
"repo_dest",
")",
":",
"with",
"dir_path",
"(",
"repo_dest",
")",
":",
"args",
"=",
"[",
"'-r'",
",",
"'requirements/compiled.txt'",
"]",
"if",
"not",
"verbose",
":",
"args",
".",
"insert",
"(",
"0",
",",
"'-q'",
... | Installs all compiled requirements that can't be shipped in vendor. | [
"Installs",
"all",
"compiled",
"requirements",
"that",
"can",
"t",
"be",
"shipped",
"in",
"vendor",
"."
] | train | https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/cmd.py#L189-L196 |
mozilla/funfactory | funfactory/cmd.py | find_executable | def find_executable(name):
"""
Finds the actual path to a named command.
The first one on $PATH wins.
"""
for pt in os.environ.get('PATH', '').split(':'):
candidate = os.path.join(pt, name)
if os.path.exists(candidate):
return candidate | python | def find_executable(name):
"""
Finds the actual path to a named command.
The first one on $PATH wins.
"""
for pt in os.environ.get('PATH', '').split(':'):
candidate = os.path.join(pt, name)
if os.path.exists(candidate):
return candidate | [
"def",
"find_executable",
"(",
"name",
")",
":",
"for",
"pt",
"in",
"os",
".",
"environ",
".",
"get",
"(",
"'PATH'",
",",
"''",
")",
".",
"split",
"(",
"':'",
")",
":",
"candidate",
"=",
"os",
".",
"path",
".",
"join",
"(",
"pt",
",",
"name",
"... | Finds the actual path to a named command.
The first one on $PATH wins. | [
"Finds",
"the",
"actual",
"path",
"to",
"a",
"named",
"command",
"."
] | train | https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/cmd.py#L199-L208 |
mozilla/funfactory | funfactory/cmd.py | dir_path | def dir_path(dir):
"""with dir_path(path) to change into a directory."""
old_dir = os.getcwd()
os.chdir(dir)
yield
os.chdir(old_dir) | python | def dir_path(dir):
"""with dir_path(path) to change into a directory."""
old_dir = os.getcwd()
os.chdir(dir)
yield
os.chdir(old_dir) | [
"def",
"dir_path",
"(",
"dir",
")",
":",
"old_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"dir",
")",
"yield",
"os",
".",
"chdir",
"(",
"old_dir",
")"
] | with dir_path(path) to change into a directory. | [
"with",
"dir_path",
"(",
"path",
")",
"to",
"change",
"into",
"a",
"directory",
"."
] | train | https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/cmd.py#L225-L230 |
jbloomlab/phydms | phydmslib/weblogo.py | MWColorMapping | def MWColorMapping(maptype='jet', reverse=True):
"""Maps amino-acid molecular weights to colors. Otherwise, this
function is identical to *KyteDoolittleColorMapping*
"""
d = {'A':89,'R':174,'N':132,'D':133,'C':121,'Q':146,'E':147,\
'G':75,'H':155,'I':131,'L':131,'K':146,'M':149,'F':165,\
'P':115,'S':105,'T':119,'W':204,'Y':181,'V':117}
aas = sorted(AA_TO_INDEX.keys())
mws = [d[aa] for aa in aas]
if reverse:
mws = [-1 * x for x in mws]
mapper = pylab.cm.ScalarMappable(cmap=maptype)
mapper.set_clim(min(mws), max(mws))
mapping_d = {'*':'#000000'}
for (aa, h) in zip(aas, mws):
tup = mapper.to_rgba(h, bytes=True)
(red, green, blue, alpha) = tup
mapping_d[aa] = '#%02x%02x%02x' % (red, green, blue)
assert len(mapping_d[aa]) == 7
cmap = mapper.get_cmap()
return (cmap, mapping_d, mapper) | python | def MWColorMapping(maptype='jet', reverse=True):
"""Maps amino-acid molecular weights to colors. Otherwise, this
function is identical to *KyteDoolittleColorMapping*
"""
d = {'A':89,'R':174,'N':132,'D':133,'C':121,'Q':146,'E':147,\
'G':75,'H':155,'I':131,'L':131,'K':146,'M':149,'F':165,\
'P':115,'S':105,'T':119,'W':204,'Y':181,'V':117}
aas = sorted(AA_TO_INDEX.keys())
mws = [d[aa] for aa in aas]
if reverse:
mws = [-1 * x for x in mws]
mapper = pylab.cm.ScalarMappable(cmap=maptype)
mapper.set_clim(min(mws), max(mws))
mapping_d = {'*':'#000000'}
for (aa, h) in zip(aas, mws):
tup = mapper.to_rgba(h, bytes=True)
(red, green, blue, alpha) = tup
mapping_d[aa] = '#%02x%02x%02x' % (red, green, blue)
assert len(mapping_d[aa]) == 7
cmap = mapper.get_cmap()
return (cmap, mapping_d, mapper) | [
"def",
"MWColorMapping",
"(",
"maptype",
"=",
"'jet'",
",",
"reverse",
"=",
"True",
")",
":",
"d",
"=",
"{",
"'A'",
":",
"89",
",",
"'R'",
":",
"174",
",",
"'N'",
":",
"132",
",",
"'D'",
":",
"133",
",",
"'C'",
":",
"121",
",",
"'Q'",
":",
"1... | Maps amino-acid molecular weights to colors. Otherwise, this
function is identical to *KyteDoolittleColorMapping* | [
"Maps",
"amino",
"-",
"acid",
"molecular",
"weights",
"to",
"colors",
".",
"Otherwise",
"this",
"function",
"is",
"identical",
"to",
"*",
"KyteDoolittleColorMapping",
"*"
] | train | https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/weblogo.py#L83-L104 |
jbloomlab/phydms | phydmslib/weblogo.py | ChargeColorMapping | def ChargeColorMapping(maptype='jet', reverse=False):
"""Maps amino-acid charge at neutral pH to colors.
Currently does not use the keyword arguments for *maptype*
or *reverse* but accepts these arguments to be consistent
with KyteDoolittleColorMapping and MWColorMapping for now."""
pos_color = '#FF0000'
neg_color = '#0000FF'
neut_color = '#000000'
mapping_d = {'A':neut_color,'R':pos_color,'N':neut_color,\
'D':neg_color,'C':neut_color,'Q':neut_color,\
'E':neg_color,'G':neut_color,'H':pos_color,\
'I':neut_color,'L':neut_color,'K':pos_color,\
'M':neut_color,'F':neut_color,'P':neut_color,\
'S':neut_color,'T':neut_color,'W':neut_color,\
'Y':neut_color,'V':neut_color}
return (None, mapping_d, None) | python | def ChargeColorMapping(maptype='jet', reverse=False):
"""Maps amino-acid charge at neutral pH to colors.
Currently does not use the keyword arguments for *maptype*
or *reverse* but accepts these arguments to be consistent
with KyteDoolittleColorMapping and MWColorMapping for now."""
pos_color = '#FF0000'
neg_color = '#0000FF'
neut_color = '#000000'
mapping_d = {'A':neut_color,'R':pos_color,'N':neut_color,\
'D':neg_color,'C':neut_color,'Q':neut_color,\
'E':neg_color,'G':neut_color,'H':pos_color,\
'I':neut_color,'L':neut_color,'K':pos_color,\
'M':neut_color,'F':neut_color,'P':neut_color,\
'S':neut_color,'T':neut_color,'W':neut_color,\
'Y':neut_color,'V':neut_color}
return (None, mapping_d, None) | [
"def",
"ChargeColorMapping",
"(",
"maptype",
"=",
"'jet'",
",",
"reverse",
"=",
"False",
")",
":",
"pos_color",
"=",
"'#FF0000'",
"neg_color",
"=",
"'#0000FF'",
"neut_color",
"=",
"'#000000'",
"mapping_d",
"=",
"{",
"'A'",
":",
"neut_color",
",",
"'R'",
":",... | Maps amino-acid charge at neutral pH to colors.
Currently does not use the keyword arguments for *maptype*
or *reverse* but accepts these arguments to be consistent
with KyteDoolittleColorMapping and MWColorMapping for now. | [
"Maps",
"amino",
"-",
"acid",
"charge",
"at",
"neutral",
"pH",
"to",
"colors",
".",
"Currently",
"does",
"not",
"use",
"the",
"keyword",
"arguments",
"for",
"*",
"maptype",
"*",
"or",
"*",
"reverse",
"*",
"but",
"accepts",
"these",
"arguments",
"to",
"be... | train | https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/weblogo.py#L106-L124 |
jbloomlab/phydms | phydmslib/weblogo.py | FunctionalGroupColorMapping | def FunctionalGroupColorMapping(maptype='jet', reverse=False):
"""Maps amino-acid functional groups to colors.
Currently does not use the keyword arguments for *maptype*
or *reverse* but accepts these arguments to be consistent
with the other mapping functions, which all get called with
these arguments."""
small_color = '#f76ab4'
nucleophilic_color = '#ff7f00'
hydrophobic_color = '#12ab0d'
aromatic_color = '#84380b'
acidic_color = '#e41a1c'
amide_color = '#972aa8'
basic_color = '#3c58e5'
mapping_d = {'G':small_color, 'A':small_color,
'S':nucleophilic_color, 'T':nucleophilic_color, 'C':nucleophilic_color,
'V':hydrophobic_color, 'L':hydrophobic_color, 'I':hydrophobic_color, 'M':hydrophobic_color, 'P':hydrophobic_color,
'F':aromatic_color, 'Y':aromatic_color, 'W':aromatic_color,
'D':acidic_color, 'E':acidic_color,
'H':basic_color, 'K':basic_color, 'R':basic_color,
'N':amide_color, 'Q':amide_color,
'*':'#000000'}
return (None, mapping_d, None) | python | def FunctionalGroupColorMapping(maptype='jet', reverse=False):
"""Maps amino-acid functional groups to colors.
Currently does not use the keyword arguments for *maptype*
or *reverse* but accepts these arguments to be consistent
with the other mapping functions, which all get called with
these arguments."""
small_color = '#f76ab4'
nucleophilic_color = '#ff7f00'
hydrophobic_color = '#12ab0d'
aromatic_color = '#84380b'
acidic_color = '#e41a1c'
amide_color = '#972aa8'
basic_color = '#3c58e5'
mapping_d = {'G':small_color, 'A':small_color,
'S':nucleophilic_color, 'T':nucleophilic_color, 'C':nucleophilic_color,
'V':hydrophobic_color, 'L':hydrophobic_color, 'I':hydrophobic_color, 'M':hydrophobic_color, 'P':hydrophobic_color,
'F':aromatic_color, 'Y':aromatic_color, 'W':aromatic_color,
'D':acidic_color, 'E':acidic_color,
'H':basic_color, 'K':basic_color, 'R':basic_color,
'N':amide_color, 'Q':amide_color,
'*':'#000000'}
return (None, mapping_d, None) | [
"def",
"FunctionalGroupColorMapping",
"(",
"maptype",
"=",
"'jet'",
",",
"reverse",
"=",
"False",
")",
":",
"small_color",
"=",
"'#f76ab4'",
"nucleophilic_color",
"=",
"'#ff7f00'",
"hydrophobic_color",
"=",
"'#12ab0d'",
"aromatic_color",
"=",
"'#84380b'",
"acidic_colo... | Maps amino-acid functional groups to colors.
Currently does not use the keyword arguments for *maptype*
or *reverse* but accepts these arguments to be consistent
with the other mapping functions, which all get called with
these arguments. | [
"Maps",
"amino",
"-",
"acid",
"functional",
"groups",
"to",
"colors",
".",
"Currently",
"does",
"not",
"use",
"the",
"keyword",
"arguments",
"for",
"*",
"maptype",
"*",
"or",
"*",
"reverse",
"*",
"but",
"accepts",
"these",
"arguments",
"to",
"be",
"consist... | train | https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/weblogo.py#L126-L149 |
jbloomlab/phydms | phydmslib/weblogo.py | LogoPlot | def LogoPlot(sites, datatype, data, plotfile, nperline,
numberevery=10, allowunsorted=False, ydatamax=1.01,
overlay=None, fix_limits={}, fixlongname=False,
overlay_cmap=None, ylimits=None, relativestackheight=1,
custom_cmap='jet', map_metric='kd', noseparator=False,
underlay=False, scalebar=False):
"""Create sequence logo showing amino-acid or nucleotide preferences.
The heights of each letter is equal to the preference of
that site for that amino acid or nucleotide.
Note that stop codons may or may not be included in the logo
depending on whether they are present in *pi_d*.
CALLING VARIABLES:
* *sites* is a list of all of the sites that are being included
in the logo, as strings. They must be in natural sort or an error
will be raised **unless** *allowunsorted* is *True*. The sites
in the plot are ordered in the same arrangement
listed in *sites*. These should be **strings**, not integers.
* *datatype* should be one of the following strings:
* 'prefs' for preferences
* 'diffprefs' for differential preferences
* 'diffsel' for differential selection
* *data* is a dictionary that has a key for every entry in
*sites*. For every site *r* in *sites*, *sites[r][x]*
is the value for character *x*.
Preferences must sum to one; differential preferences to zero.
All sites must have the same set of characters. The characters
must be the set of nucleotides or amino acids with or without
stop codons.
* *plotfile* is a string giving the name of the created PDF file
of the logo plot.
It must end in the extension ``.pdf``.
* *nperline* is the number of sites per line. Often 40 to 80 are good values.
* *numberevery* is specifies how frequently we put labels for the sites on
x-axis.
* *allowunsorted* : if *True* then we allow the entries in *sites* to
**not** be sorted. This means that the logo plot will **not** have
sites in sorted order.
* *ydatamax* : meaningful only if *datatype* is 'diffprefs'. In this case, it gives
the maximum that the logo stacks extend in the positive and negative directions.
Cannot be smaller than the maximum extent of the differential preferences.
* *ylimits*: is **mandatory** if *datatype* is 'diffsel', and meaningless
otherwise. It is *(ymin, ymax)* where *ymax > 0 > ymin*, and gives extent
of the data in the positive and negative directions. Must encompass the
actual maximum and minimum of the data.
* *overlay* : make overlay bars that indicate other properties for
the sites. If you set to something other than `None`, it should be
a list giving one to three properties. Each property is a tuple:
*(prop_d, shortname, longname)* where:
- *prop_d* is a dictionary keyed by site numbers that are in *sites*.
For each *r* in *sites*, *prop_d[r]* gives the value of the property,
or if there is no entry in *prop_d* for *r*, then the property
is undefined and is colored white. Properties can either be:
* continuous: in this case, all of the values should be numbers.
* discrete : in this case, all of the values should be strings.
While in practice, if you have more than a few discrete
categories (different strings), the plot will be a mess.
- *shortname* : short name for the property; will not format well
if more than 4 or 5 characters.
- *longname* : longer name for property used on axes label. Can be the
same as *shortname* if you don't need a different long name.
- In the special case where both *shortname* and *longname* are
the string `wildtype`, then rather than an overlay bar we
right the one-character wildtype identity in `prop_d` for each
site.
* *fix_limits* is only meaningful if *overlay* is being used. In this case, for any
*shortname* in *overlay* that also keys an entry in *fix_limits*, we use
*fix_limits[shortname]* to set the limits for *shortname*. Specifically,
*fix_limits[shortname]* should be the 2-tuple *(ticks, ticknames)*. *ticks*
should be a list of tick locations (numbers) and *ticknames* should be a list of
the corresponding tick label for that tick.
* If *fixlongname* is *True*, then we use the *longname* in *overlay* exactly as written;
otherwise we add a parenthesis indicating the *shortname* for which this *longname*
stands.
* *overlay_cmap* can be the name of a valid *matplotlib.colors.Colormap*, such as the
string *jet* or *bwr*. Otherwise, it can be *None* and a (hopefully) good choice will
be made for you.
* *custom_cmap* can be the name of a valid *matplotlib.colors.Colormap* which will be
used to color amino-acid one-letter codes in the logoplot by the *map_metric* when
either 'kd' or 'mw' is used as *map_metric*.
* *relativestackheight* indicates how high the letter stack is relative to
the default. The default is multiplied by this number, so make it > 1
for a higher letter stack.
* *map_metric* specifies the amino-acid property metric used to map colors to amino-acid
letters. Valid options are 'kd' (Kyte-Doolittle hydrophobicity scale, default), 'mw'
(molecular weight), 'functionalgroup' (functional groups: small, nucleophilic, hydrophobic,
aromatic, basic, acidic, and amide), and 'charge' (charge at neutral pH). If 'charge' is used, then the
argument for *custom_cmap* will no longer be meaningful, since 'charge' uses its own
blue/black/red colormapping. Similarly, 'functionalgroup' uses its own colormapping.
* *noseparator* is only meaningful if *datatype* is 'diffsel' or 'diffprefs'.
If it set to *True*, then we do **not** print a black horizontal line to
separate positive and negative values.
* *underlay* if `True` then make an underlay rather than an overlay.
* *scalebar*: show a scale bar. If `False`, no scale bar shown. Otherwise
should be a 2-tuple of `(scalebarlen, scalebarlabel)`. Currently only
works when data is `diffsel`.
"""
assert datatype in ['prefs', 'diffprefs', 'diffsel'], "Invalid datatype {0}".format(datatype)
# check data, and get characters
assert sites, "No sites specified"
assert set(sites) == set(data.keys()), "Not a match between sites and the keys of data"
characters = list(data[sites[0]].keys())
aas = sorted(AA_TO_INDEX.keys())
if set(characters) == set(NT_TO_INDEX.keys()):
alphabet_type = 'nt'
elif set(characters) == set(aas) or set(characters) == set(aas + ['*']):
alphabet_type = 'aa'
else:
raise ValueError("Invalid set of characters in data. Does not specify either nucleotides or amino acids:\n%s" % str(characters))
for r in sites:
if set(data[r].keys()) != set(characters):
raise ValueError("Not all sites in data have the same set of characters")
firstblankchar = 'B' # character for first blank space for diffprefs / diffsel
assert firstblankchar not in characters, "firstblankchar in characters"
lastblankchar = 'b' # character for last blank space for diffprefs / diffsel
assert lastblankchar not in characters, "lastblankchar in characters"
separatorchar = '-' # separates positive and negative for diffprefs / diffsel
assert separatorchar not in characters, "lastblankchar in characters"
if noseparator:
separatorheight = 0
else:
separatorheight = 0.02 # height of separator as frac of total for diffprefs / diffsel
if os.path.splitext(plotfile)[1].lower() != '.pdf':
raise ValueError("plotfile must end in .pdf: %s" % plotfile)
if os.path.isfile(plotfile):
os.remove(plotfile) # remove existing plot
if not allowunsorted:
sorted_sites = natsort.natsorted([r for r in sites])
if sorted_sites != sites:
raise ValueError("sites is not properly sorted")
# Following are specifications of weblogo sizing taken from its documentation
stackwidth = 9.5 # stack width in points, not default size of 10.8, but set to this in weblogo call below
barheight = 5.5 # height of bars in points if using overlay
barspacing = 2.0 # spacing between bars in points if using overlay
stackaspectratio = 4.4 # ratio of stack height:width, doesn't count part going over maximum value of 1
assert relativestackheight > 0, "relativestackheight must be > 0"
stackaspectratio *= relativestackheight
if overlay:
if len(overlay) > 3:
raise ValueError("overlay cannot have more than 3 entries")
ymax = (stackaspectratio * stackwidth + len(overlay) * (barspacing + barheight)) / float(stackaspectratio * stackwidth)
aspectratio = ymax * stackaspectratio # effective aspect ratio for full range
else:
ymax = 1.0
aspectratio = stackaspectratio
rmargin = 11.5 # right margin in points, fixed by weblogo
stackheightmargin = 16 # margin between stacks in points, fixed by weblogo
showscalebar = False
try:
# write data into transfacfile (a temporary file)
(fd, transfacfile) = tempfile.mkstemp()
f = os.fdopen(fd, 'w')
ordered_alphabets = {} # keyed by site index (0, 1, ...) with values ordered lists for characters from bottom to top
if datatype == 'prefs':
chars_for_string = characters
f.write('ID ID\nBF BF\nP0 %s\n' % ' '.join(chars_for_string))
for (isite, r) in enumerate(sites):
f.write('%d %s\n' % (isite, ' '.join([str(data[r][x]) for x in characters])))
pi_r = [(data[r][x], x) for x in characters]
pi_r.sort()
ordered_alphabets[isite] = [tup[1] for tup in pi_r] # order from smallest to biggest
elif datatype == 'diffprefs':
chars_for_string = characters + [firstblankchar, lastblankchar, separatorchar]
ydatamax *= 2.0 # maximum possible range of data, multiply by two for range
f.write('ID ID\nBF BF\nP0 %s\n' % ' '.join(chars_for_string))
for (isite, r) in enumerate(sites):
positivesum = sum([data[r][x] for x in characters if data[r][x] > 0]) + separatorheight / 2.0
negativesum = sum([data[r][x] for x in characters if data[r][x] < 0]) - separatorheight / 2.0
if abs(positivesum + negativesum) > 1.0e-3:
raise ValueError("Differential preferences sum of %s is not close to zero for site %s" % (positivesum + negativesum, r))
if 2.0 * positivesum > ydatamax:
raise ValueError("You need to increase ydatamax: the total differential preferences sum to more than the y-axis limits. Right now, ydatamax is %.3f while the total differential preferences are %.3f" % (ydatamax, 2.0 * positivesum))
f.write('%d' % isite)
deltapi_r = []
for x in characters:
deltapi_r.append((data[r][x], x))
f.write(' %s' % (abs(data[r][x]) / float(ydatamax)))
deltapi_r.sort()
firstpositiveindex = 0
while deltapi_r[firstpositiveindex][0] < 0:
firstpositiveindex += 1
ordered_alphabets[isite] = [firstblankchar] + [tup[1] for tup in deltapi_r[ : firstpositiveindex]] + [separatorchar] + [tup[1] for tup in deltapi_r[firstpositiveindex : ]] + [lastblankchar] # order from most negative to most positive with blank characters and separators
f.write(' %g %g %g\n' % (0.5 * (ydatamax + 2.0 * negativesum) / ydatamax, 0.5 * (ydatamax + 2.0 * negativesum) / ydatamax, separatorheight)) # heights for blank charactors and separators
elif datatype == 'diffsel':
assert ylimits, "You must specify ylimits if using diffsel"
(dataymin, dataymax) = ylimits
assert dataymax > 0 > dataymin, "Invalid ylimits of {0}".format(ylimits)
yextent = float(dataymax - dataymin)
separatorheight *= yextent
chars_for_string = characters + [firstblankchar, lastblankchar, separatorchar]
f.write('ID ID\nBF BF\nP0 {0}\n'.format(' '.join(chars_for_string)))
for (isite, r) in enumerate(sites):
positivesum = sum([data[r][x] for x in characters if data[r][x] > 0]) + separatorheight / 2.0
negativesum = sum([data[r][x] for x in characters if data[r][x] < 0]) - separatorheight / 2.0
assert positivesum <= dataymax, "Data exceeds ylimits in positive direction"
assert negativesum >= dataymin, "Data exceeds ylimits in negative direction"
f.write('{0}'.format(isite))
diffsel_r = []
for x in characters:
diffsel_r.append((data[r][x], x))
f.write(' {0}'.format(abs(data[r][x]) / yextent))
diffsel_r.sort()
firstpositiveindex = 0
while diffsel_r[firstpositiveindex][0] < 0:
firstpositiveindex += 1
ordered_alphabets[isite] = [firstblankchar] + [tup[1] for tup in diffsel_r[ : firstpositiveindex]] + [separatorchar] + [tup[1] for tup in diffsel_r[firstpositiveindex : ]] + [lastblankchar] # order from most negative to most positive with blank characters and separators
f.write(' %g %g %g\n' % ((negativesum - dataymin) / yextent, (dataymax - positivesum) / yextent, separatorheight / yextent)) # heights for blank charactors and separators
# height of one unit on y-axis in points
heightofone = stackwidth * stackaspectratio / yextent
assert heightofone > 0
if scalebar:
showscalebar = (heightofone * scalebar[0], scalebar[1])
else:
raise ValueError("Invalid datatype of %s" % datatype)
f.close()
# create web logo
charstring = ''.join(chars_for_string)
assert len(charstring) == len(chars_for_string), "Length of charstring doesn't match length of chars_for_string. Do you have unallowable multi-letter characters?\n%s" % (str(chars_for_string))
logoprior = weblogolib.parse_prior('equiprobable', charstring, 0)
motif = _my_Motif.read_transfac(open(transfacfile), charstring)
logodata = weblogolib.LogoData.from_counts(motif.alphabet, motif, logoprior)
logo_options = weblogolib.LogoOptions()
logo_options.fineprint = None
logo_options.stacks_per_line = nperline
logo_options.stack_aspect_ratio = aspectratio
logo_options.stack_width = stackwidth
logo_options.unit_name = 'probability'
logo_options.show_yaxis = False
logo_options.yaxis_scale = ymax
if alphabet_type == 'aa':
map_functions = {'kd':KyteDoolittleColorMapping,
'mw': MWColorMapping,
'charge' : ChargeColorMapping,
'functionalgroup':FunctionalGroupColorMapping}
map_fcn = map_functions[map_metric]
(cmap, colormapping, mapper) = map_fcn(maptype=custom_cmap)
elif alphabet_type == 'nt':
colormapping = {}
colormapping['A'] = '#008000'
colormapping['T'] = '#FF0000'
colormapping['C'] = '#0000FF'
colormapping['G'] = '#FFA500'
else:
raise ValueError("Invalid alphabet_type %s" % alphabet_type)
colormapping[firstblankchar] = colormapping[lastblankchar] = '#000000' # black, but color doesn't matter as modified weblogo code replaces with empty space
colormapping[separatorchar] = '#000000' # black
color_scheme = weblogolib.colorscheme.ColorScheme()
for x in chars_for_string:
if hasattr(color_scheme, 'rules'):
color_scheme.rules.append(weblogolib.colorscheme.SymbolColor(x, colormapping[x], "'%s'" % x))
else:
# this part is needed for weblogo 3.4
color_scheme.groups.append(weblogolib.colorscheme.ColorGroup(x, colormapping[x], "'%s'" % x))
logo_options.color_scheme = color_scheme
logo_options.annotate = [{True:r, False:''}[0 == isite % numberevery] for (isite, r) in enumerate(sites)]
logoformat = weblogolib.LogoFormat(logodata, logo_options)
# _my_pdf_formatter is modified from weblogo version 3.4 source code
# to allow custom ordering of the symbols.
pdf = _my_pdf_formatter(logodata, logoformat, ordered_alphabets)
with open(plotfile, 'wb') as f:
f.write(pdf)
assert os.path.isfile(plotfile), "Failed to find expected plotfile %s" % plotfile
finally:
# close if still open
try:
f.close()
except:
pass
# remove temporary file
if os.path.isfile(transfacfile):
os.remove(transfacfile)
# now build the overlay
if overlay or showscalebar:
try:
(fdoverlay, overlayfile) = tempfile.mkstemp(suffix='.pdf')
(fdmerged, mergedfile) = tempfile.mkstemp(suffix='.pdf')
foverlay = os.fdopen(fdoverlay, 'wb')
foverlay.close() # close, but we still have the path overlayfile...
fmerged = os.fdopen(fdmerged, 'wb')
logoheight = stackwidth * stackaspectratio + stackheightmargin
LogoOverlay(sites, overlayfile, overlay, nperline, sitewidth=stackwidth, rmargin=rmargin, logoheight=logoheight, barheight=barheight, barspacing=barspacing, fix_limits=fix_limits, fixlongname=fixlongname, overlay_cmap=overlay_cmap, underlay=underlay, scalebar=showscalebar)
plotfile_f = open(plotfile, 'rb')
plot = PyPDF2.PdfFileReader(plotfile_f).getPage(0)
overlayfile_f = open(overlayfile, 'rb')
overlaypdf = PyPDF2.PdfFileReader(overlayfile_f).getPage(0)
xshift = overlaypdf.artBox[2] - plot.artBox[2]
yshift = (barheight + barspacing) * len(overlay) - 0.5 * barspacing
overlaypdf.mergeTranslatedPage(plot, xshift,
yshift * int(underlay), expand=True)
overlaypdf.compressContentStreams()
output = PyPDF2.PdfFileWriter()
output.addPage(overlaypdf)
output.write(fmerged)
fmerged.close()
shutil.move(mergedfile, plotfile)
finally:
try:
plotfile_f.close()
except:
pass
try:
overlayfile_f.close()
except:
pass
try:
foverlay.close()
except:
pass
try:
fmerged.close()
except:
pass
for fname in [overlayfile, mergedfile]:
if os.path.isfile(fname):
os.remove(fname) | python | def LogoPlot(sites, datatype, data, plotfile, nperline,
numberevery=10, allowunsorted=False, ydatamax=1.01,
overlay=None, fix_limits={}, fixlongname=False,
overlay_cmap=None, ylimits=None, relativestackheight=1,
custom_cmap='jet', map_metric='kd', noseparator=False,
underlay=False, scalebar=False):
"""Create sequence logo showing amino-acid or nucleotide preferences.
The heights of each letter is equal to the preference of
that site for that amino acid or nucleotide.
Note that stop codons may or may not be included in the logo
depending on whether they are present in *pi_d*.
CALLING VARIABLES:
* *sites* is a list of all of the sites that are being included
in the logo, as strings. They must be in natural sort or an error
will be raised **unless** *allowunsorted* is *True*. The sites
in the plot are ordered in the same arrangement
listed in *sites*. These should be **strings**, not integers.
* *datatype* should be one of the following strings:
* 'prefs' for preferences
* 'diffprefs' for differential preferences
* 'diffsel' for differential selection
* *data* is a dictionary that has a key for every entry in
*sites*. For every site *r* in *sites*, *sites[r][x]*
is the value for character *x*.
Preferences must sum to one; differential preferences to zero.
All sites must have the same set of characters. The characters
must be the set of nucleotides or amino acids with or without
stop codons.
* *plotfile* is a string giving the name of the created PDF file
of the logo plot.
It must end in the extension ``.pdf``.
* *nperline* is the number of sites per line. Often 40 to 80 are good values.
* *numberevery* is specifies how frequently we put labels for the sites on
x-axis.
* *allowunsorted* : if *True* then we allow the entries in *sites* to
**not** be sorted. This means that the logo plot will **not** have
sites in sorted order.
* *ydatamax* : meaningful only if *datatype* is 'diffprefs'. In this case, it gives
the maximum that the logo stacks extend in the positive and negative directions.
Cannot be smaller than the maximum extent of the differential preferences.
* *ylimits*: is **mandatory** if *datatype* is 'diffsel', and meaningless
otherwise. It is *(ymin, ymax)* where *ymax > 0 > ymin*, and gives extent
of the data in the positive and negative directions. Must encompass the
actual maximum and minimum of the data.
* *overlay* : make overlay bars that indicate other properties for
the sites. If you set to something other than `None`, it should be
a list giving one to three properties. Each property is a tuple:
*(prop_d, shortname, longname)* where:
- *prop_d* is a dictionary keyed by site numbers that are in *sites*.
For each *r* in *sites*, *prop_d[r]* gives the value of the property,
or if there is no entry in *prop_d* for *r*, then the property
is undefined and is colored white. Properties can either be:
* continuous: in this case, all of the values should be numbers.
* discrete : in this case, all of the values should be strings.
While in practice, if you have more than a few discrete
categories (different strings), the plot will be a mess.
- *shortname* : short name for the property; will not format well
if more than 4 or 5 characters.
- *longname* : longer name for property used on axes label. Can be the
same as *shortname* if you don't need a different long name.
- In the special case where both *shortname* and *longname* are
the string `wildtype`, then rather than an overlay bar we
right the one-character wildtype identity in `prop_d` for each
site.
* *fix_limits* is only meaningful if *overlay* is being used. In this case, for any
*shortname* in *overlay* that also keys an entry in *fix_limits*, we use
*fix_limits[shortname]* to set the limits for *shortname*. Specifically,
*fix_limits[shortname]* should be the 2-tuple *(ticks, ticknames)*. *ticks*
should be a list of tick locations (numbers) and *ticknames* should be a list of
the corresponding tick label for that tick.
* If *fixlongname* is *True*, then we use the *longname* in *overlay* exactly as written;
otherwise we add a parenthesis indicating the *shortname* for which this *longname*
stands.
* *overlay_cmap* can be the name of a valid *matplotlib.colors.Colormap*, such as the
string *jet* or *bwr*. Otherwise, it can be *None* and a (hopefully) good choice will
be made for you.
* *custom_cmap* can be the name of a valid *matplotlib.colors.Colormap* which will be
used to color amino-acid one-letter codes in the logoplot by the *map_metric* when
either 'kd' or 'mw' is used as *map_metric*.
* *relativestackheight* indicates how high the letter stack is relative to
the default. The default is multiplied by this number, so make it > 1
for a higher letter stack.
* *map_metric* specifies the amino-acid property metric used to map colors to amino-acid
letters. Valid options are 'kd' (Kyte-Doolittle hydrophobicity scale, default), 'mw'
(molecular weight), 'functionalgroup' (functional groups: small, nucleophilic, hydrophobic,
aromatic, basic, acidic, and amide), and 'charge' (charge at neutral pH). If 'charge' is used, then the
argument for *custom_cmap* will no longer be meaningful, since 'charge' uses its own
blue/black/red colormapping. Similarly, 'functionalgroup' uses its own colormapping.
* *noseparator* is only meaningful if *datatype* is 'diffsel' or 'diffprefs'.
If it set to *True*, then we do **not** print a black horizontal line to
separate positive and negative values.
* *underlay* if `True` then make an underlay rather than an overlay.
* *scalebar*: show a scale bar. If `False`, no scale bar shown. Otherwise
should be a 2-tuple of `(scalebarlen, scalebarlabel)`. Currently only
works when data is `diffsel`.
"""
assert datatype in ['prefs', 'diffprefs', 'diffsel'], "Invalid datatype {0}".format(datatype)
# check data, and get characters
assert sites, "No sites specified"
assert set(sites) == set(data.keys()), "Not a match between sites and the keys of data"
characters = list(data[sites[0]].keys())
aas = sorted(AA_TO_INDEX.keys())
if set(characters) == set(NT_TO_INDEX.keys()):
alphabet_type = 'nt'
elif set(characters) == set(aas) or set(characters) == set(aas + ['*']):
alphabet_type = 'aa'
else:
raise ValueError("Invalid set of characters in data. Does not specify either nucleotides or amino acids:\n%s" % str(characters))
for r in sites:
if set(data[r].keys()) != set(characters):
raise ValueError("Not all sites in data have the same set of characters")
firstblankchar = 'B' # character for first blank space for diffprefs / diffsel
assert firstblankchar not in characters, "firstblankchar in characters"
lastblankchar = 'b' # character for last blank space for diffprefs / diffsel
assert lastblankchar not in characters, "lastblankchar in characters"
separatorchar = '-' # separates positive and negative for diffprefs / diffsel
assert separatorchar not in characters, "lastblankchar in characters"
if noseparator:
separatorheight = 0
else:
separatorheight = 0.02 # height of separator as frac of total for diffprefs / diffsel
if os.path.splitext(plotfile)[1].lower() != '.pdf':
raise ValueError("plotfile must end in .pdf: %s" % plotfile)
if os.path.isfile(plotfile):
os.remove(plotfile) # remove existing plot
if not allowunsorted:
sorted_sites = natsort.natsorted([r for r in sites])
if sorted_sites != sites:
raise ValueError("sites is not properly sorted")
# Following are specifications of weblogo sizing taken from its documentation
stackwidth = 9.5 # stack width in points, not default size of 10.8, but set to this in weblogo call below
barheight = 5.5 # height of bars in points if using overlay
barspacing = 2.0 # spacing between bars in points if using overlay
stackaspectratio = 4.4 # ratio of stack height:width, doesn't count part going over maximum value of 1
assert relativestackheight > 0, "relativestackheight must be > 0"
stackaspectratio *= relativestackheight
if overlay:
if len(overlay) > 3:
raise ValueError("overlay cannot have more than 3 entries")
ymax = (stackaspectratio * stackwidth + len(overlay) * (barspacing + barheight)) / float(stackaspectratio * stackwidth)
aspectratio = ymax * stackaspectratio # effective aspect ratio for full range
else:
ymax = 1.0
aspectratio = stackaspectratio
rmargin = 11.5 # right margin in points, fixed by weblogo
stackheightmargin = 16 # margin between stacks in points, fixed by weblogo
showscalebar = False
try:
# write data into transfacfile (a temporary file)
(fd, transfacfile) = tempfile.mkstemp()
f = os.fdopen(fd, 'w')
ordered_alphabets = {} # keyed by site index (0, 1, ...) with values ordered lists for characters from bottom to top
if datatype == 'prefs':
chars_for_string = characters
f.write('ID ID\nBF BF\nP0 %s\n' % ' '.join(chars_for_string))
for (isite, r) in enumerate(sites):
f.write('%d %s\n' % (isite, ' '.join([str(data[r][x]) for x in characters])))
pi_r = [(data[r][x], x) for x in characters]
pi_r.sort()
ordered_alphabets[isite] = [tup[1] for tup in pi_r] # order from smallest to biggest
elif datatype == 'diffprefs':
chars_for_string = characters + [firstblankchar, lastblankchar, separatorchar]
ydatamax *= 2.0 # maximum possible range of data, multiply by two for range
f.write('ID ID\nBF BF\nP0 %s\n' % ' '.join(chars_for_string))
for (isite, r) in enumerate(sites):
positivesum = sum([data[r][x] for x in characters if data[r][x] > 0]) + separatorheight / 2.0
negativesum = sum([data[r][x] for x in characters if data[r][x] < 0]) - separatorheight / 2.0
if abs(positivesum + negativesum) > 1.0e-3:
raise ValueError("Differential preferences sum of %s is not close to zero for site %s" % (positivesum + negativesum, r))
if 2.0 * positivesum > ydatamax:
raise ValueError("You need to increase ydatamax: the total differential preferences sum to more than the y-axis limits. Right now, ydatamax is %.3f while the total differential preferences are %.3f" % (ydatamax, 2.0 * positivesum))
f.write('%d' % isite)
deltapi_r = []
for x in characters:
deltapi_r.append((data[r][x], x))
f.write(' %s' % (abs(data[r][x]) / float(ydatamax)))
deltapi_r.sort()
firstpositiveindex = 0
while deltapi_r[firstpositiveindex][0] < 0:
firstpositiveindex += 1
ordered_alphabets[isite] = [firstblankchar] + [tup[1] for tup in deltapi_r[ : firstpositiveindex]] + [separatorchar] + [tup[1] for tup in deltapi_r[firstpositiveindex : ]] + [lastblankchar] # order from most negative to most positive with blank characters and separators
f.write(' %g %g %g\n' % (0.5 * (ydatamax + 2.0 * negativesum) / ydatamax, 0.5 * (ydatamax + 2.0 * negativesum) / ydatamax, separatorheight)) # heights for blank charactors and separators
elif datatype == 'diffsel':
assert ylimits, "You must specify ylimits if using diffsel"
(dataymin, dataymax) = ylimits
assert dataymax > 0 > dataymin, "Invalid ylimits of {0}".format(ylimits)
yextent = float(dataymax - dataymin)
separatorheight *= yextent
chars_for_string = characters + [firstblankchar, lastblankchar, separatorchar]
f.write('ID ID\nBF BF\nP0 {0}\n'.format(' '.join(chars_for_string)))
for (isite, r) in enumerate(sites):
positivesum = sum([data[r][x] for x in characters if data[r][x] > 0]) + separatorheight / 2.0
negativesum = sum([data[r][x] for x in characters if data[r][x] < 0]) - separatorheight / 2.0
assert positivesum <= dataymax, "Data exceeds ylimits in positive direction"
assert negativesum >= dataymin, "Data exceeds ylimits in negative direction"
f.write('{0}'.format(isite))
diffsel_r = []
for x in characters:
diffsel_r.append((data[r][x], x))
f.write(' {0}'.format(abs(data[r][x]) / yextent))
diffsel_r.sort()
firstpositiveindex = 0
while diffsel_r[firstpositiveindex][0] < 0:
firstpositiveindex += 1
ordered_alphabets[isite] = [firstblankchar] + [tup[1] for tup in diffsel_r[ : firstpositiveindex]] + [separatorchar] + [tup[1] for tup in diffsel_r[firstpositiveindex : ]] + [lastblankchar] # order from most negative to most positive with blank characters and separators
f.write(' %g %g %g\n' % ((negativesum - dataymin) / yextent, (dataymax - positivesum) / yextent, separatorheight / yextent)) # heights for blank charactors and separators
# height of one unit on y-axis in points
heightofone = stackwidth * stackaspectratio / yextent
assert heightofone > 0
if scalebar:
showscalebar = (heightofone * scalebar[0], scalebar[1])
else:
raise ValueError("Invalid datatype of %s" % datatype)
f.close()
# create web logo
charstring = ''.join(chars_for_string)
assert len(charstring) == len(chars_for_string), "Length of charstring doesn't match length of chars_for_string. Do you have unallowable multi-letter characters?\n%s" % (str(chars_for_string))
logoprior = weblogolib.parse_prior('equiprobable', charstring, 0)
motif = _my_Motif.read_transfac(open(transfacfile), charstring)
logodata = weblogolib.LogoData.from_counts(motif.alphabet, motif, logoprior)
logo_options = weblogolib.LogoOptions()
logo_options.fineprint = None
logo_options.stacks_per_line = nperline
logo_options.stack_aspect_ratio = aspectratio
logo_options.stack_width = stackwidth
logo_options.unit_name = 'probability'
logo_options.show_yaxis = False
logo_options.yaxis_scale = ymax
if alphabet_type == 'aa':
map_functions = {'kd':KyteDoolittleColorMapping,
'mw': MWColorMapping,
'charge' : ChargeColorMapping,
'functionalgroup':FunctionalGroupColorMapping}
map_fcn = map_functions[map_metric]
(cmap, colormapping, mapper) = map_fcn(maptype=custom_cmap)
elif alphabet_type == 'nt':
colormapping = {}
colormapping['A'] = '#008000'
colormapping['T'] = '#FF0000'
colormapping['C'] = '#0000FF'
colormapping['G'] = '#FFA500'
else:
raise ValueError("Invalid alphabet_type %s" % alphabet_type)
colormapping[firstblankchar] = colormapping[lastblankchar] = '#000000' # black, but color doesn't matter as modified weblogo code replaces with empty space
colormapping[separatorchar] = '#000000' # black
color_scheme = weblogolib.colorscheme.ColorScheme()
for x in chars_for_string:
if hasattr(color_scheme, 'rules'):
color_scheme.rules.append(weblogolib.colorscheme.SymbolColor(x, colormapping[x], "'%s'" % x))
else:
# this part is needed for weblogo 3.4
color_scheme.groups.append(weblogolib.colorscheme.ColorGroup(x, colormapping[x], "'%s'" % x))
logo_options.color_scheme = color_scheme
logo_options.annotate = [{True:r, False:''}[0 == isite % numberevery] for (isite, r) in enumerate(sites)]
logoformat = weblogolib.LogoFormat(logodata, logo_options)
# _my_pdf_formatter is modified from weblogo version 3.4 source code
# to allow custom ordering of the symbols.
pdf = _my_pdf_formatter(logodata, logoformat, ordered_alphabets)
with open(plotfile, 'wb') as f:
f.write(pdf)
assert os.path.isfile(plotfile), "Failed to find expected plotfile %s" % plotfile
finally:
# close if still open
try:
f.close()
except:
pass
# remove temporary file
if os.path.isfile(transfacfile):
os.remove(transfacfile)
# now build the overlay
if overlay or showscalebar:
try:
(fdoverlay, overlayfile) = tempfile.mkstemp(suffix='.pdf')
(fdmerged, mergedfile) = tempfile.mkstemp(suffix='.pdf')
foverlay = os.fdopen(fdoverlay, 'wb')
foverlay.close() # close, but we still have the path overlayfile...
fmerged = os.fdopen(fdmerged, 'wb')
logoheight = stackwidth * stackaspectratio + stackheightmargin
LogoOverlay(sites, overlayfile, overlay, nperline, sitewidth=stackwidth, rmargin=rmargin, logoheight=logoheight, barheight=barheight, barspacing=barspacing, fix_limits=fix_limits, fixlongname=fixlongname, overlay_cmap=overlay_cmap, underlay=underlay, scalebar=showscalebar)
plotfile_f = open(plotfile, 'rb')
plot = PyPDF2.PdfFileReader(plotfile_f).getPage(0)
overlayfile_f = open(overlayfile, 'rb')
overlaypdf = PyPDF2.PdfFileReader(overlayfile_f).getPage(0)
xshift = overlaypdf.artBox[2] - plot.artBox[2]
yshift = (barheight + barspacing) * len(overlay) - 0.5 * barspacing
overlaypdf.mergeTranslatedPage(plot, xshift,
yshift * int(underlay), expand=True)
overlaypdf.compressContentStreams()
output = PyPDF2.PdfFileWriter()
output.addPage(overlaypdf)
output.write(fmerged)
fmerged.close()
shutil.move(mergedfile, plotfile)
finally:
try:
plotfile_f.close()
except:
pass
try:
overlayfile_f.close()
except:
pass
try:
foverlay.close()
except:
pass
try:
fmerged.close()
except:
pass
for fname in [overlayfile, mergedfile]:
if os.path.isfile(fname):
os.remove(fname) | [
"def",
"LogoPlot",
"(",
"sites",
",",
"datatype",
",",
"data",
",",
"plotfile",
",",
"nperline",
",",
"numberevery",
"=",
"10",
",",
"allowunsorted",
"=",
"False",
",",
"ydatamax",
"=",
"1.01",
",",
"overlay",
"=",
"None",
",",
"fix_limits",
"=",
"{",
... | Create sequence logo showing amino-acid or nucleotide preferences.
The heights of each letter is equal to the preference of
that site for that amino acid or nucleotide.
Note that stop codons may or may not be included in the logo
depending on whether they are present in *pi_d*.
CALLING VARIABLES:
* *sites* is a list of all of the sites that are being included
in the logo, as strings. They must be in natural sort or an error
will be raised **unless** *allowunsorted* is *True*. The sites
in the plot are ordered in the same arrangement
listed in *sites*. These should be **strings**, not integers.
* *datatype* should be one of the following strings:
* 'prefs' for preferences
* 'diffprefs' for differential preferences
* 'diffsel' for differential selection
* *data* is a dictionary that has a key for every entry in
*sites*. For every site *r* in *sites*, *sites[r][x]*
is the value for character *x*.
Preferences must sum to one; differential preferences to zero.
All sites must have the same set of characters. The characters
must be the set of nucleotides or amino acids with or without
stop codons.
* *plotfile* is a string giving the name of the created PDF file
of the logo plot.
It must end in the extension ``.pdf``.
* *nperline* is the number of sites per line. Often 40 to 80 are good values.
* *numberevery* is specifies how frequently we put labels for the sites on
x-axis.
* *allowunsorted* : if *True* then we allow the entries in *sites* to
**not** be sorted. This means that the logo plot will **not** have
sites in sorted order.
* *ydatamax* : meaningful only if *datatype* is 'diffprefs'. In this case, it gives
the maximum that the logo stacks extend in the positive and negative directions.
Cannot be smaller than the maximum extent of the differential preferences.
* *ylimits*: is **mandatory** if *datatype* is 'diffsel', and meaningless
otherwise. It is *(ymin, ymax)* where *ymax > 0 > ymin*, and gives extent
of the data in the positive and negative directions. Must encompass the
actual maximum and minimum of the data.
* *overlay* : make overlay bars that indicate other properties for
the sites. If you set to something other than `None`, it should be
a list giving one to three properties. Each property is a tuple:
*(prop_d, shortname, longname)* where:
- *prop_d* is a dictionary keyed by site numbers that are in *sites*.
For each *r* in *sites*, *prop_d[r]* gives the value of the property,
or if there is no entry in *prop_d* for *r*, then the property
is undefined and is colored white. Properties can either be:
* continuous: in this case, all of the values should be numbers.
* discrete : in this case, all of the values should be strings.
While in practice, if you have more than a few discrete
categories (different strings), the plot will be a mess.
- *shortname* : short name for the property; will not format well
if more than 4 or 5 characters.
- *longname* : longer name for property used on axes label. Can be the
same as *shortname* if you don't need a different long name.
- In the special case where both *shortname* and *longname* are
the string `wildtype`, then rather than an overlay bar we
right the one-character wildtype identity in `prop_d` for each
site.
* *fix_limits* is only meaningful if *overlay* is being used. In this case, for any
*shortname* in *overlay* that also keys an entry in *fix_limits*, we use
*fix_limits[shortname]* to set the limits for *shortname*. Specifically,
*fix_limits[shortname]* should be the 2-tuple *(ticks, ticknames)*. *ticks*
should be a list of tick locations (numbers) and *ticknames* should be a list of
the corresponding tick label for that tick.
* If *fixlongname* is *True*, then we use the *longname* in *overlay* exactly as written;
otherwise we add a parenthesis indicating the *shortname* for which this *longname*
stands.
* *overlay_cmap* can be the name of a valid *matplotlib.colors.Colormap*, such as the
string *jet* or *bwr*. Otherwise, it can be *None* and a (hopefully) good choice will
be made for you.
* *custom_cmap* can be the name of a valid *matplotlib.colors.Colormap* which will be
used to color amino-acid one-letter codes in the logoplot by the *map_metric* when
either 'kd' or 'mw' is used as *map_metric*.
* *relativestackheight* indicates how high the letter stack is relative to
the default. The default is multiplied by this number, so make it > 1
for a higher letter stack.
* *map_metric* specifies the amino-acid property metric used to map colors to amino-acid
letters. Valid options are 'kd' (Kyte-Doolittle hydrophobicity scale, default), 'mw'
(molecular weight), 'functionalgroup' (functional groups: small, nucleophilic, hydrophobic,
aromatic, basic, acidic, and amide), and 'charge' (charge at neutral pH). If 'charge' is used, then the
argument for *custom_cmap* will no longer be meaningful, since 'charge' uses its own
blue/black/red colormapping. Similarly, 'functionalgroup' uses its own colormapping.
* *noseparator* is only meaningful if *datatype* is 'diffsel' or 'diffprefs'.
If it set to *True*, then we do **not** print a black horizontal line to
separate positive and negative values.
* *underlay* if `True` then make an underlay rather than an overlay.
* *scalebar*: show a scale bar. If `False`, no scale bar shown. Otherwise
should be a 2-tuple of `(scalebarlen, scalebarlabel)`. Currently only
works when data is `diffsel`. | [
"Create",
"sequence",
"logo",
"showing",
"amino",
"-",
"acid",
"or",
"nucleotide",
"preferences",
"."
] | train | https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/weblogo.py#L152-L504 |
jbloomlab/phydms | phydmslib/weblogo.py | _my_pdf_formatter | def _my_pdf_formatter(data, format, ordered_alphabets) :
""" Generate a logo in PDF format.
Modified from weblogo version 3.4 source code.
"""
eps = _my_eps_formatter(data, format, ordered_alphabets).decode()
gs = weblogolib.GhostscriptAPI()
return gs.convert('pdf', eps, format.logo_width, format.logo_height) | python | def _my_pdf_formatter(data, format, ordered_alphabets) :
""" Generate a logo in PDF format.
Modified from weblogo version 3.4 source code.
"""
eps = _my_eps_formatter(data, format, ordered_alphabets).decode()
gs = weblogolib.GhostscriptAPI()
return gs.convert('pdf', eps, format.logo_width, format.logo_height) | [
"def",
"_my_pdf_formatter",
"(",
"data",
",",
"format",
",",
"ordered_alphabets",
")",
":",
"eps",
"=",
"_my_eps_formatter",
"(",
"data",
",",
"format",
",",
"ordered_alphabets",
")",
".",
"decode",
"(",
")",
"gs",
"=",
"weblogolib",
".",
"GhostscriptAPI",
"... | Generate a logo in PDF format.
Modified from weblogo version 3.4 source code. | [
"Generate",
"a",
"logo",
"in",
"PDF",
"format",
".",
"Modified",
"from",
"weblogo",
"version",
"3",
".",
"4",
"source",
"code",
"."
] | train | https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/weblogo.py#L551-L558 |
jbloomlab/phydms | phydmslib/weblogo.py | _my_eps_formatter | def _my_eps_formatter(logodata, format, ordered_alphabets) :
""" Generate a logo in Encapsulated Postscript (EPS)
Modified from weblogo version 3.4 source code.
*ordered_alphabets* is a dictionary keyed by zero-indexed
consecutive sites, with values giving order of characters
from bottom to top.
"""
substitutions = {}
from_format =[
"creation_date", "logo_width", "logo_height",
"lines_per_logo", "line_width", "line_height",
"line_margin_right","line_margin_left", "line_margin_bottom",
"line_margin_top", "title_height", "xaxis_label_height",
"creator_text", "logo_title", "logo_margin",
"stroke_width", "tic_length",
"stacks_per_line", "stack_margin",
"yaxis_label", "yaxis_tic_interval", "yaxis_minor_tic_interval",
"xaxis_label", "xaxis_tic_interval", "number_interval",
"fineprint", "shrink_fraction", "errorbar_fraction",
"errorbar_width_fraction",
"errorbar_gray", "small_fontsize", "fontsize",
"title_fontsize", "number_fontsize", "text_font",
"logo_font", "title_font",
"logo_label", "yaxis_scale", "end_type",
"debug", "show_title", "show_xaxis",
"show_xaxis_label", "show_yaxis", "show_yaxis_label",
"show_boxes", "show_errorbars", "show_fineprint",
"rotate_numbers", "show_ends", "stack_height",
"stack_width"
]
for s in from_format :
substitutions[s] = getattr(format,s)
substitutions["shrink"] = str(format.show_boxes).lower()
# --------- COLORS --------------
def format_color(color):
return " ".join( ("[",str(color.red) , str(color.green),
str(color.blue), "]"))
substitutions["default_color"] = format_color(format.default_color)
colors = []
if hasattr(format.color_scheme, 'rules'):
grouplist = format.color_scheme.rules
else:
# this line needed for weblogo 3.4
grouplist = format.color_scheme.groups
for group in grouplist:
cf = format_color(group.color)
for s in group.symbols :
colors.append( " ("+s+") " + cf )
substitutions["color_dict"] = "\n".join(colors)
data = []
# Unit conversion. 'None' for probability units
conv_factor = None #JDB
#JDB conv_factor = std_units[format.unit_name]
data.append("StartLine")
seq_from = format.logo_start- format.first_index
seq_to = format.logo_end - format.first_index +1
# seq_index : zero based index into sequence data
# logo_index : User visible coordinate, first_index based
# stack_index : zero based index of visible stacks
for seq_index in range(seq_from, seq_to) :
logo_index = seq_index + format.first_index
stack_index = seq_index - seq_from
if stack_index!=0 and (stack_index % format.stacks_per_line) ==0 :
data.append("")
data.append("EndLine")
data.append("StartLine")
data.append("")
data.append("(%s) StartStack" % format.annotate[seq_index] )
if conv_factor:
stack_height = logodata.entropy[seq_index] * std_units[format.unit_name]
else :
stack_height = 1.0 # Probability
# The following code modified by JDB to use ordered_alphabets
# and also to replace the "blank" characters 'b' and 'B'
# by spaces.
s_d = dict(zip(logodata.alphabet, logodata.counts[seq_index]))
s = []
for aa in ordered_alphabets[seq_index]:
if aa not in ['B', 'b']:
s.append((s_d[aa], aa))
else:
s.append((s_d[aa], ' '))
# s = [(s_d[aa], aa) for aa in ordered_alphabets[seq_index]]
# Sort by frequency. If equal frequency then reverse alphabetic
# (So sort reverse alphabetic first, then frequencty)
# TODO: doublecheck this actual works
#s = list(zip(logodata.counts[seq_index], logodata.alphabet))
#s.sort(key= lambda x: x[1])
#s.reverse()
#s.sort(key= lambda x: x[0])
#if not format.reverse_stacks: s.reverse()
C = float(sum(logodata.counts[seq_index]))
if C > 0.0 :
fraction_width = 1.0
if format.scale_width :
fraction_width = logodata.weight[seq_index]
# print(fraction_width, file=sys.stderr)
for c in s:
data.append(" %f %f (%s) ShowSymbol" % (fraction_width, c[0]*stack_height/C, c[1]) )
# Draw error bar on top of logo. Replaced by DrawErrorbarFirst above.
if logodata.entropy_interval is not None and conv_factor and C>0.0:
low, high = logodata.entropy_interval[seq_index]
center = logodata.entropy[seq_index]
low *= conv_factor
high *= conv_factor
center *=conv_factor
if high> format.yaxis_scale : high = format.yaxis_scale
down = (center - low)
up = (high - center)
data.append(" %f %f DrawErrorbar" % (down, up) )
data.append("EndStack")
data.append("")
data.append("EndLine")
substitutions["logo_data"] = "\n".join(data)
# Create and output logo
template = corebio.utils.resource_string( __name__, '_weblogo_template.eps', __file__).decode()
logo = string.Template(template).substitute(substitutions)
return logo.encode() | python | def _my_eps_formatter(logodata, format, ordered_alphabets) :
""" Generate a logo in Encapsulated Postscript (EPS)
Modified from weblogo version 3.4 source code.
*ordered_alphabets* is a dictionary keyed by zero-indexed
consecutive sites, with values giving order of characters
from bottom to top.
"""
substitutions = {}
from_format =[
"creation_date", "logo_width", "logo_height",
"lines_per_logo", "line_width", "line_height",
"line_margin_right","line_margin_left", "line_margin_bottom",
"line_margin_top", "title_height", "xaxis_label_height",
"creator_text", "logo_title", "logo_margin",
"stroke_width", "tic_length",
"stacks_per_line", "stack_margin",
"yaxis_label", "yaxis_tic_interval", "yaxis_minor_tic_interval",
"xaxis_label", "xaxis_tic_interval", "number_interval",
"fineprint", "shrink_fraction", "errorbar_fraction",
"errorbar_width_fraction",
"errorbar_gray", "small_fontsize", "fontsize",
"title_fontsize", "number_fontsize", "text_font",
"logo_font", "title_font",
"logo_label", "yaxis_scale", "end_type",
"debug", "show_title", "show_xaxis",
"show_xaxis_label", "show_yaxis", "show_yaxis_label",
"show_boxes", "show_errorbars", "show_fineprint",
"rotate_numbers", "show_ends", "stack_height",
"stack_width"
]
for s in from_format :
substitutions[s] = getattr(format,s)
substitutions["shrink"] = str(format.show_boxes).lower()
# --------- COLORS --------------
def format_color(color):
return " ".join( ("[",str(color.red) , str(color.green),
str(color.blue), "]"))
substitutions["default_color"] = format_color(format.default_color)
colors = []
if hasattr(format.color_scheme, 'rules'):
grouplist = format.color_scheme.rules
else:
# this line needed for weblogo 3.4
grouplist = format.color_scheme.groups
for group in grouplist:
cf = format_color(group.color)
for s in group.symbols :
colors.append( " ("+s+") " + cf )
substitutions["color_dict"] = "\n".join(colors)
data = []
# Unit conversion. 'None' for probability units
conv_factor = None #JDB
#JDB conv_factor = std_units[format.unit_name]
data.append("StartLine")
seq_from = format.logo_start- format.first_index
seq_to = format.logo_end - format.first_index +1
# seq_index : zero based index into sequence data
# logo_index : User visible coordinate, first_index based
# stack_index : zero based index of visible stacks
for seq_index in range(seq_from, seq_to) :
logo_index = seq_index + format.first_index
stack_index = seq_index - seq_from
if stack_index!=0 and (stack_index % format.stacks_per_line) ==0 :
data.append("")
data.append("EndLine")
data.append("StartLine")
data.append("")
data.append("(%s) StartStack" % format.annotate[seq_index] )
if conv_factor:
stack_height = logodata.entropy[seq_index] * std_units[format.unit_name]
else :
stack_height = 1.0 # Probability
# The following code modified by JDB to use ordered_alphabets
# and also to replace the "blank" characters 'b' and 'B'
# by spaces.
s_d = dict(zip(logodata.alphabet, logodata.counts[seq_index]))
s = []
for aa in ordered_alphabets[seq_index]:
if aa not in ['B', 'b']:
s.append((s_d[aa], aa))
else:
s.append((s_d[aa], ' '))
# s = [(s_d[aa], aa) for aa in ordered_alphabets[seq_index]]
# Sort by frequency. If equal frequency then reverse alphabetic
# (So sort reverse alphabetic first, then frequencty)
# TODO: doublecheck this actual works
#s = list(zip(logodata.counts[seq_index], logodata.alphabet))
#s.sort(key= lambda x: x[1])
#s.reverse()
#s.sort(key= lambda x: x[0])
#if not format.reverse_stacks: s.reverse()
C = float(sum(logodata.counts[seq_index]))
if C > 0.0 :
fraction_width = 1.0
if format.scale_width :
fraction_width = logodata.weight[seq_index]
# print(fraction_width, file=sys.stderr)
for c in s:
data.append(" %f %f (%s) ShowSymbol" % (fraction_width, c[0]*stack_height/C, c[1]) )
# Draw error bar on top of logo. Replaced by DrawErrorbarFirst above.
if logodata.entropy_interval is not None and conv_factor and C>0.0:
low, high = logodata.entropy_interval[seq_index]
center = logodata.entropy[seq_index]
low *= conv_factor
high *= conv_factor
center *=conv_factor
if high> format.yaxis_scale : high = format.yaxis_scale
down = (center - low)
up = (high - center)
data.append(" %f %f DrawErrorbar" % (down, up) )
data.append("EndStack")
data.append("")
data.append("EndLine")
substitutions["logo_data"] = "\n".join(data)
# Create and output logo
template = corebio.utils.resource_string( __name__, '_weblogo_template.eps', __file__).decode()
logo = string.Template(template).substitute(substitutions)
return logo.encode() | [
"def",
"_my_eps_formatter",
"(",
"logodata",
",",
"format",
",",
"ordered_alphabets",
")",
":",
"substitutions",
"=",
"{",
"}",
"from_format",
"=",
"[",
"\"creation_date\"",
",",
"\"logo_width\"",
",",
"\"logo_height\"",
",",
"\"lines_per_logo\"",
",",
"\"line_width... | Generate a logo in Encapsulated Postscript (EPS)
Modified from weblogo version 3.4 source code.
*ordered_alphabets* is a dictionary keyed by zero-indexed
consecutive sites, with values giving order of characters
from bottom to top. | [
"Generate",
"a",
"logo",
"in",
"Encapsulated",
"Postscript",
"(",
"EPS",
")",
"Modified",
"from",
"weblogo",
"version",
"3",
".",
"4",
"source",
"code",
"."
] | train | https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/weblogo.py#L561-L705 |
jbloomlab/phydms | phydmslib/weblogo.py | LogoOverlay | def LogoOverlay(sites, overlayfile, overlay, nperline, sitewidth, rmargin, logoheight, barheight, barspacing, fix_limits={}, fixlongname=False, overlay_cmap=None, underlay=False, scalebar=False):
"""Makes overlay for *LogoPlot*.
This function creates colored bars overlay bars showing up to two
properties.
The trick of this function is to create the bars the right
size so they align when they overlay the logo plot.
CALLING VARIABLES:
* *sites* : same as the variable of this name used by *LogoPlot*.
* *overlayfile* is a string giving the name of created PDF file containing
the overlay. It must end in the extension ``.pdf``.
* *overlay* : same as the variable of this name used by *LogoPlot*.
* *nperline* : same as the variable of this name used by *LogoPlot*.
* *sitewidth* is the width of each site in points.
* *rmargin* is the right margin in points.
* *logoheight* is the total height of each logo row in points.
* *barheight* is the total height of each bar in points.
* *barspacing* is the vertical spacing between bars in points.
* *fix_limits* has the same meaning of the variable of this name used by *LogoPlot*.
* *fixlongname* has the same meaning of the variable of this name used by *LogoPlot*.
* *overlay_cmap* has the same meaning of the variable of this name used by *LogoPlot*.
* *underlay* is a bool. If `True`, make an underlay rather than an overlay.
* *scalebar: if not `False`, is 2-tuple `(scalebarheight, scalebarlabel)`
where `scalebarheight` is in points.
"""
if os.path.splitext(overlayfile)[1] != '.pdf':
raise ValueError("overlayfile must end in .pdf: %s" % overlayfile)
if not overlay_cmap:
(cmap, mapping_d, mapper) = KyteDoolittleColorMapping()
else:
mapper = pylab.cm.ScalarMappable(cmap=overlay_cmap)
cmap = mapper.get_cmap()
pts_per_inch = 72.0 # to convert between points and inches
# some general properties of the plot
matplotlib.rc('text', usetex=True)
matplotlib.rc('xtick', labelsize=8)
matplotlib.rc('xtick', direction='out')
matplotlib.rc('ytick', direction='out')
matplotlib.rc('axes', linewidth=0.5)
matplotlib.rc('ytick.major', size=3)
matplotlib.rc('xtick.major', size=2.5)
# define sizes (still in points)
colorbar_bmargin = 20 # margin below color bars in points
colorbar_tmargin = 15 # margin above color bars in points
nlines = int(math.ceil(len(sites) / float(nperline)))
lmargin = 25 # left margin in points
barwidth = nperline * sitewidth
figwidth = lmargin + rmargin + barwidth
figheight = nlines * (logoheight + len(overlay) * (barheight +
barspacing)) + (barheight + colorbar_bmargin + colorbar_tmargin) + (
int(underlay) * len(overlay) * (barheight + barspacing))
# set up the figure and axes
fig = pylab.figure(figsize=(figwidth / pts_per_inch, figheight / pts_per_inch))
# determine property types
prop_types = {}
for (prop_d, shortname, longname) in overlay:
if shortname == longname == 'wildtype':
assert all([(isinstance(prop, str) and len(prop) == 1) for
prop in prop_d.values()]), 'prop_d does not give letters'
proptype = 'wildtype'
(vmin, vmax) = (0, 1) # not used, but need to be assigned
propcategories = None # not used, but needs to be assigned
elif all([isinstance(prop, str) for prop in prop_d.values()]):
proptype = 'discrete'
propcategories = list(set(prop_d.values()))
propcategories.sort()
(vmin, vmax) = (0, len(propcategories) - 1)
elif all ([isinstance(prop, (int, float)) for prop in prop_d.values()]):
proptype = 'continuous'
propcategories = None
(vmin, vmax) = (min(prop_d.values()), max(prop_d.values()))
# If vmin is slightly greater than zero, set it to zero. This helps for RSA properties.
if vmin >= 0 and vmin / float(vmax - vmin) < 0.05:
vmin = 0.0
# And if vmax is just a bit less than one, set it to that...
if 0.9 <= vmax <= 1.0:
vmax = 1.0
else:
raise ValueError("Property %s is neither continuous or discrete. Values are:\n%s" % (shortname, str(prop_d.items())))
if shortname in fix_limits:
(vmin, vmax) = (min(fix_limits[shortname][0]), max(fix_limits[shortname][0]))
assert vmin < vmax, "vmin >= vmax, did you incorrectly use fix_vmin and fix_vmax?"
prop_types[shortname] = (proptype, vmin, vmax, propcategories)
assert len(prop_types) == len(overlay), "Not as many property types as overlays. Did you give the same name (shortname) to multiple properties in the overlay?"
# loop over each line of the multi-lined plot
prop_image = {}
for iline in range(nlines):
isites = sites[iline * nperline : min(len(sites), (iline + 1) * nperline)]
xlength = len(isites) * sitewidth
logo_ax = pylab.axes([lmargin / figwidth, ((nlines - iline - 1) * (logoheight + len(overlay) * (barspacing + barheight))) / figheight, xlength / figwidth, logoheight / figheight], frameon=False)
logo_ax.yaxis.set_ticks_position('none')
logo_ax.xaxis.set_ticks_position('none')
pylab.yticks([])
pylab.xlim(0.5, len(isites) + 0.5)
pylab.xticks([])
for (iprop, (prop_d, shortname, longname)) in enumerate(overlay):
(proptype, vmin, vmax, propcategories) = prop_types[shortname]
prop_ax = pylab.axes([
lmargin / figwidth,
((nlines - iline - 1) * (logoheight +
len(overlay) * (barspacing + barheight)) +
(1 - int(underlay)) * logoheight + int(underlay) *
barspacing + iprop * (barspacing + barheight))
/ figheight,
xlength / figwidth,
barheight / figheight],
frameon=(proptype != 'wildtype'))
prop_ax.xaxis.set_ticks_position('none')
pylab.xticks([])
pylab.xlim((0, len(isites)))
pylab.ylim(-0.5, 0.5)
if proptype == 'wildtype':
pylab.yticks([])
prop_ax.yaxis.set_ticks_position('none')
for (isite, site) in enumerate(isites):
pylab.text(isite + 0.5, -0.5, prop_d[site], size=9,
horizontalalignment='center', family='monospace')
continue
pylab.yticks([0], [shortname], size=8)
prop_ax.yaxis.set_ticks_position('left')
propdata = pylab.zeros(shape=(1, len(isites)))
propdata[ : ] = pylab.nan # set to nan for all entries
for (isite, site) in enumerate(isites):
if site in prop_d:
if proptype == 'continuous':
propdata[(0, isite)] = prop_d[site]
elif proptype == 'discrete':
propdata[(0, isite)] = propcategories.index(prop_d[site])
else:
raise ValueError('neither continuous nor discrete')
prop_image[shortname] = pylab.imshow(propdata, interpolation='nearest', aspect='auto', extent=[0, len(isites), 0.5, -0.5], cmap=cmap, vmin=vmin, vmax=vmax)
pylab.yticks([0], [shortname], size=8)
# set up colorbar axes, then color bars
ncolorbars = len([p for p in prop_types.values() if p[0] != 'wildtype'])
if scalebar:
ncolorbars += 1
if ncolorbars == 1:
colorbarwidth = 0.4
colorbarspacingwidth = 1.0 - colorbarwidth
elif ncolorbars:
colorbarspacingfrac = 0.5 # space between color bars is this fraction of bar width
colorbarwidth = 1.0 / (ncolorbars * (1.0 + colorbarspacingfrac)) # width of color bars in fraction of figure width
colorbarspacingwidth = colorbarwidth * colorbarspacingfrac # width of color bar spacing in fraction of figure width
# bottom of color bars
ybottom = 1.0 - (colorbar_tmargin + barheight) / figheight
propnames = {}
icolorbar = -1
icolorbarshift = 0
while icolorbar < len(overlay):
if icolorbar == -1:
# show scale bar if being used
icolorbar += 1
if scalebar:
(scalebarheight, scalebarlabel) = scalebar
xleft = (colorbarspacingwidth * 0.5 + icolorbar *
(colorbarwidth + colorbarspacingwidth))
ytop = 1 - colorbar_tmargin / figheight
scalebarheightfrac = scalebarheight / figheight
# follow here for fig axes: https://stackoverflow.com/a/5022412
fullfigax = pylab.axes([0, 0, 1, 1], facecolor=(1, 1, 1, 0))
fullfigax.axvline(x=xleft, ymin=ytop - scalebarheightfrac,
ymax=ytop, color='black', linewidth=1.5)
pylab.text(xleft + 0.005, ytop - scalebarheightfrac / 2.0,
scalebarlabel, verticalalignment='center',
horizontalalignment='left',
transform=fullfigax.transAxes)
continue
(prop_d, shortname, longname) = overlay[icolorbar]
icolorbar += 1
(proptype, vmin, vmax, propcategories) = prop_types[shortname]
if proptype == 'wildtype':
icolorbarshift += 1
continue
if shortname == longname or not longname:
propname = shortname
elif fixlongname:
propname = longname
else:
propname = "%s (%s)" % (longname, shortname)
colorbar_ax = pylab.axes([colorbarspacingwidth * 0.5 + (icolorbar - icolorbarshift - int(not bool(scalebar))) * (colorbarwidth + colorbarspacingwidth), ybottom, colorbarwidth, barheight / figheight], frameon=True)
colorbar_ax.xaxis.set_ticks_position('bottom')
colorbar_ax.yaxis.set_ticks_position('none')
pylab.xticks([])
pylab.yticks([])
pylab.title(propname, size=9)
if proptype == 'continuous':
cb = pylab.colorbar(prop_image[shortname], cax=colorbar_ax, orientation='horizontal')
# if range is close to zero to one, manually set tics to 0, 0.5, 1. This helps for RSA
if -0.1 <= vmin <= 0 and 1.0 <= vmax <= 1.15:
cb.set_ticks([0, 0.5, 1])
cb.set_ticklabels(['0', '0.5', '1'])
# if it seems plausible, set integer ticks
if 4 < (vmax - vmin) <= 11:
fixedticks = [itick for itick in range(int(vmin), int(vmax) + 1)]
cb.set_ticks(fixedticks)
cb.set_ticklabels([str(itick) for itick in fixedticks])
elif proptype == 'discrete':
cb = pylab.colorbar(prop_image[shortname], cax=colorbar_ax, orientation='horizontal', boundaries=[i for i in range(len(propcategories) + 1)], values=[i for i in range(len(propcategories))])
cb.set_ticks([i + 0.5 for i in range(len(propcategories))])
cb.set_ticklabels(propcategories)
else:
raise ValueError("Invalid proptype")
if shortname in fix_limits:
(ticklocs, ticknames) = fix_limits[shortname]
cb.set_ticks(ticklocs)
cb.set_ticklabels(ticknames)
# save the plot
pylab.savefig(overlayfile, transparent=True) | python | def LogoOverlay(sites, overlayfile, overlay, nperline, sitewidth, rmargin, logoheight, barheight, barspacing, fix_limits={}, fixlongname=False, overlay_cmap=None, underlay=False, scalebar=False):
"""Makes overlay for *LogoPlot*.
This function creates colored bars overlay bars showing up to two
properties.
The trick of this function is to create the bars the right
size so they align when they overlay the logo plot.
CALLING VARIABLES:
* *sites* : same as the variable of this name used by *LogoPlot*.
* *overlayfile* is a string giving the name of created PDF file containing
the overlay. It must end in the extension ``.pdf``.
* *overlay* : same as the variable of this name used by *LogoPlot*.
* *nperline* : same as the variable of this name used by *LogoPlot*.
* *sitewidth* is the width of each site in points.
* *rmargin* is the right margin in points.
* *logoheight* is the total height of each logo row in points.
* *barheight* is the total height of each bar in points.
* *barspacing* is the vertical spacing between bars in points.
* *fix_limits* has the same meaning of the variable of this name used by *LogoPlot*.
* *fixlongname* has the same meaning of the variable of this name used by *LogoPlot*.
* *overlay_cmap* has the same meaning of the variable of this name used by *LogoPlot*.
* *underlay* is a bool. If `True`, make an underlay rather than an overlay.
* *scalebar: if not `False`, is 2-tuple `(scalebarheight, scalebarlabel)`
where `scalebarheight` is in points.
"""
if os.path.splitext(overlayfile)[1] != '.pdf':
raise ValueError("overlayfile must end in .pdf: %s" % overlayfile)
if not overlay_cmap:
(cmap, mapping_d, mapper) = KyteDoolittleColorMapping()
else:
mapper = pylab.cm.ScalarMappable(cmap=overlay_cmap)
cmap = mapper.get_cmap()
pts_per_inch = 72.0 # to convert between points and inches
# some general properties of the plot
matplotlib.rc('text', usetex=True)
matplotlib.rc('xtick', labelsize=8)
matplotlib.rc('xtick', direction='out')
matplotlib.rc('ytick', direction='out')
matplotlib.rc('axes', linewidth=0.5)
matplotlib.rc('ytick.major', size=3)
matplotlib.rc('xtick.major', size=2.5)
# define sizes (still in points)
colorbar_bmargin = 20 # margin below color bars in points
colorbar_tmargin = 15 # margin above color bars in points
nlines = int(math.ceil(len(sites) / float(nperline)))
lmargin = 25 # left margin in points
barwidth = nperline * sitewidth
figwidth = lmargin + rmargin + barwidth
figheight = nlines * (logoheight + len(overlay) * (barheight +
barspacing)) + (barheight + colorbar_bmargin + colorbar_tmargin) + (
int(underlay) * len(overlay) * (barheight + barspacing))
# set up the figure and axes
fig = pylab.figure(figsize=(figwidth / pts_per_inch, figheight / pts_per_inch))
# determine property types
prop_types = {}
for (prop_d, shortname, longname) in overlay:
if shortname == longname == 'wildtype':
assert all([(isinstance(prop, str) and len(prop) == 1) for
prop in prop_d.values()]), 'prop_d does not give letters'
proptype = 'wildtype'
(vmin, vmax) = (0, 1) # not used, but need to be assigned
propcategories = None # not used, but needs to be assigned
elif all([isinstance(prop, str) for prop in prop_d.values()]):
proptype = 'discrete'
propcategories = list(set(prop_d.values()))
propcategories.sort()
(vmin, vmax) = (0, len(propcategories) - 1)
elif all ([isinstance(prop, (int, float)) for prop in prop_d.values()]):
proptype = 'continuous'
propcategories = None
(vmin, vmax) = (min(prop_d.values()), max(prop_d.values()))
# If vmin is slightly greater than zero, set it to zero. This helps for RSA properties.
if vmin >= 0 and vmin / float(vmax - vmin) < 0.05:
vmin = 0.0
# And if vmax is just a bit less than one, set it to that...
if 0.9 <= vmax <= 1.0:
vmax = 1.0
else:
raise ValueError("Property %s is neither continuous or discrete. Values are:\n%s" % (shortname, str(prop_d.items())))
if shortname in fix_limits:
(vmin, vmax) = (min(fix_limits[shortname][0]), max(fix_limits[shortname][0]))
assert vmin < vmax, "vmin >= vmax, did you incorrectly use fix_vmin and fix_vmax?"
prop_types[shortname] = (proptype, vmin, vmax, propcategories)
assert len(prop_types) == len(overlay), "Not as many property types as overlays. Did you give the same name (shortname) to multiple properties in the overlay?"
# loop over each line of the multi-lined plot
prop_image = {}
for iline in range(nlines):
isites = sites[iline * nperline : min(len(sites), (iline + 1) * nperline)]
xlength = len(isites) * sitewidth
logo_ax = pylab.axes([lmargin / figwidth, ((nlines - iline - 1) * (logoheight + len(overlay) * (barspacing + barheight))) / figheight, xlength / figwidth, logoheight / figheight], frameon=False)
logo_ax.yaxis.set_ticks_position('none')
logo_ax.xaxis.set_ticks_position('none')
pylab.yticks([])
pylab.xlim(0.5, len(isites) + 0.5)
pylab.xticks([])
for (iprop, (prop_d, shortname, longname)) in enumerate(overlay):
(proptype, vmin, vmax, propcategories) = prop_types[shortname]
prop_ax = pylab.axes([
lmargin / figwidth,
((nlines - iline - 1) * (logoheight +
len(overlay) * (barspacing + barheight)) +
(1 - int(underlay)) * logoheight + int(underlay) *
barspacing + iprop * (barspacing + barheight))
/ figheight,
xlength / figwidth,
barheight / figheight],
frameon=(proptype != 'wildtype'))
prop_ax.xaxis.set_ticks_position('none')
pylab.xticks([])
pylab.xlim((0, len(isites)))
pylab.ylim(-0.5, 0.5)
if proptype == 'wildtype':
pylab.yticks([])
prop_ax.yaxis.set_ticks_position('none')
for (isite, site) in enumerate(isites):
pylab.text(isite + 0.5, -0.5, prop_d[site], size=9,
horizontalalignment='center', family='monospace')
continue
pylab.yticks([0], [shortname], size=8)
prop_ax.yaxis.set_ticks_position('left')
propdata = pylab.zeros(shape=(1, len(isites)))
propdata[ : ] = pylab.nan # set to nan for all entries
for (isite, site) in enumerate(isites):
if site in prop_d:
if proptype == 'continuous':
propdata[(0, isite)] = prop_d[site]
elif proptype == 'discrete':
propdata[(0, isite)] = propcategories.index(prop_d[site])
else:
raise ValueError('neither continuous nor discrete')
prop_image[shortname] = pylab.imshow(propdata, interpolation='nearest', aspect='auto', extent=[0, len(isites), 0.5, -0.5], cmap=cmap, vmin=vmin, vmax=vmax)
pylab.yticks([0], [shortname], size=8)
# set up colorbar axes, then color bars
ncolorbars = len([p for p in prop_types.values() if p[0] != 'wildtype'])
if scalebar:
ncolorbars += 1
if ncolorbars == 1:
colorbarwidth = 0.4
colorbarspacingwidth = 1.0 - colorbarwidth
elif ncolorbars:
colorbarspacingfrac = 0.5 # space between color bars is this fraction of bar width
colorbarwidth = 1.0 / (ncolorbars * (1.0 + colorbarspacingfrac)) # width of color bars in fraction of figure width
colorbarspacingwidth = colorbarwidth * colorbarspacingfrac # width of color bar spacing in fraction of figure width
# bottom of color bars
ybottom = 1.0 - (colorbar_tmargin + barheight) / figheight
propnames = {}
icolorbar = -1
icolorbarshift = 0
while icolorbar < len(overlay):
if icolorbar == -1:
# show scale bar if being used
icolorbar += 1
if scalebar:
(scalebarheight, scalebarlabel) = scalebar
xleft = (colorbarspacingwidth * 0.5 + icolorbar *
(colorbarwidth + colorbarspacingwidth))
ytop = 1 - colorbar_tmargin / figheight
scalebarheightfrac = scalebarheight / figheight
# follow here for fig axes: https://stackoverflow.com/a/5022412
fullfigax = pylab.axes([0, 0, 1, 1], facecolor=(1, 1, 1, 0))
fullfigax.axvline(x=xleft, ymin=ytop - scalebarheightfrac,
ymax=ytop, color='black', linewidth=1.5)
pylab.text(xleft + 0.005, ytop - scalebarheightfrac / 2.0,
scalebarlabel, verticalalignment='center',
horizontalalignment='left',
transform=fullfigax.transAxes)
continue
(prop_d, shortname, longname) = overlay[icolorbar]
icolorbar += 1
(proptype, vmin, vmax, propcategories) = prop_types[shortname]
if proptype == 'wildtype':
icolorbarshift += 1
continue
if shortname == longname or not longname:
propname = shortname
elif fixlongname:
propname = longname
else:
propname = "%s (%s)" % (longname, shortname)
colorbar_ax = pylab.axes([colorbarspacingwidth * 0.5 + (icolorbar - icolorbarshift - int(not bool(scalebar))) * (colorbarwidth + colorbarspacingwidth), ybottom, colorbarwidth, barheight / figheight], frameon=True)
colorbar_ax.xaxis.set_ticks_position('bottom')
colorbar_ax.yaxis.set_ticks_position('none')
pylab.xticks([])
pylab.yticks([])
pylab.title(propname, size=9)
if proptype == 'continuous':
cb = pylab.colorbar(prop_image[shortname], cax=colorbar_ax, orientation='horizontal')
# if range is close to zero to one, manually set tics to 0, 0.5, 1. This helps for RSA
if -0.1 <= vmin <= 0 and 1.0 <= vmax <= 1.15:
cb.set_ticks([0, 0.5, 1])
cb.set_ticklabels(['0', '0.5', '1'])
# if it seems plausible, set integer ticks
if 4 < (vmax - vmin) <= 11:
fixedticks = [itick for itick in range(int(vmin), int(vmax) + 1)]
cb.set_ticks(fixedticks)
cb.set_ticklabels([str(itick) for itick in fixedticks])
elif proptype == 'discrete':
cb = pylab.colorbar(prop_image[shortname], cax=colorbar_ax, orientation='horizontal', boundaries=[i for i in range(len(propcategories) + 1)], values=[i for i in range(len(propcategories))])
cb.set_ticks([i + 0.5 for i in range(len(propcategories))])
cb.set_ticklabels(propcategories)
else:
raise ValueError("Invalid proptype")
if shortname in fix_limits:
(ticklocs, ticknames) = fix_limits[shortname]
cb.set_ticks(ticklocs)
cb.set_ticklabels(ticknames)
# save the plot
pylab.savefig(overlayfile, transparent=True) | [
"def",
"LogoOverlay",
"(",
"sites",
",",
"overlayfile",
",",
"overlay",
",",
"nperline",
",",
"sitewidth",
",",
"rmargin",
",",
"logoheight",
",",
"barheight",
",",
"barspacing",
",",
"fix_limits",
"=",
"{",
"}",
",",
"fixlongname",
"=",
"False",
",",
"ove... | Makes overlay for *LogoPlot*.
This function creates colored bars overlay bars showing up to two
properties.
The trick of this function is to create the bars the right
size so they align when they overlay the logo plot.
CALLING VARIABLES:
* *sites* : same as the variable of this name used by *LogoPlot*.
* *overlayfile* is a string giving the name of created PDF file containing
the overlay. It must end in the extension ``.pdf``.
* *overlay* : same as the variable of this name used by *LogoPlot*.
* *nperline* : same as the variable of this name used by *LogoPlot*.
* *sitewidth* is the width of each site in points.
* *rmargin* is the right margin in points.
* *logoheight* is the total height of each logo row in points.
* *barheight* is the total height of each bar in points.
* *barspacing* is the vertical spacing between bars in points.
* *fix_limits* has the same meaning of the variable of this name used by *LogoPlot*.
* *fixlongname* has the same meaning of the variable of this name used by *LogoPlot*.
* *overlay_cmap* has the same meaning of the variable of this name used by *LogoPlot*.
* *underlay* is a bool. If `True`, make an underlay rather than an overlay.
* *scalebar: if not `False`, is 2-tuple `(scalebarheight, scalebarlabel)`
where `scalebarheight` is in points. | [
"Makes",
"overlay",
"for",
"*",
"LogoPlot",
"*",
"."
] | train | https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/weblogo.py#L883-L1108 |
jbloomlab/phydms | phydmslib/weblogo.py | _my_Motif.read_transfac | def read_transfac( fin, alphabet = None) :
""" Parse a sequence matrix from a file.
Returns a tuple of (alphabet, matrix)
"""
items = []
start=True
for line in fin :
if line.isspace() or line[0] =='#' : continue
stuff = line.split()
if start and stuff[0] != 'PO' and stuff[0] != 'P0': continue
if stuff[0]=='XX' or stuff[0]=='//': break
start = False
items.append(stuff)
if len(items) < 2 :
raise ValueError("Vacuous file.")
# Is the first line a header line?
header = items.pop(0)
hcols = len(header)
rows = len(items)
cols = len(items[0])
if not( header[0] == 'PO' or header[0] =='P0' or hcols == cols-1 or hcols == cols-2) :
raise ValueError("Missing header line!")
# Do all lines (except the first) contain the same number of items?
cols = len(items[0])
for i in range(1, len(items)) :
if cols != len(items[i]) :
raise ValueError("Inconsistant length, row %d: " % i)
# Vertical or horizontal arrangement?
if header[0] == 'PO' or header[0] == 'P0': header.pop(0)
position_header = True
alphabet_header = True
for h in header :
if not corebio.utils.isint(h) : position_header = False
#allow non-alphabetic if not str.isalpha(h) : alphabet_header = False
if not position_header and not alphabet_header :
raise ValueError("Can't parse header: %s" % str(header))
if position_header and alphabet_header :
raise ValueError("Can't parse header")
# Check row headers
if alphabet_header :
for i,r in enumerate(items) :
if not corebio.utils.isint(r[0]) and r[0][0]!='P' :
raise ValueError(
"Expected position as first item on line %d" % i)
r.pop(0)
defacto_alphabet = ''.join(header)
else :
a = []
for i,r in enumerate(items) :
if not ischar(r[0]) and r[0][0]!='P' :
raise ValueError(
"Expected position as first item on line %d" % i)
a.append(r.pop(0))
defacto_alphabet = ''.join(a)
# Check defacto_alphabet
defacto_alphabet = corebio.seq.Alphabet(defacto_alphabet)
if alphabet :
if not defacto_alphabet.alphabetic(alphabet) :
raise ValueError("Incompatible alphabets: %s , %s (defacto)"
% (alphabet, defacto_alphabet))
else :
alphabets = (unambiguous_rna_alphabet,
unambiguous_dna_alphabet,
unambiguous_protein_alphabet,
)
for a in alphabets :
if defacto_alphabet.alphabetic(a) :
alphabet = a
break
if not alphabet :
alphabet = defacto_alphabet
# The last item of each row may be extra cruft. Remove
if len(items[0]) == len(header) +1 :
for r in items :
r.pop()
# items should now be a list of lists of numbers (as strings)
rows = len(items)
cols = len(items[0])
matrix = numpy.zeros( (rows,cols) , dtype=numpy.float64)
for r in range( rows) :
for c in range(cols):
matrix[r,c] = float( items[r][c])
if position_header :
matrix.transpose()
return _my_Motif(defacto_alphabet, matrix).reindex(alphabet) | python | def read_transfac( fin, alphabet = None) :
""" Parse a sequence matrix from a file.
Returns a tuple of (alphabet, matrix)
"""
items = []
start=True
for line in fin :
if line.isspace() or line[0] =='#' : continue
stuff = line.split()
if start and stuff[0] != 'PO' and stuff[0] != 'P0': continue
if stuff[0]=='XX' or stuff[0]=='//': break
start = False
items.append(stuff)
if len(items) < 2 :
raise ValueError("Vacuous file.")
# Is the first line a header line?
header = items.pop(0)
hcols = len(header)
rows = len(items)
cols = len(items[0])
if not( header[0] == 'PO' or header[0] =='P0' or hcols == cols-1 or hcols == cols-2) :
raise ValueError("Missing header line!")
# Do all lines (except the first) contain the same number of items?
cols = len(items[0])
for i in range(1, len(items)) :
if cols != len(items[i]) :
raise ValueError("Inconsistant length, row %d: " % i)
# Vertical or horizontal arrangement?
if header[0] == 'PO' or header[0] == 'P0': header.pop(0)
position_header = True
alphabet_header = True
for h in header :
if not corebio.utils.isint(h) : position_header = False
#allow non-alphabetic if not str.isalpha(h) : alphabet_header = False
if not position_header and not alphabet_header :
raise ValueError("Can't parse header: %s" % str(header))
if position_header and alphabet_header :
raise ValueError("Can't parse header")
# Check row headers
if alphabet_header :
for i,r in enumerate(items) :
if not corebio.utils.isint(r[0]) and r[0][0]!='P' :
raise ValueError(
"Expected position as first item on line %d" % i)
r.pop(0)
defacto_alphabet = ''.join(header)
else :
a = []
for i,r in enumerate(items) :
if not ischar(r[0]) and r[0][0]!='P' :
raise ValueError(
"Expected position as first item on line %d" % i)
a.append(r.pop(0))
defacto_alphabet = ''.join(a)
# Check defacto_alphabet
defacto_alphabet = corebio.seq.Alphabet(defacto_alphabet)
if alphabet :
if not defacto_alphabet.alphabetic(alphabet) :
raise ValueError("Incompatible alphabets: %s , %s (defacto)"
% (alphabet, defacto_alphabet))
else :
alphabets = (unambiguous_rna_alphabet,
unambiguous_dna_alphabet,
unambiguous_protein_alphabet,
)
for a in alphabets :
if defacto_alphabet.alphabetic(a) :
alphabet = a
break
if not alphabet :
alphabet = defacto_alphabet
# The last item of each row may be extra cruft. Remove
if len(items[0]) == len(header) +1 :
for r in items :
r.pop()
# items should now be a list of lists of numbers (as strings)
rows = len(items)
cols = len(items[0])
matrix = numpy.zeros( (rows,cols) , dtype=numpy.float64)
for r in range( rows) :
for c in range(cols):
matrix[r,c] = float( items[r][c])
if position_header :
matrix.transpose()
return _my_Motif(defacto_alphabet, matrix).reindex(alphabet) | [
"def",
"read_transfac",
"(",
"fin",
",",
"alphabet",
"=",
"None",
")",
":",
"items",
"=",
"[",
"]",
"start",
"=",
"True",
"for",
"line",
"in",
"fin",
":",
"if",
"line",
".",
"isspace",
"(",
")",
"or",
"line",
"[",
"0",
"]",
"==",
"'#'",
":",
"c... | Parse a sequence matrix from a file.
Returns a tuple of (alphabet, matrix) | [
"Parse",
"a",
"sequence",
"matrix",
"from",
"a",
"file",
".",
"Returns",
"a",
"tuple",
"of",
"(",
"alphabet",
"matrix",
")"
] | train | https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/weblogo.py#L776-L877 |
ubccr/pinky | pinky/mol/molecule.py | Molecule.pruneToAtoms | def pruneToAtoms(self, atoms):
"""Prune the molecule to the specified atoms
bonds will be removed atomatically"""
_atoms = self.atoms[:]
for atom in _atoms:
if atom not in atoms:
self.remove_atom(atom) | python | def pruneToAtoms(self, atoms):
"""Prune the molecule to the specified atoms
bonds will be removed atomatically"""
_atoms = self.atoms[:]
for atom in _atoms:
if atom not in atoms:
self.remove_atom(atom) | [
"def",
"pruneToAtoms",
"(",
"self",
",",
"atoms",
")",
":",
"_atoms",
"=",
"self",
".",
"atoms",
"[",
":",
"]",
"for",
"atom",
"in",
"_atoms",
":",
"if",
"atom",
"not",
"in",
"atoms",
":",
"self",
".",
"remove_atom",
"(",
"atom",
")"
] | Prune the molecule to the specified atoms
bonds will be removed atomatically | [
"Prune",
"the",
"molecule",
"to",
"the",
"specified",
"atoms",
"bonds",
"will",
"be",
"removed",
"atomatically"
] | train | https://github.com/ubccr/pinky/blob/e9d6e8ff72aa7f670b591e3bd3629cb879db1a93/pinky/mol/molecule.py#L192-L198 |
shawalli/psycopg2-pgevents | psycopg2_pgevents/event.py | poll | def poll(connection: connection, timeout: float=1.0) -> Iterable[Event]:
"""Poll the connection for notification events.
This method operates as an iterable. It will keep returning events until
all events have been read.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
timeout: float
Number of seconds to block for an event before timing out.
Returns
-------
event: Event or None
If an event is available, an Event is returned.
If no event is available, None is returned.
Examples
--------
>>> events = [evt for evt in connection.poll()]
>>> for evt in connection.poll():
print(evt)
"""
if timeout > 0.0:
log('Polling for events (Blocking, {} seconds)...'.format(timeout), logger_name=_LOGGER_NAME)
else:
log('Polling for events (Non-Blocking)...', logger_name=_LOGGER_NAME)
if select.select([connection], [], [], timeout) == ([], [], []):
log('...No events found', logger_name=_LOGGER_NAME)
return
else:
log('Events', logger_name=_LOGGER_NAME)
log('------', logger_name=_LOGGER_NAME)
connection.poll()
while connection.notifies:
event = connection.notifies.pop(0)
log(str(event), logger_name=_LOGGER_NAME)
yield Event.fromjson(event.payload) | python | def poll(connection: connection, timeout: float=1.0) -> Iterable[Event]:
"""Poll the connection for notification events.
This method operates as an iterable. It will keep returning events until
all events have been read.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
timeout: float
Number of seconds to block for an event before timing out.
Returns
-------
event: Event or None
If an event is available, an Event is returned.
If no event is available, None is returned.
Examples
--------
>>> events = [evt for evt in connection.poll()]
>>> for evt in connection.poll():
print(evt)
"""
if timeout > 0.0:
log('Polling for events (Blocking, {} seconds)...'.format(timeout), logger_name=_LOGGER_NAME)
else:
log('Polling for events (Non-Blocking)...', logger_name=_LOGGER_NAME)
if select.select([connection], [], [], timeout) == ([], [], []):
log('...No events found', logger_name=_LOGGER_NAME)
return
else:
log('Events', logger_name=_LOGGER_NAME)
log('------', logger_name=_LOGGER_NAME)
connection.poll()
while connection.notifies:
event = connection.notifies.pop(0)
log(str(event), logger_name=_LOGGER_NAME)
yield Event.fromjson(event.payload) | [
"def",
"poll",
"(",
"connection",
":",
"connection",
",",
"timeout",
":",
"float",
"=",
"1.0",
")",
"->",
"Iterable",
"[",
"Event",
"]",
":",
"if",
"timeout",
">",
"0.0",
":",
"log",
"(",
"'Polling for events (Blocking, {} seconds)...'",
".",
"format",
"(",
... | Poll the connection for notification events.
This method operates as an iterable. It will keep returning events until
all events have been read.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
timeout: float
Number of seconds to block for an event before timing out.
Returns
-------
event: Event or None
If an event is available, an Event is returned.
If no event is available, None is returned.
Examples
--------
>>> events = [evt for evt in connection.poll()]
>>> for evt in connection.poll():
print(evt) | [
"Poll",
"the",
"connection",
"for",
"notification",
"events",
"."
] | train | https://github.com/shawalli/psycopg2-pgevents/blob/bf04c05839a27c56834b26748d227c71cd87257c/psycopg2_pgevents/event.py#L154-L196 |
shawalli/psycopg2-pgevents | psycopg2_pgevents/event.py | Event.fromjson | def fromjson(cls, json_string: str) -> 'Event':
"""Create a new Event from a from a psycopg2-pgevent event JSON.
Parameters
----------
json_string: str
Valid psycopg2-pgevent event JSON.
Returns
-------
Event
Event created from JSON deserialization.
"""
obj = json.loads(json_string)
return cls(
UUID(obj['event_id']),
obj['event_type'],
obj['schema_name'],
obj['table_name'],
obj['row_id']
) | python | def fromjson(cls, json_string: str) -> 'Event':
"""Create a new Event from a from a psycopg2-pgevent event JSON.
Parameters
----------
json_string: str
Valid psycopg2-pgevent event JSON.
Returns
-------
Event
Event created from JSON deserialization.
"""
obj = json.loads(json_string)
return cls(
UUID(obj['event_id']),
obj['event_type'],
obj['schema_name'],
obj['table_name'],
obj['row_id']
) | [
"def",
"fromjson",
"(",
"cls",
",",
"json_string",
":",
"str",
")",
"->",
"'Event'",
":",
"obj",
"=",
"json",
".",
"loads",
"(",
"json_string",
")",
"return",
"cls",
"(",
"UUID",
"(",
"obj",
"[",
"'event_id'",
"]",
")",
",",
"obj",
"[",
"'event_type'... | Create a new Event from a from a psycopg2-pgevent event JSON.
Parameters
----------
json_string: str
Valid psycopg2-pgevent event JSON.
Returns
-------
Event
Event created from JSON deserialization. | [
"Create",
"a",
"new",
"Event",
"from",
"a",
"from",
"a",
"psycopg2",
"-",
"pgevent",
"event",
"JSON",
"."
] | train | https://github.com/shawalli/psycopg2-pgevents/blob/bf04c05839a27c56834b26748d227c71cd87257c/psycopg2_pgevents/event.py#L79-L100 |
shawalli/psycopg2-pgevents | psycopg2_pgevents/event.py | Event.tojson | def tojson(self) -> str:
"""Serialize an Event into JSON.
Returns
-------
str
JSON-serialized Event.
"""
return json.dumps({
'event_id': str(self.id),
'event_type': self.type,
'schema_name': self.schema_name,
'table_name': self.table_name,
'row_id': self.row_id
}) | python | def tojson(self) -> str:
"""Serialize an Event into JSON.
Returns
-------
str
JSON-serialized Event.
"""
return json.dumps({
'event_id': str(self.id),
'event_type': self.type,
'schema_name': self.schema_name,
'table_name': self.table_name,
'row_id': self.row_id
}) | [
"def",
"tojson",
"(",
"self",
")",
"->",
"str",
":",
"return",
"json",
".",
"dumps",
"(",
"{",
"'event_id'",
":",
"str",
"(",
"self",
".",
"id",
")",
",",
"'event_type'",
":",
"self",
".",
"type",
",",
"'schema_name'",
":",
"self",
".",
"schema_name"... | Serialize an Event into JSON.
Returns
-------
str
JSON-serialized Event. | [
"Serialize",
"an",
"Event",
"into",
"JSON",
"."
] | train | https://github.com/shawalli/psycopg2-pgevents/blob/bf04c05839a27c56834b26748d227c71cd87257c/psycopg2_pgevents/event.py#L102-L117 |
mikekatz04/BOWIE | bowie/plotutils/makeprocess.py | MakePlotProcess.input_data | def input_data(self):
"""Function to extract data from files according to pid.
This function will read in the data with
:class:`bowie.plotutils.readdata.ReadInData`.
"""
ordererd = np.sort(np.asarray(list(self.plot_info.keys())).astype(int))
trans_cont_dict = OrderedDict()
for i in ordererd:
trans_cont_dict[str(i)] = self.plot_info[str(i)]
self.plot_info = trans_cont_dict
# set empty lists for x,y,z
x = [[]for i in np.arange(len(self.plot_info.keys()))]
y = [[] for i in np.arange(len(self.plot_info.keys()))]
z = [[] for i in np.arange(len(self.plot_info.keys()))]
# read in base files/data
for k, axis_string in enumerate(self.plot_info.keys()):
if 'file' not in self.plot_info[axis_string].keys():
continue
for j, file_dict in enumerate(self.plot_info[axis_string]['file']):
data_class = ReadInData(**{**self.general, **file_dict,
**self.plot_info[axis_string]['limits']})
x[k].append(data_class.x_append_value)
y[k].append(data_class.y_append_value)
z[k].append(data_class.z_append_value)
# print(axis_string)
# add data from plots to current plot based on index
for k, axis_string in enumerate(self.plot_info.keys()):
# takes first file from plot
if 'indices' in self.plot_info[axis_string]:
if type(self.plot_info[axis_string]['indices']) == int:
self.plot_info[axis_string]['indices'] = (
[self.plot_info[axis_string]['indices']])
for index in self.plot_info[axis_string]['indices']:
index = int(index)
x[k].append(x[index][0])
y[k].append(y[index][0])
z[k].append(z[index][0])
# read or append control values for ratio plots
for k, axis_string in enumerate(self.plot_info.keys()):
if 'control' in self.plot_info[axis_string]:
if ('name' in self.plot_info[axis_string]['control'] or
'label' in self.plot_info[axis_string]['control']):
file_dict = self.plot_info[axis_string]['control']
if 'limits' in self.plot_info[axis_string].keys():
liimits_dict = self.plot_info[axis_string]['limits']
data_class = ReadInData(**{**self.general, **file_dict,
**self.plot_info[axis_string]['limits']})
x[k].append(data_class.x_append_value)
y[k].append(data_class.y_append_value)
z[k].append(data_class.z_append_value)
elif 'index' in self.plot_info[axis_string]['control']:
index = int(self.plot_info[axis_string]['control']['index'])
x[k].append(x[index][0])
y[k].append(y[index][0])
z[k].append(z[index][0])
# print(axis_string)
# transfer lists in PlotVals class.
value_classes = []
for k in range(len(x)):
value_classes.append(PlotVals(x[k], y[k], z[k]))
self.value_classes = value_classes
return | python | def input_data(self):
"""Function to extract data from files according to pid.
This function will read in the data with
:class:`bowie.plotutils.readdata.ReadInData`.
"""
ordererd = np.sort(np.asarray(list(self.plot_info.keys())).astype(int))
trans_cont_dict = OrderedDict()
for i in ordererd:
trans_cont_dict[str(i)] = self.plot_info[str(i)]
self.plot_info = trans_cont_dict
# set empty lists for x,y,z
x = [[]for i in np.arange(len(self.plot_info.keys()))]
y = [[] for i in np.arange(len(self.plot_info.keys()))]
z = [[] for i in np.arange(len(self.plot_info.keys()))]
# read in base files/data
for k, axis_string in enumerate(self.plot_info.keys()):
if 'file' not in self.plot_info[axis_string].keys():
continue
for j, file_dict in enumerate(self.plot_info[axis_string]['file']):
data_class = ReadInData(**{**self.general, **file_dict,
**self.plot_info[axis_string]['limits']})
x[k].append(data_class.x_append_value)
y[k].append(data_class.y_append_value)
z[k].append(data_class.z_append_value)
# print(axis_string)
# add data from plots to current plot based on index
for k, axis_string in enumerate(self.plot_info.keys()):
# takes first file from plot
if 'indices' in self.plot_info[axis_string]:
if type(self.plot_info[axis_string]['indices']) == int:
self.plot_info[axis_string]['indices'] = (
[self.plot_info[axis_string]['indices']])
for index in self.plot_info[axis_string]['indices']:
index = int(index)
x[k].append(x[index][0])
y[k].append(y[index][0])
z[k].append(z[index][0])
# read or append control values for ratio plots
for k, axis_string in enumerate(self.plot_info.keys()):
if 'control' in self.plot_info[axis_string]:
if ('name' in self.plot_info[axis_string]['control'] or
'label' in self.plot_info[axis_string]['control']):
file_dict = self.plot_info[axis_string]['control']
if 'limits' in self.plot_info[axis_string].keys():
liimits_dict = self.plot_info[axis_string]['limits']
data_class = ReadInData(**{**self.general, **file_dict,
**self.plot_info[axis_string]['limits']})
x[k].append(data_class.x_append_value)
y[k].append(data_class.y_append_value)
z[k].append(data_class.z_append_value)
elif 'index' in self.plot_info[axis_string]['control']:
index = int(self.plot_info[axis_string]['control']['index'])
x[k].append(x[index][0])
y[k].append(y[index][0])
z[k].append(z[index][0])
# print(axis_string)
# transfer lists in PlotVals class.
value_classes = []
for k in range(len(x)):
value_classes.append(PlotVals(x[k], y[k], z[k]))
self.value_classes = value_classes
return | [
"def",
"input_data",
"(",
"self",
")",
":",
"ordererd",
"=",
"np",
".",
"sort",
"(",
"np",
".",
"asarray",
"(",
"list",
"(",
"self",
".",
"plot_info",
".",
"keys",
"(",
")",
")",
")",
".",
"astype",
"(",
"int",
")",
")",
"trans_cont_dict",
"=",
"... | Function to extract data from files according to pid.
This function will read in the data with
:class:`bowie.plotutils.readdata.ReadInData`. | [
"Function",
"to",
"extract",
"data",
"from",
"files",
"according",
"to",
"pid",
"."
] | train | https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/bowie/plotutils/makeprocess.py#L96-L178 |
mikekatz04/BOWIE | bowie/plotutils/makeprocess.py | MakePlotProcess.setup_figure | def setup_figure(self):
"""Sets up the initial figure on to which every plot is added.
"""
# declare figure and axes environments
fig, ax = plt.subplots(nrows=int(self.num_rows),
ncols=int(self.num_cols),
sharex=self.sharex,
sharey=self.sharey)
fig.set_size_inches(self.figure_width, self.figure_height)
# create list of ax. Catch error if it is a single plot.
try:
ax = ax.ravel()
except AttributeError:
ax = [ax]
# create list of plot types
self.plot_types = [self.plot_info[str(i)]['plot_type'] for i in range(len(ax))]
if len(self.plot_types) == 1:
if self.plot_types[0] not in self.colorbars:
self.colorbars[self.plot_types[0]] = {'cbar_pos': 5}
else:
if 'cbar_pos' not in self.colorbars[self.plot_types[0]]:
self.colorbars[self.plot_types[0]]['cbar_pos'] = 5
# prepare colorbar classes
self.colorbar_classes = {}
for plot_type in self.plot_types:
if plot_type in self.colorbar_classes:
continue
if plot_type == 'Horizon':
self.colorbar_classes[plot_type] = None
elif plot_type in self.colorbars:
self.colorbar_classes[plot_type] = FigColorbar(fig, plot_type,
**self.colorbars[plot_type])
else:
self.colorbar_classes[plot_type] = FigColorbar(fig, plot_type)
# set subplots_adjust settings
if 'Ratio' in self.plot_types or 'Waterfall':
self.subplots_adjust_kwargs['right'] = 0.79
# adjust figure sizes
fig.subplots_adjust(**self.subplots_adjust_kwargs)
if 'fig_y_label' in self.__dict__.keys():
fig.text(self.fig_y_label_x,
self.fig_y_label_y,
r'{}'.format(self.fig_y_label),
**self.fig_y_label_kwargs)
if 'fig_x_label' in self.__dict__.keys():
fig.text(self.fig_x_label_x,
self.fig_x_label_y,
r'{}'.format(self.fig_x_label),
**self.fig_x_label_kwargs)
if 'fig_title' in self.__dict__.keys():
fig.text(self.fig_title_kwargs['x'],
self.fig_title_kwargs['y'],
r'{}'.format(self.fig_title),
**self.fig_title_kwargs)
self.fig, self.ax = fig, ax
return | python | def setup_figure(self):
"""Sets up the initial figure on to which every plot is added.
"""
# declare figure and axes environments
fig, ax = plt.subplots(nrows=int(self.num_rows),
ncols=int(self.num_cols),
sharex=self.sharex,
sharey=self.sharey)
fig.set_size_inches(self.figure_width, self.figure_height)
# create list of ax. Catch error if it is a single plot.
try:
ax = ax.ravel()
except AttributeError:
ax = [ax]
# create list of plot types
self.plot_types = [self.plot_info[str(i)]['plot_type'] for i in range(len(ax))]
if len(self.plot_types) == 1:
if self.plot_types[0] not in self.colorbars:
self.colorbars[self.plot_types[0]] = {'cbar_pos': 5}
else:
if 'cbar_pos' not in self.colorbars[self.plot_types[0]]:
self.colorbars[self.plot_types[0]]['cbar_pos'] = 5
# prepare colorbar classes
self.colorbar_classes = {}
for plot_type in self.plot_types:
if plot_type in self.colorbar_classes:
continue
if plot_type == 'Horizon':
self.colorbar_classes[plot_type] = None
elif plot_type in self.colorbars:
self.colorbar_classes[plot_type] = FigColorbar(fig, plot_type,
**self.colorbars[plot_type])
else:
self.colorbar_classes[plot_type] = FigColorbar(fig, plot_type)
# set subplots_adjust settings
if 'Ratio' in self.plot_types or 'Waterfall':
self.subplots_adjust_kwargs['right'] = 0.79
# adjust figure sizes
fig.subplots_adjust(**self.subplots_adjust_kwargs)
if 'fig_y_label' in self.__dict__.keys():
fig.text(self.fig_y_label_x,
self.fig_y_label_y,
r'{}'.format(self.fig_y_label),
**self.fig_y_label_kwargs)
if 'fig_x_label' in self.__dict__.keys():
fig.text(self.fig_x_label_x,
self.fig_x_label_y,
r'{}'.format(self.fig_x_label),
**self.fig_x_label_kwargs)
if 'fig_title' in self.__dict__.keys():
fig.text(self.fig_title_kwargs['x'],
self.fig_title_kwargs['y'],
r'{}'.format(self.fig_title),
**self.fig_title_kwargs)
self.fig, self.ax = fig, ax
return | [
"def",
"setup_figure",
"(",
"self",
")",
":",
"# declare figure and axes environments",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"nrows",
"=",
"int",
"(",
"self",
".",
"num_rows",
")",
",",
"ncols",
"=",
"int",
"(",
"self",
".",
"num_cols",
")... | Sets up the initial figure on to which every plot is added. | [
"Sets",
"up",
"the",
"initial",
"figure",
"on",
"to",
"which",
"every",
"plot",
"is",
"added",
"."
] | train | https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/bowie/plotutils/makeprocess.py#L180-L250 |
mikekatz04/BOWIE | bowie/plotutils/makeprocess.py | MakePlotProcess.create_plots | def create_plots(self):
"""Creates plots according to each plotting class.
"""
for i, axis in enumerate(self.ax):
# plot everything. First check general dict for parameters related to plots.
trans_plot_class_call = globals()[self.plot_types[i]]
trans_plot_class = trans_plot_class_call(self.fig, axis,
self.value_classes[i].x_arr_list,
self.value_classes[i].y_arr_list,
self.value_classes[i].z_arr_list,
colorbar=(
self.colorbar_classes[self.plot_types[i]]),
**{**self.general,
**self.figure,
**self.plot_info[str(i)],
**self.plot_info[str(i)]['limits'],
**self.plot_info[str(i)]['label'],
**self.plot_info[str(i)]['extra'],
**self.plot_info[str(i)]['legend']})
# create the plot
trans_plot_class.make_plot()
# setup the plot
trans_plot_class.setup_plot()
# print("Axis", i, "Complete")
return | python | def create_plots(self):
"""Creates plots according to each plotting class.
"""
for i, axis in enumerate(self.ax):
# plot everything. First check general dict for parameters related to plots.
trans_plot_class_call = globals()[self.plot_types[i]]
trans_plot_class = trans_plot_class_call(self.fig, axis,
self.value_classes[i].x_arr_list,
self.value_classes[i].y_arr_list,
self.value_classes[i].z_arr_list,
colorbar=(
self.colorbar_classes[self.plot_types[i]]),
**{**self.general,
**self.figure,
**self.plot_info[str(i)],
**self.plot_info[str(i)]['limits'],
**self.plot_info[str(i)]['label'],
**self.plot_info[str(i)]['extra'],
**self.plot_info[str(i)]['legend']})
# create the plot
trans_plot_class.make_plot()
# setup the plot
trans_plot_class.setup_plot()
# print("Axis", i, "Complete")
return | [
"def",
"create_plots",
"(",
"self",
")",
":",
"for",
"i",
",",
"axis",
"in",
"enumerate",
"(",
"self",
".",
"ax",
")",
":",
"# plot everything. First check general dict for parameters related to plots.",
"trans_plot_class_call",
"=",
"globals",
"(",
")",
"[",
"self"... | Creates plots according to each plotting class. | [
"Creates",
"plots",
"according",
"to",
"each",
"plotting",
"class",
"."
] | train | https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/bowie/plotutils/makeprocess.py#L252-L280 |
cidles/pressagio | src/pressagio/dbconnector.py | DatabaseConnector.create_ngram_table | def create_ngram_table(self, cardinality):
"""
Creates a table for n-gram of a give cardinality. The table name is
constructed from this parameter, for example for cardinality `2` there
will be a table `_2_gram` created.
Parameters
----------
cardinality : int
The cardinality to create a table for.
"""
query = "CREATE TABLE IF NOT EXISTS _{0}_gram (".format(cardinality)
unique = ""
for i in reversed(range(cardinality)):
if i != 0:
unique += "word_{0}, ".format(i)
query += "word_{0} TEXT, ".format(i)
else:
unique += "word"
query += "word TEXT, count INTEGER, UNIQUE({0}) );".format(
unique)
self.execute_sql(query) | python | def create_ngram_table(self, cardinality):
"""
Creates a table for n-gram of a give cardinality. The table name is
constructed from this parameter, for example for cardinality `2` there
will be a table `_2_gram` created.
Parameters
----------
cardinality : int
The cardinality to create a table for.
"""
query = "CREATE TABLE IF NOT EXISTS _{0}_gram (".format(cardinality)
unique = ""
for i in reversed(range(cardinality)):
if i != 0:
unique += "word_{0}, ".format(i)
query += "word_{0} TEXT, ".format(i)
else:
unique += "word"
query += "word TEXT, count INTEGER, UNIQUE({0}) );".format(
unique)
self.execute_sql(query) | [
"def",
"create_ngram_table",
"(",
"self",
",",
"cardinality",
")",
":",
"query",
"=",
"\"CREATE TABLE IF NOT EXISTS _{0}_gram (\"",
".",
"format",
"(",
"cardinality",
")",
"unique",
"=",
"\"\"",
"for",
"i",
"in",
"reversed",
"(",
"range",
"(",
"cardinality",
")"... | Creates a table for n-gram of a give cardinality. The table name is
constructed from this parameter, for example for cardinality `2` there
will be a table `_2_gram` created.
Parameters
----------
cardinality : int
The cardinality to create a table for. | [
"Creates",
"a",
"table",
"for",
"n",
"-",
"gram",
"of",
"a",
"give",
"cardinality",
".",
"The",
"table",
"name",
"is",
"constructed",
"from",
"this",
"parameter",
"for",
"example",
"for",
"cardinality",
"2",
"there",
"will",
"be",
"a",
"table",
"_2_gram",
... | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L56-L79 |
cidles/pressagio | src/pressagio/dbconnector.py | DatabaseConnector.create_index | def create_index(self, cardinality):
"""
Create an index for the table with the given cardinality.
Parameters
----------
cardinality : int
The cardinality to create a index for.
"""
for i in reversed(range(cardinality)):
if i != 0:
query = "CREATE INDEX idx_{0}_gram_{1} ON _{0}_gram(word_{1});".format(cardinality, i)
self.execute_sql(query) | python | def create_index(self, cardinality):
"""
Create an index for the table with the given cardinality.
Parameters
----------
cardinality : int
The cardinality to create a index for.
"""
for i in reversed(range(cardinality)):
if i != 0:
query = "CREATE INDEX idx_{0}_gram_{1} ON _{0}_gram(word_{1});".format(cardinality, i)
self.execute_sql(query) | [
"def",
"create_index",
"(",
"self",
",",
"cardinality",
")",
":",
"for",
"i",
"in",
"reversed",
"(",
"range",
"(",
"cardinality",
")",
")",
":",
"if",
"i",
"!=",
"0",
":",
"query",
"=",
"\"CREATE INDEX idx_{0}_gram_{1} ON _{0}_gram(word_{1});\"",
".",
"format"... | Create an index for the table with the given cardinality.
Parameters
----------
cardinality : int
The cardinality to create a index for. | [
"Create",
"an",
"index",
"for",
"the",
"table",
"with",
"the",
"given",
"cardinality",
"."
] | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L97-L110 |
cidles/pressagio | src/pressagio/dbconnector.py | DatabaseConnector.ngrams | def ngrams(self, with_counts=False):
"""
Returns all ngrams that are in the table.
Parameters
----------
None
Returns
-------
ngrams : generator
A generator for ngram tuples.
"""
query = "SELECT "
for i in reversed(range(self.cardinality)):
if i != 0:
query += "word_{0}, ".format(i)
elif i == 0:
query += "word"
if with_counts:
query += ", count"
query += " FROM _{0}_gram;".format(self.cardinality)
result = self.execute_sql(query)
for row in result:
yield tuple(row) | python | def ngrams(self, with_counts=False):
"""
Returns all ngrams that are in the table.
Parameters
----------
None
Returns
-------
ngrams : generator
A generator for ngram tuples.
"""
query = "SELECT "
for i in reversed(range(self.cardinality)):
if i != 0:
query += "word_{0}, ".format(i)
elif i == 0:
query += "word"
if with_counts:
query += ", count"
query += " FROM _{0}_gram;".format(self.cardinality)
result = self.execute_sql(query)
for row in result:
yield tuple(row) | [
"def",
"ngrams",
"(",
"self",
",",
"with_counts",
"=",
"False",
")",
":",
"query",
"=",
"\"SELECT \"",
"for",
"i",
"in",
"reversed",
"(",
"range",
"(",
"self",
".",
"cardinality",
")",
")",
":",
"if",
"i",
"!=",
"0",
":",
"query",
"+=",
"\"word_{0}, ... | Returns all ngrams that are in the table.
Parameters
----------
None
Returns
-------
ngrams : generator
A generator for ngram tuples. | [
"Returns",
"all",
"ngrams",
"that",
"are",
"in",
"the",
"table",
"."
] | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L150-L178 |
cidles/pressagio | src/pressagio/dbconnector.py | DatabaseConnector.ngram_count | def ngram_count(self, ngram):
"""
Gets the count for a given ngram from the database.
Parameters
----------
ngram : iterable of str
A list, set or tuple of strings.
Returns
-------
count : int
The count of the ngram.
"""
query = "SELECT count FROM _{0}_gram".format(len(ngram))
query += self._build_where_clause(ngram)
query += ";"
result = self.execute_sql(query)
return self._extract_first_integer(result) | python | def ngram_count(self, ngram):
"""
Gets the count for a given ngram from the database.
Parameters
----------
ngram : iterable of str
A list, set or tuple of strings.
Returns
-------
count : int
The count of the ngram.
"""
query = "SELECT count FROM _{0}_gram".format(len(ngram))
query += self._build_where_clause(ngram)
query += ";"
result = self.execute_sql(query)
return self._extract_first_integer(result) | [
"def",
"ngram_count",
"(",
"self",
",",
"ngram",
")",
":",
"query",
"=",
"\"SELECT count FROM _{0}_gram\"",
".",
"format",
"(",
"len",
"(",
"ngram",
")",
")",
"query",
"+=",
"self",
".",
"_build_where_clause",
"(",
"ngram",
")",
"query",
"+=",
"\";\"",
"re... | Gets the count for a given ngram from the database.
Parameters
----------
ngram : iterable of str
A list, set or tuple of strings.
Returns
-------
count : int
The count of the ngram. | [
"Gets",
"the",
"count",
"for",
"a",
"given",
"ngram",
"from",
"the",
"database",
"."
] | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L185-L206 |
cidles/pressagio | src/pressagio/dbconnector.py | DatabaseConnector.insert_ngram | def insert_ngram(self, ngram, count):
"""
Inserts a given n-gram with count into the database.
Parameters
----------
ngram : iterable of str
A list, set or tuple of strings.
count : int
The count for the given n-gram.
"""
query = "INSERT INTO _{0}_gram {1};".format(len(ngram),
self._build_values_clause(ngram, count))
self.execute_sql(query) | python | def insert_ngram(self, ngram, count):
"""
Inserts a given n-gram with count into the database.
Parameters
----------
ngram : iterable of str
A list, set or tuple of strings.
count : int
The count for the given n-gram.
"""
query = "INSERT INTO _{0}_gram {1};".format(len(ngram),
self._build_values_clause(ngram, count))
self.execute_sql(query) | [
"def",
"insert_ngram",
"(",
"self",
",",
"ngram",
",",
"count",
")",
":",
"query",
"=",
"\"INSERT INTO _{0}_gram {1};\"",
".",
"format",
"(",
"len",
"(",
"ngram",
")",
",",
"self",
".",
"_build_values_clause",
"(",
"ngram",
",",
"count",
")",
")",
"self",
... | Inserts a given n-gram with count into the database.
Parameters
----------
ngram : iterable of str
A list, set or tuple of strings.
count : int
The count for the given n-gram. | [
"Inserts",
"a",
"given",
"n",
"-",
"gram",
"with",
"count",
"into",
"the",
"database",
"."
] | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L225-L239 |
cidles/pressagio | src/pressagio/dbconnector.py | DatabaseConnector.update_ngram | def update_ngram(self, ngram, count):
"""
Updates a given ngram in the database. The ngram has to be in the
database, otherwise this method will stop with an error.
Parameters
----------
ngram : iterable of str
A list, set or tuple of strings.
count : int
The count for the given n-gram.
"""
query = "UPDATE _{0}_gram SET count = {1}".format(len(ngram), count)
query += self._build_where_clause(ngram)
query += ";"
self.execute_sql(query) | python | def update_ngram(self, ngram, count):
"""
Updates a given ngram in the database. The ngram has to be in the
database, otherwise this method will stop with an error.
Parameters
----------
ngram : iterable of str
A list, set or tuple of strings.
count : int
The count for the given n-gram.
"""
query = "UPDATE _{0}_gram SET count = {1}".format(len(ngram), count)
query += self._build_where_clause(ngram)
query += ";"
self.execute_sql(query) | [
"def",
"update_ngram",
"(",
"self",
",",
"ngram",
",",
"count",
")",
":",
"query",
"=",
"\"UPDATE _{0}_gram SET count = {1}\"",
".",
"format",
"(",
"len",
"(",
"ngram",
")",
",",
"count",
")",
"query",
"+=",
"self",
".",
"_build_where_clause",
"(",
"ngram",
... | Updates a given ngram in the database. The ngram has to be in the
database, otherwise this method will stop with an error.
Parameters
----------
ngram : iterable of str
A list, set or tuple of strings.
count : int
The count for the given n-gram. | [
"Updates",
"a",
"given",
"ngram",
"in",
"the",
"database",
".",
"The",
"ngram",
"has",
"to",
"be",
"in",
"the",
"database",
"otherwise",
"this",
"method",
"will",
"stop",
"with",
"an",
"error",
"."
] | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L241-L257 |
cidles/pressagio | src/pressagio/dbconnector.py | DatabaseConnector.remove_ngram | def remove_ngram(self, ngram):
"""
Removes a given ngram from the databae. The ngram has to be in the
database, otherwise this method will stop with an error.
Parameters
----------
ngram : iterable of str
A list, set or tuple of strings.
"""
query = "DELETE FROM _{0}_gram".format(len(ngram))
query += self._build_where_clause(ngram)
query += ";"
self.execute_sql(query) | python | def remove_ngram(self, ngram):
"""
Removes a given ngram from the databae. The ngram has to be in the
database, otherwise this method will stop with an error.
Parameters
----------
ngram : iterable of str
A list, set or tuple of strings.
"""
query = "DELETE FROM _{0}_gram".format(len(ngram))
query += self._build_where_clause(ngram)
query += ";"
self.execute_sql(query) | [
"def",
"remove_ngram",
"(",
"self",
",",
"ngram",
")",
":",
"query",
"=",
"\"DELETE FROM _{0}_gram\"",
".",
"format",
"(",
"len",
"(",
"ngram",
")",
")",
"query",
"+=",
"self",
".",
"_build_where_clause",
"(",
"ngram",
")",
"query",
"+=",
"\";\"",
"self",
... | Removes a given ngram from the databae. The ngram has to be in the
database, otherwise this method will stop with an error.
Parameters
----------
ngram : iterable of str
A list, set or tuple of strings. | [
"Removes",
"a",
"given",
"ngram",
"from",
"the",
"databae",
".",
"The",
"ngram",
"has",
"to",
"be",
"in",
"the",
"database",
"otherwise",
"this",
"method",
"will",
"stop",
"with",
"an",
"error",
"."
] | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L259-L273 |
cidles/pressagio | src/pressagio/dbconnector.py | SqliteDatabaseConnector.execute_sql | def execute_sql(self, query):
"""
Executes a given query string on an open sqlite database.
"""
c = self.con.cursor()
c.execute(query)
result = c.fetchall()
return result | python | def execute_sql(self, query):
"""
Executes a given query string on an open sqlite database.
"""
c = self.con.cursor()
c.execute(query)
result = c.fetchall()
return result | [
"def",
"execute_sql",
"(",
"self",
",",
"query",
")",
":",
"c",
"=",
"self",
".",
"con",
".",
"cursor",
"(",
")",
"c",
".",
"execute",
"(",
"query",
")",
"result",
"=",
"c",
".",
"fetchall",
"(",
")",
"return",
"result"
] | Executes a given query string on an open sqlite database. | [
"Executes",
"a",
"given",
"query",
"string",
"on",
"an",
"open",
"sqlite",
"database",
"."
] | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L381-L389 |
cidles/pressagio | src/pressagio/dbconnector.py | PostgresDatabaseConnector.create_database | def create_database(self):
"""
Creates an empty database if not exists.
"""
if not self._database_exists():
con = psycopg2.connect(host=self.host, database="postgres",
user=self.user, password=self.password, port=self.port)
con.set_isolation_level(
psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
query = "CREATE DATABASE {0};".format(self.dbname)
c = con.cursor()
c.execute(query)
con.close()
if self.normalize:
self.open_database()
query = "CREATE EXTENSION IF NOT EXISTS \"plperlu\";"
self.execute_sql(query)
# query = """CREATE OR REPLACE FUNCTION normalize(str text)
#RETURNS text
#AS $$
#import unicodedata
#return ''.join(c for c in unicodedata.normalize('NFKD', str)
#if unicodedata.category(c) != 'Mn')
#$$ LANGUAGE plpython3u IMMUTABLE;"""
# query = """CREATE OR REPLACE FUNCTION normalize(mystr text)
# RETURNS text
# AS $$
# from unidecode import unidecode
# return unidecode(mystr.decode("utf-8"))
# $$ LANGUAGE plpythonu IMMUTABLE;"""
query = """CREATE OR REPLACE FUNCTION normalize(text)
RETURNS text
AS $$
use Text::Unidecode;
return unidecode(shift);
$$ LANGUAGE plperlu IMMUTABLE;"""
self.execute_sql(query)
self.commit()
self.close_database() | python | def create_database(self):
"""
Creates an empty database if not exists.
"""
if not self._database_exists():
con = psycopg2.connect(host=self.host, database="postgres",
user=self.user, password=self.password, port=self.port)
con.set_isolation_level(
psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
query = "CREATE DATABASE {0};".format(self.dbname)
c = con.cursor()
c.execute(query)
con.close()
if self.normalize:
self.open_database()
query = "CREATE EXTENSION IF NOT EXISTS \"plperlu\";"
self.execute_sql(query)
# query = """CREATE OR REPLACE FUNCTION normalize(str text)
#RETURNS text
#AS $$
#import unicodedata
#return ''.join(c for c in unicodedata.normalize('NFKD', str)
#if unicodedata.category(c) != 'Mn')
#$$ LANGUAGE plpython3u IMMUTABLE;"""
# query = """CREATE OR REPLACE FUNCTION normalize(mystr text)
# RETURNS text
# AS $$
# from unidecode import unidecode
# return unidecode(mystr.decode("utf-8"))
# $$ LANGUAGE plpythonu IMMUTABLE;"""
query = """CREATE OR REPLACE FUNCTION normalize(text)
RETURNS text
AS $$
use Text::Unidecode;
return unidecode(shift);
$$ LANGUAGE plperlu IMMUTABLE;"""
self.execute_sql(query)
self.commit()
self.close_database() | [
"def",
"create_database",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_database_exists",
"(",
")",
":",
"con",
"=",
"psycopg2",
".",
"connect",
"(",
"host",
"=",
"self",
".",
"host",
",",
"database",
"=",
"\"postgres\"",
",",
"user",
"=",
"self",... | Creates an empty database if not exists. | [
"Creates",
"an",
"empty",
"database",
"if",
"not",
"exists",
"."
] | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L428-L469 |
cidles/pressagio | src/pressagio/dbconnector.py | PostgresDatabaseConnector.reset_database | def reset_database(self):
"""
Re-create an empty database.
"""
if self._database_exists():
con = psycopg2.connect(host=self.host, database="postgres",
user=self.user, password=self.password, port=self.port)
con.set_isolation_level(
psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
query = "DROP DATABASE {0};".format(self.dbname)
c = con.cursor()
c.execute(query)
con.close()
self.create_database() | python | def reset_database(self):
"""
Re-create an empty database.
"""
if self._database_exists():
con = psycopg2.connect(host=self.host, database="postgres",
user=self.user, password=self.password, port=self.port)
con.set_isolation_level(
psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
query = "DROP DATABASE {0};".format(self.dbname)
c = con.cursor()
c.execute(query)
con.close()
self.create_database() | [
"def",
"reset_database",
"(",
"self",
")",
":",
"if",
"self",
".",
"_database_exists",
"(",
")",
":",
"con",
"=",
"psycopg2",
".",
"connect",
"(",
"host",
"=",
"self",
".",
"host",
",",
"database",
"=",
"\"postgres\"",
",",
"user",
"=",
"self",
".",
... | Re-create an empty database. | [
"Re",
"-",
"create",
"an",
"empty",
"database",
"."
] | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L472-L486 |
cidles/pressagio | src/pressagio/dbconnector.py | PostgresDatabaseConnector.create_index | def create_index(self, cardinality):
"""
Create an index for the table with the given cardinality.
Parameters
----------
cardinality : int
The cardinality to create a index for.
"""
DatabaseConnector.create_index(self, cardinality)
query = "CREATE INDEX idx_{0}_gram_varchar ON _{0}_gram(word varchar_pattern_ops);".format(cardinality)
self.execute_sql(query)
if self.lowercase:
for i in reversed(range(cardinality)):
if i != 0:
query = "CREATE INDEX idx_{0}_gram_{1}_lower ON _{0}_gram(LOWER(word_{1}));".format(cardinality, i)
self.execute_sql(query)
if self.normalize:
query = "CREATE INDEX idx_{0}_gram_lower_normalized_varchar ON _{0}_gram(NORMALIZE(LOWER(word)) varchar_pattern_ops);".format(cardinality)
self.execute_sql(query)
else:
query = "CREATE INDEX idx_{0}_gram_lower_varchar ON _{0}_gram(LOWER(word) varchar_pattern_ops);".format(cardinality)
self.execute_sql(query)
elif self.normalize:
query = "CREATE INDEX idx_{0}_gram_normalized_varchar ON _{0}_gram(NORMALIZE(word) varchar_pattern_ops);".format(cardinality)
self.execute_sql(query) | python | def create_index(self, cardinality):
"""
Create an index for the table with the given cardinality.
Parameters
----------
cardinality : int
The cardinality to create a index for.
"""
DatabaseConnector.create_index(self, cardinality)
query = "CREATE INDEX idx_{0}_gram_varchar ON _{0}_gram(word varchar_pattern_ops);".format(cardinality)
self.execute_sql(query)
if self.lowercase:
for i in reversed(range(cardinality)):
if i != 0:
query = "CREATE INDEX idx_{0}_gram_{1}_lower ON _{0}_gram(LOWER(word_{1}));".format(cardinality, i)
self.execute_sql(query)
if self.normalize:
query = "CREATE INDEX idx_{0}_gram_lower_normalized_varchar ON _{0}_gram(NORMALIZE(LOWER(word)) varchar_pattern_ops);".format(cardinality)
self.execute_sql(query)
else:
query = "CREATE INDEX idx_{0}_gram_lower_varchar ON _{0}_gram(LOWER(word) varchar_pattern_ops);".format(cardinality)
self.execute_sql(query)
elif self.normalize:
query = "CREATE INDEX idx_{0}_gram_normalized_varchar ON _{0}_gram(NORMALIZE(word) varchar_pattern_ops);".format(cardinality)
self.execute_sql(query) | [
"def",
"create_index",
"(",
"self",
",",
"cardinality",
")",
":",
"DatabaseConnector",
".",
"create_index",
"(",
"self",
",",
"cardinality",
")",
"query",
"=",
"\"CREATE INDEX idx_{0}_gram_varchar ON _{0}_gram(word varchar_pattern_ops);\"",
".",
"format",
"(",
"cardinalit... | Create an index for the table with the given cardinality.
Parameters
----------
cardinality : int
The cardinality to create a index for. | [
"Create",
"an",
"index",
"for",
"the",
"table",
"with",
"the",
"given",
"cardinality",
"."
] | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L488-L522 |
cidles/pressagio | src/pressagio/dbconnector.py | PostgresDatabaseConnector.delete_index | def delete_index(self, cardinality):
"""
Delete index for the table with the given cardinality.
Parameters
----------
cardinality : int
The cardinality of the index to delete.
"""
DatabaseConnector.delete_index(self, cardinality)
query = "DROP INDEX IF EXISTS idx_{0}_gram_varchar;".format(cardinality)
self.execute_sql(query)
query = "DROP INDEX IF EXISTS idx_{0}_gram_normalized_varchar;".format(
cardinality)
self.execute_sql(query)
query = "DROP INDEX IF EXISTS idx_{0}_gram_lower_varchar;".format(
cardinality)
self.execute_sql(query)
query = "DROP INDEX IF EXISTS idx_{0}_gram_lower_normalized_varchar;".\
format(cardinality)
self.execute_sql(query)
for i in reversed(range(cardinality)):
if i != 0:
query = "DROP INDEX IF EXISTS idx_{0}_gram_{1}_lower;".format(
cardinality, i)
self.execute_sql(query) | python | def delete_index(self, cardinality):
"""
Delete index for the table with the given cardinality.
Parameters
----------
cardinality : int
The cardinality of the index to delete.
"""
DatabaseConnector.delete_index(self, cardinality)
query = "DROP INDEX IF EXISTS idx_{0}_gram_varchar;".format(cardinality)
self.execute_sql(query)
query = "DROP INDEX IF EXISTS idx_{0}_gram_normalized_varchar;".format(
cardinality)
self.execute_sql(query)
query = "DROP INDEX IF EXISTS idx_{0}_gram_lower_varchar;".format(
cardinality)
self.execute_sql(query)
query = "DROP INDEX IF EXISTS idx_{0}_gram_lower_normalized_varchar;".\
format(cardinality)
self.execute_sql(query)
for i in reversed(range(cardinality)):
if i != 0:
query = "DROP INDEX IF EXISTS idx_{0}_gram_{1}_lower;".format(
cardinality, i)
self.execute_sql(query) | [
"def",
"delete_index",
"(",
"self",
",",
"cardinality",
")",
":",
"DatabaseConnector",
".",
"delete_index",
"(",
"self",
",",
"cardinality",
")",
"query",
"=",
"\"DROP INDEX IF EXISTS idx_{0}_gram_varchar;\"",
".",
"format",
"(",
"cardinality",
")",
"self",
".",
"... | Delete index for the table with the given cardinality.
Parameters
----------
cardinality : int
The cardinality of the index to delete. | [
"Delete",
"index",
"for",
"the",
"table",
"with",
"the",
"given",
"cardinality",
"."
] | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L524-L551 |
cidles/pressagio | src/pressagio/dbconnector.py | PostgresDatabaseConnector.open_database | def open_database(self):
"""
Opens the sqlite database.
"""
if not self.con:
try:
self.con = psycopg2.connect(host=self.host,
database=self.dbname, user=self.user,
password=self.password, port=self.port)
except psycopg2.Error as e:
print("Error while opening database:")
print(e.pgerror) | python | def open_database(self):
"""
Opens the sqlite database.
"""
if not self.con:
try:
self.con = psycopg2.connect(host=self.host,
database=self.dbname, user=self.user,
password=self.password, port=self.port)
except psycopg2.Error as e:
print("Error while opening database:")
print(e.pgerror) | [
"def",
"open_database",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"con",
":",
"try",
":",
"self",
".",
"con",
"=",
"psycopg2",
".",
"connect",
"(",
"host",
"=",
"self",
".",
"host",
",",
"database",
"=",
"self",
".",
"dbname",
",",
"user",
... | Opens the sqlite database. | [
"Opens",
"the",
"sqlite",
"database",
"."
] | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L560-L572 |
cidles/pressagio | src/pressagio/dbconnector.py | PostgresDatabaseConnector.execute_sql | def execute_sql(self, query):
"""
Executes a given query string on an open postgres database.
"""
c = self.con.cursor()
c.execute(query)
result = []
if c.rowcount > 0:
try:
result = c.fetchall()
except psycopg2.ProgrammingError:
pass
return result | python | def execute_sql(self, query):
"""
Executes a given query string on an open postgres database.
"""
c = self.con.cursor()
c.execute(query)
result = []
if c.rowcount > 0:
try:
result = c.fetchall()
except psycopg2.ProgrammingError:
pass
return result | [
"def",
"execute_sql",
"(",
"self",
",",
"query",
")",
":",
"c",
"=",
"self",
".",
"con",
".",
"cursor",
"(",
")",
"c",
".",
"execute",
"(",
"query",
")",
"result",
"=",
"[",
"]",
"if",
"c",
".",
"rowcount",
">",
"0",
":",
"try",
":",
"result",
... | Executes a given query string on an open postgres database. | [
"Executes",
"a",
"given",
"query",
"string",
"on",
"an",
"open",
"postgres",
"database",
"."
] | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L583-L596 |
cidles/pressagio | src/pressagio/dbconnector.py | PostgresDatabaseConnector._database_exists | def _database_exists(self):
"""
Check if the database exists.
"""
con = psycopg2.connect(host=self.host, database="postgres",
user=self.user, password=self.password, port=self.port)
query_check = "select datname from pg_catalog.pg_database"
query_check += " where datname = '{0}';".format(self.dbname)
c = con.cursor()
c.execute(query_check)
result = c.fetchall()
if len(result) > 0:
return True
return False | python | def _database_exists(self):
"""
Check if the database exists.
"""
con = psycopg2.connect(host=self.host, database="postgres",
user=self.user, password=self.password, port=self.port)
query_check = "select datname from pg_catalog.pg_database"
query_check += " where datname = '{0}';".format(self.dbname)
c = con.cursor()
c.execute(query_check)
result = c.fetchall()
if len(result) > 0:
return True
return False | [
"def",
"_database_exists",
"(",
"self",
")",
":",
"con",
"=",
"psycopg2",
".",
"connect",
"(",
"host",
"=",
"self",
".",
"host",
",",
"database",
"=",
"\"postgres\"",
",",
"user",
"=",
"self",
".",
"user",
",",
"password",
"=",
"self",
".",
"password",... | Check if the database exists. | [
"Check",
"if",
"the",
"database",
"exists",
"."
] | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L601-L615 |
ubccr/pinky | pinky/mol/chirality.py | T.getChirality | def getChirality(self, order):
"""(order)->what is the chirality of a given order of
atoms?"""
indices = tuple([self._initialOrder.index(atom.handle)
for atom in order])
same = chiral_table[indices]
if same:
return self.chirality
else:
if self.chirality == "@": return "@@"
else: return "@" | python | def getChirality(self, order):
"""(order)->what is the chirality of a given order of
atoms?"""
indices = tuple([self._initialOrder.index(atom.handle)
for atom in order])
same = chiral_table[indices]
if same:
return self.chirality
else:
if self.chirality == "@": return "@@"
else: return "@" | [
"def",
"getChirality",
"(",
"self",
",",
"order",
")",
":",
"indices",
"=",
"tuple",
"(",
"[",
"self",
".",
"_initialOrder",
".",
"index",
"(",
"atom",
".",
"handle",
")",
"for",
"atom",
"in",
"order",
"]",
")",
"same",
"=",
"chiral_table",
"[",
"ind... | (order)->what is the chirality of a given order of
atoms? | [
"(",
"order",
")",
"-",
">",
"what",
"is",
"the",
"chirality",
"of",
"a",
"given",
"order",
"of",
"atoms?"
] | train | https://github.com/ubccr/pinky/blob/e9d6e8ff72aa7f670b591e3bd3629cb879db1a93/pinky/mol/chirality.py#L105-L115 |
mozilla/funfactory | funfactory/log.py | log_cef | def log_cef(name, severity=logging.INFO, env=None, username='none',
signature=None, **kwargs):
"""
Wraps cef logging function so we don't need to pass in the config
dictionary every time. See bug 707060. ``env`` can be either a request
object or just the request.META dictionary.
"""
cef_logger = commonware.log.getLogger('cef')
c = {'product': settings.CEF_PRODUCT,
'vendor': settings.CEF_VENDOR,
'version': settings.CEF_VERSION,
'device_version': settings.CEF_DEVICE_VERSION}
# The CEF library looks for some things in the env object like
# REQUEST_METHOD and any REMOTE_ADDR stuff. Django not only doesn't send
# half the stuff you'd expect, but it specifically doesn't implement
# readline on its FakePayload object so these things fail. I have no idea
# if that's outdated code in Django or not, but andym made this
# <strike>awesome</strike> less crappy so the tests will actually pass.
# In theory, the last part of this if() will never be hit except in the
# test runner. Good luck with that.
if isinstance(env, HttpRequest):
r = env.META.copy()
elif isinstance(env, dict):
r = env
else:
r = {}
# Drop kwargs into CEF config array, then log.
c['environ'] = r
c.update({
'username': username,
'signature': signature,
'data': kwargs,
})
cef_logger.log(severity, name, c) | python | def log_cef(name, severity=logging.INFO, env=None, username='none',
signature=None, **kwargs):
"""
Wraps cef logging function so we don't need to pass in the config
dictionary every time. See bug 707060. ``env`` can be either a request
object or just the request.META dictionary.
"""
cef_logger = commonware.log.getLogger('cef')
c = {'product': settings.CEF_PRODUCT,
'vendor': settings.CEF_VENDOR,
'version': settings.CEF_VERSION,
'device_version': settings.CEF_DEVICE_VERSION}
# The CEF library looks for some things in the env object like
# REQUEST_METHOD and any REMOTE_ADDR stuff. Django not only doesn't send
# half the stuff you'd expect, but it specifically doesn't implement
# readline on its FakePayload object so these things fail. I have no idea
# if that's outdated code in Django or not, but andym made this
# <strike>awesome</strike> less crappy so the tests will actually pass.
# In theory, the last part of this if() will never be hit except in the
# test runner. Good luck with that.
if isinstance(env, HttpRequest):
r = env.META.copy()
elif isinstance(env, dict):
r = env
else:
r = {}
# Drop kwargs into CEF config array, then log.
c['environ'] = r
c.update({
'username': username,
'signature': signature,
'data': kwargs,
})
cef_logger.log(severity, name, c) | [
"def",
"log_cef",
"(",
"name",
",",
"severity",
"=",
"logging",
".",
"INFO",
",",
"env",
"=",
"None",
",",
"username",
"=",
"'none'",
",",
"signature",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cef_logger",
"=",
"commonware",
".",
"log",
".",
... | Wraps cef logging function so we don't need to pass in the config
dictionary every time. See bug 707060. ``env`` can be either a request
object or just the request.META dictionary. | [
"Wraps",
"cef",
"logging",
"function",
"so",
"we",
"don",
"t",
"need",
"to",
"pass",
"in",
"the",
"config",
"dictionary",
"every",
"time",
".",
"See",
"bug",
"707060",
".",
"env",
"can",
"be",
"either",
"a",
"request",
"object",
"or",
"just",
"the",
"r... | train | https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/log.py#L22-L60 |
hayd/ctox | ctox/config.py | get_changedir | def get_changedir(env):
"changedir = {envdir}"
from ctox.subst import replace_braces
changedir = _get_env_maybe(env, 'testenv', 'changedir')
if changedir:
return replace_braces(changedir, env)
else:
return env.toxinidir | python | def get_changedir(env):
"changedir = {envdir}"
from ctox.subst import replace_braces
changedir = _get_env_maybe(env, 'testenv', 'changedir')
if changedir:
return replace_braces(changedir, env)
else:
return env.toxinidir | [
"def",
"get_changedir",
"(",
"env",
")",
":",
"from",
"ctox",
".",
"subst",
"import",
"replace_braces",
"changedir",
"=",
"_get_env_maybe",
"(",
"env",
",",
"'testenv'",
",",
"'changedir'",
")",
"if",
"changedir",
":",
"return",
"replace_braces",
"(",
"changed... | changedir = {envdir} | [
"changedir",
"=",
"{",
"envdir",
"}"
] | train | https://github.com/hayd/ctox/blob/6f032488ad67170d57d025a830d7b967075b0d7f/ctox/config.py#L41-L48 |
zyga/morris | morris/__init__.py | remove_signals_listeners | def remove_signals_listeners(instance):
"""
utility function that disconnects all listeners from all signals on an
object
"""
if hasattr(instance, "__listeners__"):
for listener in list(instance.__listeners__):
for signal in instance.__listeners__[listener]:
signal.disconnect(listener) | python | def remove_signals_listeners(instance):
"""
utility function that disconnects all listeners from all signals on an
object
"""
if hasattr(instance, "__listeners__"):
for listener in list(instance.__listeners__):
for signal in instance.__listeners__[listener]:
signal.disconnect(listener) | [
"def",
"remove_signals_listeners",
"(",
"instance",
")",
":",
"if",
"hasattr",
"(",
"instance",
",",
"\"__listeners__\"",
")",
":",
"for",
"listener",
"in",
"list",
"(",
"instance",
".",
"__listeners__",
")",
":",
"for",
"signal",
"in",
"instance",
".",
"__l... | utility function that disconnects all listeners from all signals on an
object | [
"utility",
"function",
"that",
"disconnects",
"all",
"listeners",
"from",
"all",
"signals",
"on",
"an",
"object"
] | train | https://github.com/zyga/morris/blob/7cd6da662c8c95b93b5fb8bb25eae8686becf31a/morris/__init__.py#L865-L873 |
zyga/morris | morris/__init__.py | signal.connect | def connect(self, listener, pass_signal=False):
"""
Connect a new listener to this signal
:param listener:
The listener (callable) to add
:param pass_signal:
An optional argument that controls if the signal object is
explicitly passed to this listener when it is being fired.
If enabled, a ``signal=`` keyword argument is passed to the
listener function.
:returns:
None
The listener will be called whenever :meth:`fire()` or
:meth:`__call__()` are called. The listener is appended to the list of
listeners. Duplicates are not checked and if a listener is added twice
it gets called twice.
"""
info = listenerinfo(listener, pass_signal)
self._listeners.append(info)
_logger.debug("connect %r to %r", str(listener), self._name)
# Track listeners in the instances only
if inspect.ismethod(listener):
listener_object = listener.__self__
# Ensure that the instance has __listeners__ property
if not hasattr(listener_object, "__listeners__"):
listener_object.__listeners__ = collections.defaultdict(list)
# Append the signals a listener is connected to
listener_object.__listeners__[listener].append(self) | python | def connect(self, listener, pass_signal=False):
"""
Connect a new listener to this signal
:param listener:
The listener (callable) to add
:param pass_signal:
An optional argument that controls if the signal object is
explicitly passed to this listener when it is being fired.
If enabled, a ``signal=`` keyword argument is passed to the
listener function.
:returns:
None
The listener will be called whenever :meth:`fire()` or
:meth:`__call__()` are called. The listener is appended to the list of
listeners. Duplicates are not checked and if a listener is added twice
it gets called twice.
"""
info = listenerinfo(listener, pass_signal)
self._listeners.append(info)
_logger.debug("connect %r to %r", str(listener), self._name)
# Track listeners in the instances only
if inspect.ismethod(listener):
listener_object = listener.__self__
# Ensure that the instance has __listeners__ property
if not hasattr(listener_object, "__listeners__"):
listener_object.__listeners__ = collections.defaultdict(list)
# Append the signals a listener is connected to
listener_object.__listeners__[listener].append(self) | [
"def",
"connect",
"(",
"self",
",",
"listener",
",",
"pass_signal",
"=",
"False",
")",
":",
"info",
"=",
"listenerinfo",
"(",
"listener",
",",
"pass_signal",
")",
"self",
".",
"_listeners",
".",
"append",
"(",
"info",
")",
"_logger",
".",
"debug",
"(",
... | Connect a new listener to this signal
:param listener:
The listener (callable) to add
:param pass_signal:
An optional argument that controls if the signal object is
explicitly passed to this listener when it is being fired.
If enabled, a ``signal=`` keyword argument is passed to the
listener function.
:returns:
None
The listener will be called whenever :meth:`fire()` or
:meth:`__call__()` are called. The listener is appended to the list of
listeners. Duplicates are not checked and if a listener is added twice
it gets called twice. | [
"Connect",
"a",
"new",
"listener",
"to",
"this",
"signal"
] | train | https://github.com/zyga/morris/blob/7cd6da662c8c95b93b5fb8bb25eae8686becf31a/morris/__init__.py#L631-L660 |
zyga/morris | morris/__init__.py | signal.disconnect | def disconnect(self, listener, pass_signal=False):
"""
Disconnect an existing listener from this signal
:param listener:
The listener (callable) to remove
:param pass_signal:
An optional argument that controls if the signal object is
explicitly passed to this listener when it is being fired.
If enabled, a ``signal=`` keyword argument is passed to the
listener function.
Here, this argument simply aids in disconnecting the right
listener. Make sure to pass the same value as was passed to
:meth:`connect()`
:raises ValueError:
If the listener (with the same value of pass_signal) is not present
:returns:
None
"""
info = listenerinfo(listener, pass_signal)
self._listeners.remove(info)
_logger.debug(
"disconnect %r from %r", str(listener), self._name)
if inspect.ismethod(listener):
listener_object = listener.__self__
if hasattr(listener_object, "__listeners__"):
listener_object.__listeners__[listener].remove(self)
# Remove the listener from the list if any signals connected
if (len(listener_object.__listeners__[listener])) == 0:
del listener_object.__listeners__[listener] | python | def disconnect(self, listener, pass_signal=False):
"""
Disconnect an existing listener from this signal
:param listener:
The listener (callable) to remove
:param pass_signal:
An optional argument that controls if the signal object is
explicitly passed to this listener when it is being fired.
If enabled, a ``signal=`` keyword argument is passed to the
listener function.
Here, this argument simply aids in disconnecting the right
listener. Make sure to pass the same value as was passed to
:meth:`connect()`
:raises ValueError:
If the listener (with the same value of pass_signal) is not present
:returns:
None
"""
info = listenerinfo(listener, pass_signal)
self._listeners.remove(info)
_logger.debug(
"disconnect %r from %r", str(listener), self._name)
if inspect.ismethod(listener):
listener_object = listener.__self__
if hasattr(listener_object, "__listeners__"):
listener_object.__listeners__[listener].remove(self)
# Remove the listener from the list if any signals connected
if (len(listener_object.__listeners__[listener])) == 0:
del listener_object.__listeners__[listener] | [
"def",
"disconnect",
"(",
"self",
",",
"listener",
",",
"pass_signal",
"=",
"False",
")",
":",
"info",
"=",
"listenerinfo",
"(",
"listener",
",",
"pass_signal",
")",
"self",
".",
"_listeners",
".",
"remove",
"(",
"info",
")",
"_logger",
".",
"debug",
"("... | Disconnect an existing listener from this signal
:param listener:
The listener (callable) to remove
:param pass_signal:
An optional argument that controls if the signal object is
explicitly passed to this listener when it is being fired.
If enabled, a ``signal=`` keyword argument is passed to the
listener function.
Here, this argument simply aids in disconnecting the right
listener. Make sure to pass the same value as was passed to
:meth:`connect()`
:raises ValueError:
If the listener (with the same value of pass_signal) is not present
:returns:
None | [
"Disconnect",
"an",
"existing",
"listener",
"from",
"this",
"signal"
] | train | https://github.com/zyga/morris/blob/7cd6da662c8c95b93b5fb8bb25eae8686becf31a/morris/__init__.py#L662-L692 |
zyga/morris | morris/__init__.py | signal.fire | def fire(self, args, kwargs):
"""
Fire this signal with the specified arguments and keyword arguments.
Typically this is used by using :meth:`__call__()` on this object which
is more natural as it does all the argument packing/unpacking
transparently.
"""
for info in self._listeners[:]:
if info.pass_signal:
info.listener(*args, signal=self, **kwargs)
else:
info.listener(*args, **kwargs) | python | def fire(self, args, kwargs):
"""
Fire this signal with the specified arguments and keyword arguments.
Typically this is used by using :meth:`__call__()` on this object which
is more natural as it does all the argument packing/unpacking
transparently.
"""
for info in self._listeners[:]:
if info.pass_signal:
info.listener(*args, signal=self, **kwargs)
else:
info.listener(*args, **kwargs) | [
"def",
"fire",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"for",
"info",
"in",
"self",
".",
"_listeners",
"[",
":",
"]",
":",
"if",
"info",
".",
"pass_signal",
":",
"info",
".",
"listener",
"(",
"*",
"args",
",",
"signal",
"=",
"self",
",... | Fire this signal with the specified arguments and keyword arguments.
Typically this is used by using :meth:`__call__()` on this object which
is more natural as it does all the argument packing/unpacking
transparently. | [
"Fire",
"this",
"signal",
"with",
"the",
"specified",
"arguments",
"and",
"keyword",
"arguments",
"."
] | train | https://github.com/zyga/morris/blob/7cd6da662c8c95b93b5fb8bb25eae8686becf31a/morris/__init__.py#L694-L706 |
zyga/morris | morris/__init__.py | SignalInterceptorMixIn.watchSignal | def watchSignal(self, signal):
"""
Setup provisions to watch a specified signal
:param signal:
The :class:`Signal` to watch for.
After calling this method you can use :meth:`assertSignalFired()`
and :meth:`assertSignalNotFired()` with the same signal.
"""
self._extend_state()
def signal_handler(*args, **kwargs):
self._events_seen.append((signal, args, kwargs))
signal.connect(signal_handler)
if hasattr(self, 'addCleanup'):
self.addCleanup(signal.disconnect, signal_handler) | python | def watchSignal(self, signal):
"""
Setup provisions to watch a specified signal
:param signal:
The :class:`Signal` to watch for.
After calling this method you can use :meth:`assertSignalFired()`
and :meth:`assertSignalNotFired()` with the same signal.
"""
self._extend_state()
def signal_handler(*args, **kwargs):
self._events_seen.append((signal, args, kwargs))
signal.connect(signal_handler)
if hasattr(self, 'addCleanup'):
self.addCleanup(signal.disconnect, signal_handler) | [
"def",
"watchSignal",
"(",
"self",
",",
"signal",
")",
":",
"self",
".",
"_extend_state",
"(",
")",
"def",
"signal_handler",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_events_seen",
".",
"append",
"(",
"(",
"signal",
",",
"ar... | Setup provisions to watch a specified signal
:param signal:
The :class:`Signal` to watch for.
After calling this method you can use :meth:`assertSignalFired()`
and :meth:`assertSignalNotFired()` with the same signal. | [
"Setup",
"provisions",
"to",
"watch",
"a",
"specified",
"signal"
] | train | https://github.com/zyga/morris/blob/7cd6da662c8c95b93b5fb8bb25eae8686becf31a/morris/__init__.py#L773-L789 |
zyga/morris | morris/__init__.py | SignalInterceptorMixIn.assertSignalFired | def assertSignalFired(self, signal, *args, **kwargs):
"""
Assert that a signal was fired with appropriate arguments.
:param signal:
The :class:`Signal` that should have been fired.
Typically this is ``SomeClass.on_some_signal`` reference
:param args:
List of positional arguments passed to the signal handler
:param kwargs:
List of keyword arguments passed to the signal handler
:returns:
A 3-tuple (signal, args, kwargs) that describes that event
"""
event = (signal, args, kwargs)
self.assertIn(
event, self._events_seen,
"\nSignal unexpectedly not fired: {}\n".format(event))
return event | python | def assertSignalFired(self, signal, *args, **kwargs):
"""
Assert that a signal was fired with appropriate arguments.
:param signal:
The :class:`Signal` that should have been fired.
Typically this is ``SomeClass.on_some_signal`` reference
:param args:
List of positional arguments passed to the signal handler
:param kwargs:
List of keyword arguments passed to the signal handler
:returns:
A 3-tuple (signal, args, kwargs) that describes that event
"""
event = (signal, args, kwargs)
self.assertIn(
event, self._events_seen,
"\nSignal unexpectedly not fired: {}\n".format(event))
return event | [
"def",
"assertSignalFired",
"(",
"self",
",",
"signal",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"event",
"=",
"(",
"signal",
",",
"args",
",",
"kwargs",
")",
"self",
".",
"assertIn",
"(",
"event",
",",
"self",
".",
"_events_seen",
",",
... | Assert that a signal was fired with appropriate arguments.
:param signal:
The :class:`Signal` that should have been fired.
Typically this is ``SomeClass.on_some_signal`` reference
:param args:
List of positional arguments passed to the signal handler
:param kwargs:
List of keyword arguments passed to the signal handler
:returns:
A 3-tuple (signal, args, kwargs) that describes that event | [
"Assert",
"that",
"a",
"signal",
"was",
"fired",
"with",
"appropriate",
"arguments",
"."
] | train | https://github.com/zyga/morris/blob/7cd6da662c8c95b93b5fb8bb25eae8686becf31a/morris/__init__.py#L791-L809 |
zyga/morris | morris/__init__.py | SignalInterceptorMixIn.assertSignalNotFired | def assertSignalNotFired(self, signal, *args, **kwargs):
"""
Assert that a signal was fired with appropriate arguments.
:param signal:
The :class:`Signal` that should not have been fired.
Typically this is ``SomeClass.on_some_signal`` reference
:param args:
List of positional arguments passed to the signal handler
:param kwargs:
List of keyword arguments passed to the signal handler
"""
event = (signal, args, kwargs)
self.assertNotIn(
event, self._events_seen,
"\nSignal unexpectedly fired: {}\n".format(event)) | python | def assertSignalNotFired(self, signal, *args, **kwargs):
"""
Assert that a signal was fired with appropriate arguments.
:param signal:
The :class:`Signal` that should not have been fired.
Typically this is ``SomeClass.on_some_signal`` reference
:param args:
List of positional arguments passed to the signal handler
:param kwargs:
List of keyword arguments passed to the signal handler
"""
event = (signal, args, kwargs)
self.assertNotIn(
event, self._events_seen,
"\nSignal unexpectedly fired: {}\n".format(event)) | [
"def",
"assertSignalNotFired",
"(",
"self",
",",
"signal",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"event",
"=",
"(",
"signal",
",",
"args",
",",
"kwargs",
")",
"self",
".",
"assertNotIn",
"(",
"event",
",",
"self",
".",
"_events_seen",
... | Assert that a signal was fired with appropriate arguments.
:param signal:
The :class:`Signal` that should not have been fired.
Typically this is ``SomeClass.on_some_signal`` reference
:param args:
List of positional arguments passed to the signal handler
:param kwargs:
List of keyword arguments passed to the signal handler | [
"Assert",
"that",
"a",
"signal",
"was",
"fired",
"with",
"appropriate",
"arguments",
"."
] | train | https://github.com/zyga/morris/blob/7cd6da662c8c95b93b5fb8bb25eae8686becf31a/morris/__init__.py#L811-L826 |
zyga/morris | morris/__init__.py | SignalInterceptorMixIn.assertSignalOrdering | def assertSignalOrdering(self, *expected_events):
"""
Assert that a signals were fired in a specific sequence.
:param expected_events:
A (varadic) list of events describing the signals that were fired
Each element is a 3-tuple (signal, args, kwargs) that describes
the event.
.. note::
If you are using :meth:`assertSignalFired()` then the return value
of that method is a single event that can be passed to this method
"""
expected_order = [self._events_seen.index(event)
for event in expected_events]
actual_order = sorted(expected_order)
self.assertEqual(
expected_order, actual_order,
"\nExpected order of fired signals:\n{}\n"
"Actual order observed:\n{}".format(
"\n".join(
"\t{}: {}".format(i, event)
for i, event in enumerate(expected_events, 1)),
"\n".join(
"\t{}: {}".format(i, event)
for i, event in enumerate(
(self._events_seen[idx] for idx in actual_order), 1)))) | python | def assertSignalOrdering(self, *expected_events):
"""
Assert that a signals were fired in a specific sequence.
:param expected_events:
A (varadic) list of events describing the signals that were fired
Each element is a 3-tuple (signal, args, kwargs) that describes
the event.
.. note::
If you are using :meth:`assertSignalFired()` then the return value
of that method is a single event that can be passed to this method
"""
expected_order = [self._events_seen.index(event)
for event in expected_events]
actual_order = sorted(expected_order)
self.assertEqual(
expected_order, actual_order,
"\nExpected order of fired signals:\n{}\n"
"Actual order observed:\n{}".format(
"\n".join(
"\t{}: {}".format(i, event)
for i, event in enumerate(expected_events, 1)),
"\n".join(
"\t{}: {}".format(i, event)
for i, event in enumerate(
(self._events_seen[idx] for idx in actual_order), 1)))) | [
"def",
"assertSignalOrdering",
"(",
"self",
",",
"*",
"expected_events",
")",
":",
"expected_order",
"=",
"[",
"self",
".",
"_events_seen",
".",
"index",
"(",
"event",
")",
"for",
"event",
"in",
"expected_events",
"]",
"actual_order",
"=",
"sorted",
"(",
"ex... | Assert that a signals were fired in a specific sequence.
:param expected_events:
A (varadic) list of events describing the signals that were fired
Each element is a 3-tuple (signal, args, kwargs) that describes
the event.
.. note::
If you are using :meth:`assertSignalFired()` then the return value
of that method is a single event that can be passed to this method | [
"Assert",
"that",
"a",
"signals",
"were",
"fired",
"in",
"a",
"specific",
"sequence",
"."
] | train | https://github.com/zyga/morris/blob/7cd6da662c8c95b93b5fb8bb25eae8686becf31a/morris/__init__.py#L828-L854 |
mozilla/funfactory | funfactory/helpers.py | url | def url(viewname, *args, **kwargs):
"""Helper for Django's ``reverse`` in templates."""
return reverse(viewname, args=args, kwargs=kwargs) | python | def url(viewname, *args, **kwargs):
"""Helper for Django's ``reverse`` in templates."""
return reverse(viewname, args=args, kwargs=kwargs) | [
"def",
"url",
"(",
"viewname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"reverse",
"(",
"viewname",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
")"
] | Helper for Django's ``reverse`` in templates. | [
"Helper",
"for",
"Django",
"s",
"reverse",
"in",
"templates",
"."
] | train | https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/helpers.py#L28-L30 |
mozilla/funfactory | funfactory/helpers.py | urlparams | def urlparams(url_, hash=None, **query):
"""Add a fragment and/or query paramaters to a URL.
New query params will be appended to exising parameters, except duplicate
names, which will be replaced.
"""
url = urlparse.urlparse(url_)
fragment = hash if hash is not None else url.fragment
# Use dict(parse_qsl) so we don't get lists of values.
q = url.query
query_dict = dict(urlparse.parse_qsl(smart_str(q))) if q else {}
query_dict.update((k, v) for k, v in query.items())
query_string = _urlencode([(k, v) for k, v in query_dict.items()
if v is not None])
new = urlparse.ParseResult(url.scheme, url.netloc, url.path, url.params,
query_string, fragment)
return new.geturl() | python | def urlparams(url_, hash=None, **query):
"""Add a fragment and/or query paramaters to a URL.
New query params will be appended to exising parameters, except duplicate
names, which will be replaced.
"""
url = urlparse.urlparse(url_)
fragment = hash if hash is not None else url.fragment
# Use dict(parse_qsl) so we don't get lists of values.
q = url.query
query_dict = dict(urlparse.parse_qsl(smart_str(q))) if q else {}
query_dict.update((k, v) for k, v in query.items())
query_string = _urlencode([(k, v) for k, v in query_dict.items()
if v is not None])
new = urlparse.ParseResult(url.scheme, url.netloc, url.path, url.params,
query_string, fragment)
return new.geturl() | [
"def",
"urlparams",
"(",
"url_",
",",
"hash",
"=",
"None",
",",
"*",
"*",
"query",
")",
":",
"url",
"=",
"urlparse",
".",
"urlparse",
"(",
"url_",
")",
"fragment",
"=",
"hash",
"if",
"hash",
"is",
"not",
"None",
"else",
"url",
".",
"fragment",
"# U... | Add a fragment and/or query paramaters to a URL.
New query params will be appended to exising parameters, except duplicate
names, which will be replaced. | [
"Add",
"a",
"fragment",
"and",
"/",
"or",
"query",
"paramaters",
"to",
"a",
"URL",
"."
] | train | https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/helpers.py#L34-L52 |
mozilla/funfactory | funfactory/helpers.py | _urlencode | def _urlencode(items):
"""A Unicode-safe URLencoder."""
try:
return urllib.urlencode(items)
except UnicodeEncodeError:
return urllib.urlencode([(k, smart_str(v)) for k, v in items]) | python | def _urlencode(items):
"""A Unicode-safe URLencoder."""
try:
return urllib.urlencode(items)
except UnicodeEncodeError:
return urllib.urlencode([(k, smart_str(v)) for k, v in items]) | [
"def",
"_urlencode",
"(",
"items",
")",
":",
"try",
":",
"return",
"urllib",
".",
"urlencode",
"(",
"items",
")",
"except",
"UnicodeEncodeError",
":",
"return",
"urllib",
".",
"urlencode",
"(",
"[",
"(",
"k",
",",
"smart_str",
"(",
"v",
")",
")",
"for"... | A Unicode-safe URLencoder. | [
"A",
"Unicode",
"-",
"safe",
"URLencoder",
"."
] | train | https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/helpers.py#L55-L60 |
mozilla/funfactory | funfactory/helpers.py | urlencode | def urlencode(txt):
"""Url encode a path."""
if isinstance(txt, unicode):
txt = txt.encode('utf-8')
return urllib.quote_plus(txt) | python | def urlencode(txt):
"""Url encode a path."""
if isinstance(txt, unicode):
txt = txt.encode('utf-8')
return urllib.quote_plus(txt) | [
"def",
"urlencode",
"(",
"txt",
")",
":",
"if",
"isinstance",
"(",
"txt",
",",
"unicode",
")",
":",
"txt",
"=",
"txt",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"urllib",
".",
"quote_plus",
"(",
"txt",
")"
] | Url encode a path. | [
"Url",
"encode",
"a",
"path",
"."
] | train | https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/helpers.py#L64-L68 |
calmjs/calmjs.parse | src/calmjs/parse/handlers/core.py | token_handler_str_default | def token_handler_str_default(
token, dispatcher, node, subnode, sourcepath_stack=(None,)):
"""
Standard token handler that will return the value, ignoring any
tokens or strings that have been remapped.
"""
if isinstance(token.pos, int):
_, lineno, colno = node.getpos(subnode, token.pos)
else:
lineno, colno = None, None
yield StreamFragment(subnode, lineno, colno, None, sourcepath_stack[-1]) | python | def token_handler_str_default(
token, dispatcher, node, subnode, sourcepath_stack=(None,)):
"""
Standard token handler that will return the value, ignoring any
tokens or strings that have been remapped.
"""
if isinstance(token.pos, int):
_, lineno, colno = node.getpos(subnode, token.pos)
else:
lineno, colno = None, None
yield StreamFragment(subnode, lineno, colno, None, sourcepath_stack[-1]) | [
"def",
"token_handler_str_default",
"(",
"token",
",",
"dispatcher",
",",
"node",
",",
"subnode",
",",
"sourcepath_stack",
"=",
"(",
"None",
",",
")",
")",
":",
"if",
"isinstance",
"(",
"token",
".",
"pos",
",",
"int",
")",
":",
"_",
",",
"lineno",
","... | Standard token handler that will return the value, ignoring any
tokens or strings that have been remapped. | [
"Standard",
"token",
"handler",
"that",
"will",
"return",
"the",
"value",
"ignoring",
"any",
"tokens",
"or",
"strings",
"that",
"have",
"been",
"remapped",
"."
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/core.py#L55-L66 |
calmjs/calmjs.parse | src/calmjs/parse/handlers/core.py | token_handler_unobfuscate | def token_handler_unobfuscate(
token, dispatcher, node, subnode, sourcepath_stack=(None,)):
"""
A token handler that will resolve and return the original identifier
value.
"""
original = (
node.value
if isinstance(node, Identifier) and node.value != subnode else
None
)
if isinstance(token.pos, int):
_, lineno, colno = node.getpos(original or subnode, token.pos)
else:
lineno, colno = None, None
yield StreamFragment(
subnode, lineno, colno, original, sourcepath_stack[-1]) | python | def token_handler_unobfuscate(
token, dispatcher, node, subnode, sourcepath_stack=(None,)):
"""
A token handler that will resolve and return the original identifier
value.
"""
original = (
node.value
if isinstance(node, Identifier) and node.value != subnode else
None
)
if isinstance(token.pos, int):
_, lineno, colno = node.getpos(original or subnode, token.pos)
else:
lineno, colno = None, None
yield StreamFragment(
subnode, lineno, colno, original, sourcepath_stack[-1]) | [
"def",
"token_handler_unobfuscate",
"(",
"token",
",",
"dispatcher",
",",
"node",
",",
"subnode",
",",
"sourcepath_stack",
"=",
"(",
"None",
",",
")",
")",
":",
"original",
"=",
"(",
"node",
".",
"value",
"if",
"isinstance",
"(",
"node",
",",
"Identifier",... | A token handler that will resolve and return the original identifier
value. | [
"A",
"token",
"handler",
"that",
"will",
"resolve",
"and",
"return",
"the",
"original",
"identifier",
"value",
"."
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/core.py#L69-L88 |
calmjs/calmjs.parse | src/calmjs/parse/io.py | read | def read(parser, stream):
"""
Return an AST from the input ES5 stream.
Arguments
parser
A parser instance.
stream
Either a stream object or a callable that produces one. The
stream object to read from; its 'read' method will be invoked.
If a callable was provided, the 'close' method on its return
value will be called to close the stream.
"""
source = stream() if callable(stream) else stream
try:
text = source.read()
stream_name = getattr(source, 'name', None)
try:
result = parser(text)
except ECMASyntaxError as e:
error_name = repr_compat(stream_name or source)
raise type(e)('%s in %s' % (str(e), error_name))
finally:
if callable(stream):
source.close()
result.sourcepath = stream_name
return result | python | def read(parser, stream):
"""
Return an AST from the input ES5 stream.
Arguments
parser
A parser instance.
stream
Either a stream object or a callable that produces one. The
stream object to read from; its 'read' method will be invoked.
If a callable was provided, the 'close' method on its return
value will be called to close the stream.
"""
source = stream() if callable(stream) else stream
try:
text = source.read()
stream_name = getattr(source, 'name', None)
try:
result = parser(text)
except ECMASyntaxError as e:
error_name = repr_compat(stream_name or source)
raise type(e)('%s in %s' % (str(e), error_name))
finally:
if callable(stream):
source.close()
result.sourcepath = stream_name
return result | [
"def",
"read",
"(",
"parser",
",",
"stream",
")",
":",
"source",
"=",
"stream",
"(",
")",
"if",
"callable",
"(",
"stream",
")",
"else",
"stream",
"try",
":",
"text",
"=",
"source",
".",
"read",
"(",
")",
"stream_name",
"=",
"getattr",
"(",
"source",
... | Return an AST from the input ES5 stream.
Arguments
parser
A parser instance.
stream
Either a stream object or a callable that produces one. The
stream object to read from; its 'read' method will be invoked.
If a callable was provided, the 'close' method on its return
value will be called to close the stream. | [
"Return",
"an",
"AST",
"from",
"the",
"input",
"ES5",
"stream",
"."
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/io.py#L14-L44 |
calmjs/calmjs.parse | src/calmjs/parse/io.py | write | def write(
unparser, nodes, output_stream, sourcemap_stream=None,
sourcemap_normalize_mappings=True,
sourcemap_normalize_paths=True,
source_mapping_url=NotImplemented):
"""
Write out the node using the unparser into an output stream, and
optionally the sourcemap using the sourcemap stream.
Ideally, file objects should be passed to the *_stream arguments, so
that the name resolution built into the sourcemap builder function
will be used. Also, if these file objects are opened using absolute
path arguments, enabling the sourcemap_normalize_paths flag will
have all paths normalized to their relative form.
If the provided streams are not anchored on the filesystem, or that
the provide node was generated from a string or in-memory stream,
the generation of the sourcemap should be done using the lower level
`write` function provided by the sourcemap module, which this method
wraps. Alternatively, the top level node should have its sourcepath
set to path that this node originated from.
Arguments
unparser
An unparser instance.
nodes
The Node or list of Nodes to stream to the output stream with
the unparser.
output_stream
Either a stream object or a callable that produces one. The
stream object to write to; its 'write' method will be invoked.
If a callable was provided, the 'close' method on its return
value will be called to close the stream.
sourcemap_stream
If one is provided, the sourcemap will be written out to it.
Like output_stream, it could also be a callable and be handled
in the same manner.
If this argument is the same as output_stream (note: the return
value of any callables are not compared), the stream object that
is the same as the output_stream will be used for writing out
the source map, and the source map will instead be encoded as a
'data:application/json;base64,' URL.
sourcemap_normalize_mappings
Flag for the normalization of the sourcemap mappings; Defaults
to True to enable a reduction in output size.
sourcemap_normalize_paths
If set to true, all absolute paths will be converted to the
relative form when the sourcemap is generated, if all paths
provided are in the absolute form.
Defaults to True to enable a reduction in output size.
source_mapping_url
If unspecified, the default derived path will be written as a
sourceMappingURL comment into the output stream. If explicitly
specified with a value, that will be written instead. Set to
None to disable this.
"""
closer = []
def get_stream(stream):
if callable(stream):
result = stream()
closer.append(result.close)
else:
result = stream
return result
def cleanup():
for close in reversed(closer):
close()
chunks = None
if isinstance(nodes, Node):
chunks = unparser(nodes)
elif isinstance(nodes, Iterable):
raw = [unparser(node) for node in nodes if isinstance(node, Node)]
if raw:
chunks = chain(*raw)
if not chunks:
raise TypeError('must either provide a Node or list containing Nodes')
try:
out_s = get_stream(output_stream)
sourcemap_stream = (
out_s if sourcemap_stream is output_stream else sourcemap_stream)
mappings, sources, names = sourcemap.write(
chunks, out_s, normalize=sourcemap_normalize_mappings)
if sourcemap_stream:
sourcemap_stream = get_stream(sourcemap_stream)
sourcemap.write_sourcemap(
mappings, sources, names, out_s, sourcemap_stream,
normalize_paths=sourcemap_normalize_paths,
source_mapping_url=source_mapping_url,
)
finally:
cleanup() | python | def write(
unparser, nodes, output_stream, sourcemap_stream=None,
sourcemap_normalize_mappings=True,
sourcemap_normalize_paths=True,
source_mapping_url=NotImplemented):
"""
Write out the node using the unparser into an output stream, and
optionally the sourcemap using the sourcemap stream.
Ideally, file objects should be passed to the *_stream arguments, so
that the name resolution built into the sourcemap builder function
will be used. Also, if these file objects are opened using absolute
path arguments, enabling the sourcemap_normalize_paths flag will
have all paths normalized to their relative form.
If the provided streams are not anchored on the filesystem, or that
the provide node was generated from a string or in-memory stream,
the generation of the sourcemap should be done using the lower level
`write` function provided by the sourcemap module, which this method
wraps. Alternatively, the top level node should have its sourcepath
set to path that this node originated from.
Arguments
unparser
An unparser instance.
nodes
The Node or list of Nodes to stream to the output stream with
the unparser.
output_stream
Either a stream object or a callable that produces one. The
stream object to write to; its 'write' method will be invoked.
If a callable was provided, the 'close' method on its return
value will be called to close the stream.
sourcemap_stream
If one is provided, the sourcemap will be written out to it.
Like output_stream, it could also be a callable and be handled
in the same manner.
If this argument is the same as output_stream (note: the return
value of any callables are not compared), the stream object that
is the same as the output_stream will be used for writing out
the source map, and the source map will instead be encoded as a
'data:application/json;base64,' URL.
sourcemap_normalize_mappings
Flag for the normalization of the sourcemap mappings; Defaults
to True to enable a reduction in output size.
sourcemap_normalize_paths
If set to true, all absolute paths will be converted to the
relative form when the sourcemap is generated, if all paths
provided are in the absolute form.
Defaults to True to enable a reduction in output size.
source_mapping_url
If unspecified, the default derived path will be written as a
sourceMappingURL comment into the output stream. If explicitly
specified with a value, that will be written instead. Set to
None to disable this.
"""
closer = []
def get_stream(stream):
if callable(stream):
result = stream()
closer.append(result.close)
else:
result = stream
return result
def cleanup():
for close in reversed(closer):
close()
chunks = None
if isinstance(nodes, Node):
chunks = unparser(nodes)
elif isinstance(nodes, Iterable):
raw = [unparser(node) for node in nodes if isinstance(node, Node)]
if raw:
chunks = chain(*raw)
if not chunks:
raise TypeError('must either provide a Node or list containing Nodes')
try:
out_s = get_stream(output_stream)
sourcemap_stream = (
out_s if sourcemap_stream is output_stream else sourcemap_stream)
mappings, sources, names = sourcemap.write(
chunks, out_s, normalize=sourcemap_normalize_mappings)
if sourcemap_stream:
sourcemap_stream = get_stream(sourcemap_stream)
sourcemap.write_sourcemap(
mappings, sources, names, out_s, sourcemap_stream,
normalize_paths=sourcemap_normalize_paths,
source_mapping_url=source_mapping_url,
)
finally:
cleanup() | [
"def",
"write",
"(",
"unparser",
",",
"nodes",
",",
"output_stream",
",",
"sourcemap_stream",
"=",
"None",
",",
"sourcemap_normalize_mappings",
"=",
"True",
",",
"sourcemap_normalize_paths",
"=",
"True",
",",
"source_mapping_url",
"=",
"NotImplemented",
")",
":",
... | Write out the node using the unparser into an output stream, and
optionally the sourcemap using the sourcemap stream.
Ideally, file objects should be passed to the *_stream arguments, so
that the name resolution built into the sourcemap builder function
will be used. Also, if these file objects are opened using absolute
path arguments, enabling the sourcemap_normalize_paths flag will
have all paths normalized to their relative form.
If the provided streams are not anchored on the filesystem, or that
the provide node was generated from a string or in-memory stream,
the generation of the sourcemap should be done using the lower level
`write` function provided by the sourcemap module, which this method
wraps. Alternatively, the top level node should have its sourcepath
set to path that this node originated from.
Arguments
unparser
An unparser instance.
nodes
The Node or list of Nodes to stream to the output stream with
the unparser.
output_stream
Either a stream object or a callable that produces one. The
stream object to write to; its 'write' method will be invoked.
If a callable was provided, the 'close' method on its return
value will be called to close the stream.
sourcemap_stream
If one is provided, the sourcemap will be written out to it.
Like output_stream, it could also be a callable and be handled
in the same manner.
If this argument is the same as output_stream (note: the return
value of any callables are not compared), the stream object that
is the same as the output_stream will be used for writing out
the source map, and the source map will instead be encoded as a
'data:application/json;base64,' URL.
sourcemap_normalize_mappings
Flag for the normalization of the sourcemap mappings; Defaults
to True to enable a reduction in output size.
sourcemap_normalize_paths
If set to true, all absolute paths will be converted to the
relative form when the sourcemap is generated, if all paths
provided are in the absolute form.
Defaults to True to enable a reduction in output size.
source_mapping_url
If unspecified, the default derived path will be written as a
sourceMappingURL comment into the output stream. If explicitly
specified with a value, that will be written instead. Set to
None to disable this. | [
"Write",
"out",
"the",
"node",
"using",
"the",
"unparser",
"into",
"an",
"output",
"stream",
"and",
"optionally",
"the",
"sourcemap",
"using",
"the",
"sourcemap",
"stream",
"."
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/io.py#L47-L147 |
limix/limix-core | limix_core/mean/mean_efficient.py | Mean.dof | def dof(self, index=None):
"""The number of degrees of freedom"""
if index is None:
dof = 0
for i in range(self.len):
dof += self.A[i].shape[0] * self.F[i].shape[1]
return dof
else:
return self.A[index].shape[0] * self.F[index].shape[1] | python | def dof(self, index=None):
"""The number of degrees of freedom"""
if index is None:
dof = 0
for i in range(self.len):
dof += self.A[i].shape[0] * self.F[i].shape[1]
return dof
else:
return self.A[index].shape[0] * self.F[index].shape[1] | [
"def",
"dof",
"(",
"self",
",",
"index",
"=",
"None",
")",
":",
"if",
"index",
"is",
"None",
":",
"dof",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"len",
")",
":",
"dof",
"+=",
"self",
".",
"A",
"[",
"i",
"]",
".",
"shape",
"["... | The number of degrees of freedom | [
"The",
"number",
"of",
"degrees",
"of",
"freedom"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/mean/mean_efficient.py#L69-L77 |
limix/limix-core | limix_core/mean/mean_efficient.py | Mean.clearFixedEffect | def clearFixedEffect(self):
""" erase all fixed effects """
self.A = []
self.F = []
self.F_any = np.zeros((self.N,0))
self.clear_cache() | python | def clearFixedEffect(self):
""" erase all fixed effects """
self.A = []
self.F = []
self.F_any = np.zeros((self.N,0))
self.clear_cache() | [
"def",
"clearFixedEffect",
"(",
"self",
")",
":",
"self",
".",
"A",
"=",
"[",
"]",
"self",
".",
"F",
"=",
"[",
"]",
"self",
".",
"F_any",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"N",
",",
"0",
")",
")",
"self",
".",
"clear_cache",
"("... | erase all fixed effects | [
"erase",
"all",
"fixed",
"effects"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/mean/mean_efficient.py#L94-L99 |
limix/limix-core | limix_core/mean/mean_efficient.py | Mean.addFixedEffect | def addFixedEffect(self,F=None,A=None,index=None):
"""
set sample and trait designs
F: NxK sample design
A: LxP sample design
fast_computations: False deactivates the fast computations for any and common effects (for debugging)
"""
if F is None:
F = np.ones((self.N,1))
else:
assert F.shape[0]==self.N, "F dimension mismatch"
if ((A is None) or ( (A.shape == (self.P,self.P)) and (A==np.eye(self.P)).all() )):
#case any effect
self.F_any = np.hstack((self.F_any,F))
elif (index is not None) and ((A==self.A[index]).all()):
#case common effect
self.F[index] = np.hstack((self.F_index,F))
else:
#case general A
assert A.shape[1]==self.P, "A dimension mismatch"
self.F.append(F)
self.A.append(A)
self.clear_cache() | python | def addFixedEffect(self,F=None,A=None,index=None):
"""
set sample and trait designs
F: NxK sample design
A: LxP sample design
fast_computations: False deactivates the fast computations for any and common effects (for debugging)
"""
if F is None:
F = np.ones((self.N,1))
else:
assert F.shape[0]==self.N, "F dimension mismatch"
if ((A is None) or ( (A.shape == (self.P,self.P)) and (A==np.eye(self.P)).all() )):
#case any effect
self.F_any = np.hstack((self.F_any,F))
elif (index is not None) and ((A==self.A[index]).all()):
#case common effect
self.F[index] = np.hstack((self.F_index,F))
else:
#case general A
assert A.shape[1]==self.P, "A dimension mismatch"
self.F.append(F)
self.A.append(A)
self.clear_cache() | [
"def",
"addFixedEffect",
"(",
"self",
",",
"F",
"=",
"None",
",",
"A",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"if",
"F",
"is",
"None",
":",
"F",
"=",
"np",
".",
"ones",
"(",
"(",
"self",
".",
"N",
",",
"1",
")",
")",
"else",
":",... | set sample and trait designs
F: NxK sample design
A: LxP sample design
fast_computations: False deactivates the fast computations for any and common effects (for debugging) | [
"set",
"sample",
"and",
"trait",
"designs",
"F",
":",
"NxK",
"sample",
"design",
"A",
":",
"LxP",
"sample",
"design",
"fast_computations",
":",
"False",
"deactivates",
"the",
"fast",
"computations",
"for",
"any",
"and",
"common",
"effects",
"(",
"for",
"debu... | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/mean/mean_efficient.py#L101-L125 |
limix/limix-core | limix_core/mean/mean_efficient.py | Mean.Lr | def Lr(self,value):
""" set row rotation """
assert value.shape==(self.N, self.N), 'dimension mismatch'
self._Lr = value
self.clear_cache() | python | def Lr(self,value):
""" set row rotation """
assert value.shape==(self.N, self.N), 'dimension mismatch'
self._Lr = value
self.clear_cache() | [
"def",
"Lr",
"(",
"self",
",",
"value",
")",
":",
"assert",
"value",
".",
"shape",
"==",
"(",
"self",
".",
"N",
",",
"self",
".",
"N",
")",
",",
"'dimension mismatch'",
"self",
".",
"_Lr",
"=",
"value",
"self",
".",
"clear_cache",
"(",
")"
] | set row rotation | [
"set",
"row",
"rotation"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/mean/mean_efficient.py#L129-L133 |
limix/limix-core | limix_core/mean/mean_efficient.py | Mean.Lc | def Lc(self,value):
""" set col rotation """
assert value.shape==(self.P, self.P), 'dimension mismatch'
self._Lc = value
self.clear_cache() | python | def Lc(self,value):
""" set col rotation """
assert value.shape==(self.P, self.P), 'dimension mismatch'
self._Lc = value
self.clear_cache() | [
"def",
"Lc",
"(",
"self",
",",
"value",
")",
":",
"assert",
"value",
".",
"shape",
"==",
"(",
"self",
".",
"P",
",",
"self",
".",
"P",
")",
",",
"'dimension mismatch'",
"self",
".",
"_Lc",
"=",
"value",
"self",
".",
"clear_cache",
"(",
")"
] | set col rotation | [
"set",
"col",
"rotation"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/mean/mean_efficient.py#L136-L140 |
limix/limix-core | limix_core/mean/mean_efficient.py | Mean.d | def d(self,value):
""" set anisotropic scaling """
assert value.shape[0]==self.P*self.N, 'd dimension mismatch'
self._d = value
self.clear_cache() | python | def d(self,value):
""" set anisotropic scaling """
assert value.shape[0]==self.P*self.N, 'd dimension mismatch'
self._d = value
self.clear_cache() | [
"def",
"d",
"(",
"self",
",",
"value",
")",
":",
"assert",
"value",
".",
"shape",
"[",
"0",
"]",
"==",
"self",
".",
"P",
"*",
"self",
".",
"N",
",",
"'d dimension mismatch'",
"self",
".",
"_d",
"=",
"value",
"self",
".",
"clear_cache",
"(",
")"
] | set anisotropic scaling | [
"set",
"anisotropic",
"scaling"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/mean/mean_efficient.py#L143-L147 |
limix/limix-core | limix_core/mean/mean_efficient.py | Mean.beta_hat | def beta_hat(self):
"""compute ML beta"""
XKY = self.XKY()
XanyKY = self.XanyKY()
beta_hat, beta_hat_any = self.Areml_solver.solve(b_any=XanyKY,b=XKY,check_finite=True)
return beta_hat, beta_hat_any | python | def beta_hat(self):
"""compute ML beta"""
XKY = self.XKY()
XanyKY = self.XanyKY()
beta_hat, beta_hat_any = self.Areml_solver.solve(b_any=XanyKY,b=XKY,check_finite=True)
return beta_hat, beta_hat_any | [
"def",
"beta_hat",
"(",
"self",
")",
":",
"XKY",
"=",
"self",
".",
"XKY",
"(",
")",
"XanyKY",
"=",
"self",
".",
"XanyKY",
"(",
")",
"beta_hat",
",",
"beta_hat_any",
"=",
"self",
".",
"Areml_solver",
".",
"solve",
"(",
"b_any",
"=",
"XanyKY",
",",
"... | compute ML beta | [
"compute",
"ML",
"beta"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/mean/mean_efficient.py#L200-L205 |
limix/limix-core | limix_core/mean/mean_efficient.py | Mean.XanyKXany | def XanyKXany(self):
"""
compute self covariance for any
"""
result = np.empty((self.P,self.F_any.shape[1],self.F_any.shape[1]), order='C')
for p in range(self.P):
X1D = self.Fstar_any * self.D[:,p:p+1]
X1X2 = X1D.T.dot(self.Fstar_any)
result[p] = X1X2
return result | python | def XanyKXany(self):
"""
compute self covariance for any
"""
result = np.empty((self.P,self.F_any.shape[1],self.F_any.shape[1]), order='C')
for p in range(self.P):
X1D = self.Fstar_any * self.D[:,p:p+1]
X1X2 = X1D.T.dot(self.Fstar_any)
result[p] = X1X2
return result | [
"def",
"XanyKXany",
"(",
"self",
")",
":",
"result",
"=",
"np",
".",
"empty",
"(",
"(",
"self",
".",
"P",
",",
"self",
".",
"F_any",
".",
"shape",
"[",
"1",
"]",
",",
"self",
".",
"F_any",
".",
"shape",
"[",
"1",
"]",
")",
",",
"order",
"=",
... | compute self covariance for any | [
"compute",
"self",
"covariance",
"for",
"any"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/mean/mean_efficient.py#L223-L232 |
limix/limix-core | limix_core/mean/mean_efficient.py | Mean.XanyKX | def XanyKX(self):
"""
compute cross covariance for any and rest
"""
result = np.empty((self.P,self.F_any.shape[1],self.dof), order='C')
#This is trivially parallelizable:
for p in range(self.P):
FanyD = self.Fstar_any * self.D[:,p:p+1]
start = 0
#This is trivially parallelizable:
for term in range(self.len):
stop = start + self.F[term].shape[1]*self.A[term].shape[0]
result[p,:,start:stop] = self.XanyKX2_single_p_single_term(p=p, F1=FanyD, F2=self.Fstar[term], A2=self.Astar[term])
start = stop
return result | python | def XanyKX(self):
"""
compute cross covariance for any and rest
"""
result = np.empty((self.P,self.F_any.shape[1],self.dof), order='C')
#This is trivially parallelizable:
for p in range(self.P):
FanyD = self.Fstar_any * self.D[:,p:p+1]
start = 0
#This is trivially parallelizable:
for term in range(self.len):
stop = start + self.F[term].shape[1]*self.A[term].shape[0]
result[p,:,start:stop] = self.XanyKX2_single_p_single_term(p=p, F1=FanyD, F2=self.Fstar[term], A2=self.Astar[term])
start = stop
return result | [
"def",
"XanyKX",
"(",
"self",
")",
":",
"result",
"=",
"np",
".",
"empty",
"(",
"(",
"self",
".",
"P",
",",
"self",
".",
"F_any",
".",
"shape",
"[",
"1",
"]",
",",
"self",
".",
"dof",
")",
",",
"order",
"=",
"'C'",
")",
"#This is trivially parall... | compute cross covariance for any and rest | [
"compute",
"cross",
"covariance",
"for",
"any",
"and",
"rest"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/mean/mean_efficient.py#L235-L249 |
limix/limix-core | limix_core/mean/mean_efficient.py | Mean.XKX | def XKX(self):
"""
compute self covariance for rest
"""
cov_beta = np.zeros((self.dof,self.dof))
start_row = 0
#This is trivially parallelizable:
for term1 in range(self.len):
stop_row = start_row + self.A[term1].shape[0] * self.F[term1].shape[1]
start_col = start_row
#This is trivially parallelizable:
for term2 in range(term1,self.len):
stop_col = start_col + self.A[term2].shape[0] * self.F[term2].shape[1]
cov_beta[start_row:stop_row, start_col:stop_col] = compute_X1KX2(Y=self.Ystar(), D=self.D, X1=self.Fstar[term1], X2=self.Fstar[term2], A1=self.Astar[term1], A2=self.Astar[term2])
if term1!=term2:
cov_beta[start_col:stop_col, start_row:stop_row] = cov_beta[n_weights1:stop_row, n_weights2:stop_col].T
start_col = stop_col
start_row = stop_row
return cov_beta | python | def XKX(self):
"""
compute self covariance for rest
"""
cov_beta = np.zeros((self.dof,self.dof))
start_row = 0
#This is trivially parallelizable:
for term1 in range(self.len):
stop_row = start_row + self.A[term1].shape[0] * self.F[term1].shape[1]
start_col = start_row
#This is trivially parallelizable:
for term2 in range(term1,self.len):
stop_col = start_col + self.A[term2].shape[0] * self.F[term2].shape[1]
cov_beta[start_row:stop_row, start_col:stop_col] = compute_X1KX2(Y=self.Ystar(), D=self.D, X1=self.Fstar[term1], X2=self.Fstar[term2], A1=self.Astar[term1], A2=self.Astar[term2])
if term1!=term2:
cov_beta[start_col:stop_col, start_row:stop_row] = cov_beta[n_weights1:stop_row, n_weights2:stop_col].T
start_col = stop_col
start_row = stop_row
return cov_beta | [
"def",
"XKX",
"(",
"self",
")",
":",
"cov_beta",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"dof",
",",
"self",
".",
"dof",
")",
")",
"start_row",
"=",
"0",
"#This is trivially parallelizable:",
"for",
"term1",
"in",
"range",
"(",
"self",
".",
"... | compute self covariance for rest | [
"compute",
"self",
"covariance",
"for",
"rest"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/mean/mean_efficient.py#L251-L269 |
gautammishra/lyft-rides-python-sdk | lyft_rides/auth.py | request_access_token | def request_access_token(
grant_type,
client_id=None,
client_secret=None,
scopes=None,
code=None,
refresh_token=None
):
"""Make an HTTP POST to request an access token.
Parameters
grant_type (str)
Either 'client_credientials' (Client Credentials Grant)
or 'authorization_code' (Authorization Code Grant).
client_id (str)
Your app's Client ID.
client_secret (str)
Your app's Client Secret.
scopes (set)
Set of permission scopes to request.
(e.g. {'profile', 'history'})
code (str)
The authorization code to switch for an access token.
Only used in Authorization Code Grant.
refresh_token (str)
Refresh token used to get a new access token.
Only used for Authorization Code Grant.
Returns
(requests.Response)
Successful HTTP response from a 'POST' to request
an access token.
Raises
ClientError (APIError)
Thrown if there was an HTTP error.
"""
url = build_url(auth.SERVER_HOST, auth.ACCESS_TOKEN_PATH)
if isinstance(scopes, set):
scopes = ' '.join(scopes)
args = {
'grant_type': grant_type,
'client_id': client_id,
'client_secret': client_secret,
'scope': scopes,
'code': code,
'refresh_token': refresh_token,
}
auth_header = HTTPBasicAuth(client_id, client_secret)
response = post(url=url, auth=auth_header, data=args)
if response.status_code == codes.ok:
return response
message = 'Failed to request access token: {}.'
message = message.format(response.reason)
raise ClientError(response, message) | python | def request_access_token(
grant_type,
client_id=None,
client_secret=None,
scopes=None,
code=None,
refresh_token=None
):
"""Make an HTTP POST to request an access token.
Parameters
grant_type (str)
Either 'client_credientials' (Client Credentials Grant)
or 'authorization_code' (Authorization Code Grant).
client_id (str)
Your app's Client ID.
client_secret (str)
Your app's Client Secret.
scopes (set)
Set of permission scopes to request.
(e.g. {'profile', 'history'})
code (str)
The authorization code to switch for an access token.
Only used in Authorization Code Grant.
refresh_token (str)
Refresh token used to get a new access token.
Only used for Authorization Code Grant.
Returns
(requests.Response)
Successful HTTP response from a 'POST' to request
an access token.
Raises
ClientError (APIError)
Thrown if there was an HTTP error.
"""
url = build_url(auth.SERVER_HOST, auth.ACCESS_TOKEN_PATH)
if isinstance(scopes, set):
scopes = ' '.join(scopes)
args = {
'grant_type': grant_type,
'client_id': client_id,
'client_secret': client_secret,
'scope': scopes,
'code': code,
'refresh_token': refresh_token,
}
auth_header = HTTPBasicAuth(client_id, client_secret)
response = post(url=url, auth=auth_header, data=args)
if response.status_code == codes.ok:
return response
message = 'Failed to request access token: {}.'
message = message.format(response.reason)
raise ClientError(response, message) | [
"def",
"request_access_token",
"(",
"grant_type",
",",
"client_id",
"=",
"None",
",",
"client_secret",
"=",
"None",
",",
"scopes",
"=",
"None",
",",
"code",
"=",
"None",
",",
"refresh_token",
"=",
"None",
")",
":",
"url",
"=",
"build_url",
"(",
"auth",
"... | Make an HTTP POST to request an access token.
Parameters
grant_type (str)
Either 'client_credientials' (Client Credentials Grant)
or 'authorization_code' (Authorization Code Grant).
client_id (str)
Your app's Client ID.
client_secret (str)
Your app's Client Secret.
scopes (set)
Set of permission scopes to request.
(e.g. {'profile', 'history'})
code (str)
The authorization code to switch for an access token.
Only used in Authorization Code Grant.
refresh_token (str)
Refresh token used to get a new access token.
Only used for Authorization Code Grant.
Returns
(requests.Response)
Successful HTTP response from a 'POST' to request
an access token.
Raises
ClientError (APIError)
Thrown if there was an HTTP error. | [
"Make",
"an",
"HTTP",
"POST",
"to",
"request",
"an",
"access",
"token",
".",
"Parameters",
"grant_type",
"(",
"str",
")",
"Either",
"client_credientials",
"(",
"Client",
"Credentials",
"Grant",
")",
"or",
"authorization_code",
"(",
"Authorization",
"Code",
"Gran... | train | https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/lyft_rides/auth.py#L310-L367 |
gautammishra/lyft-rides-python-sdk | lyft_rides/auth.py | refresh_access_token | def refresh_access_token(credential):
"""Use a refresh token to request a new access token.
Not suported for access tokens obtained via Implicit Grant.
Parameters
credential (OAuth2Credential)
An authorized user's OAuth 2.0 credentials.
Returns
(Session)
A new Session object with refreshed OAuth 2.0 credentials.
Raises
LyftIllegalState (APIError)
Raised if OAuth 2.0 grant type does not support
refresh tokens.
"""
if credential.grant_type == auth.AUTHORIZATION_CODE_GRANT:
response = request_access_token(
grant_type=auth.REFRESH_TOKEN,
client_id=credential.client_id,
client_secret=credential.client_secret,
refresh_token=credential.refresh_token,
)
oauth2credential = OAuth2Credential.make_from_response(
response=response,
grant_type=credential.grant_type,
client_id=credential.client_id,
client_secret=credential.client_secret,
)
return Session(oauth2credential=oauth2credential)
elif credential.grant_type == auth.CLIENT_CREDENTIAL_GRANT:
response = request_access_token(
grant_type=auth.CLIENT_CREDENTIAL_GRANT,
client_id=credential.client_id,
client_secret=credential.client_secret,
scopes=credential.scopes,
)
oauth2credential = OAuth2Credential.make_from_response(
response=response,
grant_type=credential.grant_type,
client_id=credential.client_id,
client_secret=credential.client_secret,
)
return Session(oauth2credential=oauth2credential)
message = '{} Grant Type does not support Refresh Tokens.'
message = message.format(credential.grant_type)
raise LyftIllegalState(message) | python | def refresh_access_token(credential):
"""Use a refresh token to request a new access token.
Not suported for access tokens obtained via Implicit Grant.
Parameters
credential (OAuth2Credential)
An authorized user's OAuth 2.0 credentials.
Returns
(Session)
A new Session object with refreshed OAuth 2.0 credentials.
Raises
LyftIllegalState (APIError)
Raised if OAuth 2.0 grant type does not support
refresh tokens.
"""
if credential.grant_type == auth.AUTHORIZATION_CODE_GRANT:
response = request_access_token(
grant_type=auth.REFRESH_TOKEN,
client_id=credential.client_id,
client_secret=credential.client_secret,
refresh_token=credential.refresh_token,
)
oauth2credential = OAuth2Credential.make_from_response(
response=response,
grant_type=credential.grant_type,
client_id=credential.client_id,
client_secret=credential.client_secret,
)
return Session(oauth2credential=oauth2credential)
elif credential.grant_type == auth.CLIENT_CREDENTIAL_GRANT:
response = request_access_token(
grant_type=auth.CLIENT_CREDENTIAL_GRANT,
client_id=credential.client_id,
client_secret=credential.client_secret,
scopes=credential.scopes,
)
oauth2credential = OAuth2Credential.make_from_response(
response=response,
grant_type=credential.grant_type,
client_id=credential.client_id,
client_secret=credential.client_secret,
)
return Session(oauth2credential=oauth2credential)
message = '{} Grant Type does not support Refresh Tokens.'
message = message.format(credential.grant_type)
raise LyftIllegalState(message) | [
"def",
"refresh_access_token",
"(",
"credential",
")",
":",
"if",
"credential",
".",
"grant_type",
"==",
"auth",
".",
"AUTHORIZATION_CODE_GRANT",
":",
"response",
"=",
"request_access_token",
"(",
"grant_type",
"=",
"auth",
".",
"REFRESH_TOKEN",
",",
"client_id",
... | Use a refresh token to request a new access token.
Not suported for access tokens obtained via Implicit Grant.
Parameters
credential (OAuth2Credential)
An authorized user's OAuth 2.0 credentials.
Returns
(Session)
A new Session object with refreshed OAuth 2.0 credentials.
Raises
LyftIllegalState (APIError)
Raised if OAuth 2.0 grant type does not support
refresh tokens. | [
"Use",
"a",
"refresh",
"token",
"to",
"request",
"a",
"new",
"access",
"token",
".",
"Not",
"suported",
"for",
"access",
"tokens",
"obtained",
"via",
"Implicit",
"Grant",
".",
"Parameters",
"credential",
"(",
"OAuth2Credential",
")",
"An",
"authorized",
"user"... | train | https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/lyft_rides/auth.py#L370-L420 |
gautammishra/lyft-rides-python-sdk | lyft_rides/auth.py | revoke_access_token | def revoke_access_token(credential):
"""Revoke an access token.
All future requests with the access token will be invalid.
Parameters
credential (OAuth2Credential)
An authorized user's OAuth 2.0 credentials.
Raises
ClientError (APIError)
Thrown if there was an HTTP error.
"""
url = build_url(auth.SERVER_HOST, auth.REVOKE_PATH)
args = {
'token': credential.access_token,
}
response = post(url=url, params=args)
if response.status_code == codes.ok:
return
message = 'Failed to revoke access token: {}.'
message = message.format(response.reason)
raise ClientError(response, message) | python | def revoke_access_token(credential):
"""Revoke an access token.
All future requests with the access token will be invalid.
Parameters
credential (OAuth2Credential)
An authorized user's OAuth 2.0 credentials.
Raises
ClientError (APIError)
Thrown if there was an HTTP error.
"""
url = build_url(auth.SERVER_HOST, auth.REVOKE_PATH)
args = {
'token': credential.access_token,
}
response = post(url=url, params=args)
if response.status_code == codes.ok:
return
message = 'Failed to revoke access token: {}.'
message = message.format(response.reason)
raise ClientError(response, message) | [
"def",
"revoke_access_token",
"(",
"credential",
")",
":",
"url",
"=",
"build_url",
"(",
"auth",
".",
"SERVER_HOST",
",",
"auth",
".",
"REVOKE_PATH",
")",
"args",
"=",
"{",
"'token'",
":",
"credential",
".",
"access_token",
",",
"}",
"response",
"=",
"post... | Revoke an access token.
All future requests with the access token will be invalid.
Parameters
credential (OAuth2Credential)
An authorized user's OAuth 2.0 credentials.
Raises
ClientError (APIError)
Thrown if there was an HTTP error. | [
"Revoke",
"an",
"access",
"token",
".",
"All",
"future",
"requests",
"with",
"the",
"access",
"token",
"will",
"be",
"invalid",
".",
"Parameters",
"credential",
"(",
"OAuth2Credential",
")",
"An",
"authorized",
"user",
"s",
"OAuth",
"2",
".",
"0",
"credentia... | train | https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/lyft_rides/auth.py#L423-L446 |
gautammishra/lyft-rides-python-sdk | lyft_rides/auth.py | OAuth2._build_authorization_request_url | def _build_authorization_request_url(
self,
response_type,
state=None
):
"""Form URL to request an auth code or access token.
Parameters
response_type (str)
Only 'code' (Authorization Code Grant) supported at this time
state (str)
Optional CSRF State token to send to server.
Returns
(str)
The fully constructed authorization request URL.
Raises
LyftIllegalState (ApiError)
Raised if response_type parameter is invalid.
"""
if response_type not in auth.VALID_RESPONSE_TYPES:
message = '{} is not a valid response type.'
raise LyftIllegalState(message.format(response_type))
args = OrderedDict([
('scope', ' '.join(self.scopes)),
('state', state),
('response_type', response_type),
('client_id', self.client_id),
])
return build_url(auth.SERVER_HOST, auth.AUTHORIZE_PATH, args) | python | def _build_authorization_request_url(
self,
response_type,
state=None
):
"""Form URL to request an auth code or access token.
Parameters
response_type (str)
Only 'code' (Authorization Code Grant) supported at this time
state (str)
Optional CSRF State token to send to server.
Returns
(str)
The fully constructed authorization request URL.
Raises
LyftIllegalState (ApiError)
Raised if response_type parameter is invalid.
"""
if response_type not in auth.VALID_RESPONSE_TYPES:
message = '{} is not a valid response type.'
raise LyftIllegalState(message.format(response_type))
args = OrderedDict([
('scope', ' '.join(self.scopes)),
('state', state),
('response_type', response_type),
('client_id', self.client_id),
])
return build_url(auth.SERVER_HOST, auth.AUTHORIZE_PATH, args) | [
"def",
"_build_authorization_request_url",
"(",
"self",
",",
"response_type",
",",
"state",
"=",
"None",
")",
":",
"if",
"response_type",
"not",
"in",
"auth",
".",
"VALID_RESPONSE_TYPES",
":",
"message",
"=",
"'{} is not a valid response type.'",
"raise",
"LyftIllegal... | Form URL to request an auth code or access token.
Parameters
response_type (str)
Only 'code' (Authorization Code Grant) supported at this time
state (str)
Optional CSRF State token to send to server.
Returns
(str)
The fully constructed authorization request URL.
Raises
LyftIllegalState (ApiError)
Raised if response_type parameter is invalid. | [
"Form",
"URL",
"to",
"request",
"an",
"auth",
"code",
"or",
"access",
"token",
".",
"Parameters",
"response_type",
"(",
"str",
")",
"Only",
"code",
"(",
"Authorization",
"Code",
"Grant",
")",
"supported",
"at",
"this",
"time",
"state",
"(",
"str",
")",
"... | train | https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/lyft_rides/auth.py#L61-L90 |
gautammishra/lyft-rides-python-sdk | lyft_rides/auth.py | OAuth2._extract_query | def _extract_query(self, redirect_url):
"""Extract query parameters from a url.
Parameters
redirect_url (str)
The full URL that the Lyft server redirected to after
the user authorized your app.
Returns
(dict)
A dictionary of query parameters.
"""
qs = urlparse(redirect_url)
# redirect_urls return data after query identifier (?)
qs = qs.query
query_params = parse_qs(qs)
query_params = {qp: query_params[qp][0] for qp in query_params}
return query_params | python | def _extract_query(self, redirect_url):
"""Extract query parameters from a url.
Parameters
redirect_url (str)
The full URL that the Lyft server redirected to after
the user authorized your app.
Returns
(dict)
A dictionary of query parameters.
"""
qs = urlparse(redirect_url)
# redirect_urls return data after query identifier (?)
qs = qs.query
query_params = parse_qs(qs)
query_params = {qp: query_params[qp][0] for qp in query_params}
return query_params | [
"def",
"_extract_query",
"(",
"self",
",",
"redirect_url",
")",
":",
"qs",
"=",
"urlparse",
"(",
"redirect_url",
")",
"# redirect_urls return data after query identifier (?)",
"qs",
"=",
"qs",
".",
"query",
"query_params",
"=",
"parse_qs",
"(",
"qs",
")",
"query_p... | Extract query parameters from a url.
Parameters
redirect_url (str)
The full URL that the Lyft server redirected to after
the user authorized your app.
Returns
(dict)
A dictionary of query parameters. | [
"Extract",
"query",
"parameters",
"from",
"a",
"url",
".",
"Parameters",
"redirect_url",
"(",
"str",
")",
"The",
"full",
"URL",
"that",
"the",
"Lyft",
"server",
"redirected",
"to",
"after",
"the",
"user",
"authorized",
"your",
"app",
".",
"Returns",
"(",
"... | train | https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/lyft_rides/auth.py#L92-L110 |
gautammishra/lyft-rides-python-sdk | lyft_rides/auth.py | AuthorizationCodeGrant.get_session | def get_session(self, redirect_url):
"""Complete the Authorization Code Grant process.
The redirect URL received after the user has authorized
your application contains an authorization code. Use this
authorization code to request an access token.
Parameters
redirect_url (str)
The full URL that the Lyft server redirected to after
the user authorized your app.
Returns
(Session)
A Session object with OAuth 2.0 credentials.
"""
query_params = self._extract_query(redirect_url)
authorization_code = self._verify_query(query_params)
response = request_access_token(
grant_type=auth.AUTHORIZATION_CODE_GRANT,
client_id=self.client_id,
client_secret=self.client_secret,
code=authorization_code,
)
oauth2credential = OAuth2Credential.make_from_response(
response=response,
grant_type=auth.AUTHORIZATION_CODE_GRANT,
client_id=self.client_id,
client_secret=self.client_secret,
)
return Session(oauth2credential=oauth2credential) | python | def get_session(self, redirect_url):
"""Complete the Authorization Code Grant process.
The redirect URL received after the user has authorized
your application contains an authorization code. Use this
authorization code to request an access token.
Parameters
redirect_url (str)
The full URL that the Lyft server redirected to after
the user authorized your app.
Returns
(Session)
A Session object with OAuth 2.0 credentials.
"""
query_params = self._extract_query(redirect_url)
authorization_code = self._verify_query(query_params)
response = request_access_token(
grant_type=auth.AUTHORIZATION_CODE_GRANT,
client_id=self.client_id,
client_secret=self.client_secret,
code=authorization_code,
)
oauth2credential = OAuth2Credential.make_from_response(
response=response,
grant_type=auth.AUTHORIZATION_CODE_GRANT,
client_id=self.client_id,
client_secret=self.client_secret,
)
return Session(oauth2credential=oauth2credential) | [
"def",
"get_session",
"(",
"self",
",",
"redirect_url",
")",
":",
"query_params",
"=",
"self",
".",
"_extract_query",
"(",
"redirect_url",
")",
"authorization_code",
"=",
"self",
".",
"_verify_query",
"(",
"query_params",
")",
"response",
"=",
"request_access_toke... | Complete the Authorization Code Grant process.
The redirect URL received after the user has authorized
your application contains an authorization code. Use this
authorization code to request an access token.
Parameters
redirect_url (str)
The full URL that the Lyft server redirected to after
the user authorized your app.
Returns
(Session)
A Session object with OAuth 2.0 credentials. | [
"Complete",
"the",
"Authorization",
"Code",
"Grant",
"process",
".",
"The",
"redirect",
"URL",
"received",
"after",
"the",
"user",
"has",
"authorized",
"your",
"application",
"contains",
"an",
"authorization",
"code",
".",
"Use",
"this",
"authorization",
"code",
... | train | https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/lyft_rides/auth.py#L231-L261 |
gautammishra/lyft-rides-python-sdk | lyft_rides/auth.py | ClientCredentialGrant.get_session | def get_session(self):
"""Create Session to store credentials.
Returns
(Session)
A Session object with OAuth 2.0 credentials.
"""
response = request_access_token(
grant_type=auth.CLIENT_CREDENTIAL_GRANT,
client_id=self.client_id,
client_secret=self.client_secret,
scopes=self.scopes,
)
oauth2credential = OAuth2Credential.make_from_response(
response=response,
grant_type=auth.CLIENT_CREDENTIAL_GRANT,
client_id=self.client_id,
client_secret=self.client_secret,
)
return Session(oauth2credential=oauth2credential) | python | def get_session(self):
"""Create Session to store credentials.
Returns
(Session)
A Session object with OAuth 2.0 credentials.
"""
response = request_access_token(
grant_type=auth.CLIENT_CREDENTIAL_GRANT,
client_id=self.client_id,
client_secret=self.client_secret,
scopes=self.scopes,
)
oauth2credential = OAuth2Credential.make_from_response(
response=response,
grant_type=auth.CLIENT_CREDENTIAL_GRANT,
client_id=self.client_id,
client_secret=self.client_secret,
)
return Session(oauth2credential=oauth2credential) | [
"def",
"get_session",
"(",
"self",
")",
":",
"response",
"=",
"request_access_token",
"(",
"grant_type",
"=",
"auth",
".",
"CLIENT_CREDENTIAL_GRANT",
",",
"client_id",
"=",
"self",
".",
"client_id",
",",
"client_secret",
"=",
"self",
".",
"client_secret",
",",
... | Create Session to store credentials.
Returns
(Session)
A Session object with OAuth 2.0 credentials. | [
"Create",
"Session",
"to",
"store",
"credentials",
".",
"Returns",
"(",
"Session",
")",
"A",
"Session",
"object",
"with",
"OAuth",
"2",
".",
"0",
"credentials",
"."
] | train | https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/lyft_rides/auth.py#L287-L307 |
gautammishra/lyft-rides-python-sdk | examples/authorization_code_grant.py | hello_user | def hello_user(api_client):
"""Use an authorized client to fetch and print profile information.
Parameters
api_client (LyftRidesClient)
An LyftRidesClient with OAuth 2.0 credentials.
"""
try:
response = api_client.get_user_profile()
except (ClientError, ServerError) as error:
fail_print(error)
return
else:
profile = response.json
user_id = profile.get('id')
message = 'Hello. Successfully granted access token to User ID {}.'.format(user_id)
success_print(message) | python | def hello_user(api_client):
"""Use an authorized client to fetch and print profile information.
Parameters
api_client (LyftRidesClient)
An LyftRidesClient with OAuth 2.0 credentials.
"""
try:
response = api_client.get_user_profile()
except (ClientError, ServerError) as error:
fail_print(error)
return
else:
profile = response.json
user_id = profile.get('id')
message = 'Hello. Successfully granted access token to User ID {}.'.format(user_id)
success_print(message) | [
"def",
"hello_user",
"(",
"api_client",
")",
":",
"try",
":",
"response",
"=",
"api_client",
".",
"get_user_profile",
"(",
")",
"except",
"(",
"ClientError",
",",
"ServerError",
")",
"as",
"error",
":",
"fail_print",
"(",
"error",
")",
"return",
"else",
":... | Use an authorized client to fetch and print profile information.
Parameters
api_client (LyftRidesClient)
An LyftRidesClient with OAuth 2.0 credentials. | [
"Use",
"an",
"authorized",
"client",
"to",
"fetch",
"and",
"print",
"profile",
"information",
".",
"Parameters",
"api_client",
"(",
"LyftRidesClient",
")",
"An",
"LyftRidesClient",
"with",
"OAuth",
"2",
".",
"0",
"credentials",
"."
] | train | https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/examples/authorization_code_grant.py#L92-L110 |
pyroscope/pyrobase | src/pyrobase/paver/quality.py | lint | def lint():
"report pylint results"
# report according to file extension
report_formats = {
".html": "html",
".log": "parseable",
".txt": "text",
}
lint_build_dir = easy.path("build/lint")
lint_build_dir.exists() or lint_build_dir.makedirs() # pylint: disable=expression-not-assigned
argv = []
rcfile = easy.options.lint.get("rcfile")
if not rcfile and easy.path("pylint.cfg").exists():
rcfile = "pylint.cfg"
if rcfile:
argv += ["--rcfile", os.path.abspath(rcfile)]
if easy.options.lint.get("msg_only", False):
argv += ["-rn"]
argv += [
"--import-graph", (lint_build_dir / "imports.dot").abspath(),
]
argv += support.toplevel_packages()
sys.stderr.write("Running %s::pylint '%s'\n" % (sys.argv[0], "' '".join(argv)))
outfile = easy.options.lint.get("output", None)
if outfile:
outfile = os.path.abspath(outfile)
try:
with easy.pushd("src" if easy.path("src").exists() else "."):
if outfile:
argv.extend(["-f", report_formats.get(easy.path(outfile).ext, "text")])
sys.stderr.write("Writing output to %r\n" % (str(outfile),))
outhandle = open(outfile, "w")
try:
subprocess.check_call(["pylint"] + argv, stdout=outhandle)
finally:
outhandle.close()
else:
subprocess.check_call(["pylint"] + argv, )
sys.stderr.write("paver::lint - No problems found.\n")
except subprocess.CalledProcessError as exc:
if exc.returncode & 32:
# usage error (internal error in this code)
sys.stderr.write("paver::lint - Usage error, bad arguments %r?!\n" % (argv,))
sys.exit(exc.returncode)
else:
bits = {
1: "fatal",
2: "error",
4: "warning",
8: "refactor",
16: "convention",
}
sys.stderr.write("paver::lint - Some %s message(s) issued.\n" % (
", ".join([text for bit, text in bits.items() if exc.returncode & bit])
))
if exc.returncode & 3:
sys.stderr.write("paver::lint - Exiting due to fatal / error message.\n")
sys.exit(exc.returncode) | python | def lint():
"report pylint results"
# report according to file extension
report_formats = {
".html": "html",
".log": "parseable",
".txt": "text",
}
lint_build_dir = easy.path("build/lint")
lint_build_dir.exists() or lint_build_dir.makedirs() # pylint: disable=expression-not-assigned
argv = []
rcfile = easy.options.lint.get("rcfile")
if not rcfile and easy.path("pylint.cfg").exists():
rcfile = "pylint.cfg"
if rcfile:
argv += ["--rcfile", os.path.abspath(rcfile)]
if easy.options.lint.get("msg_only", False):
argv += ["-rn"]
argv += [
"--import-graph", (lint_build_dir / "imports.dot").abspath(),
]
argv += support.toplevel_packages()
sys.stderr.write("Running %s::pylint '%s'\n" % (sys.argv[0], "' '".join(argv)))
outfile = easy.options.lint.get("output", None)
if outfile:
outfile = os.path.abspath(outfile)
try:
with easy.pushd("src" if easy.path("src").exists() else "."):
if outfile:
argv.extend(["-f", report_formats.get(easy.path(outfile).ext, "text")])
sys.stderr.write("Writing output to %r\n" % (str(outfile),))
outhandle = open(outfile, "w")
try:
subprocess.check_call(["pylint"] + argv, stdout=outhandle)
finally:
outhandle.close()
else:
subprocess.check_call(["pylint"] + argv, )
sys.stderr.write("paver::lint - No problems found.\n")
except subprocess.CalledProcessError as exc:
if exc.returncode & 32:
# usage error (internal error in this code)
sys.stderr.write("paver::lint - Usage error, bad arguments %r?!\n" % (argv,))
sys.exit(exc.returncode)
else:
bits = {
1: "fatal",
2: "error",
4: "warning",
8: "refactor",
16: "convention",
}
sys.stderr.write("paver::lint - Some %s message(s) issued.\n" % (
", ".join([text for bit, text in bits.items() if exc.returncode & bit])
))
if exc.returncode & 3:
sys.stderr.write("paver::lint - Exiting due to fatal / error message.\n")
sys.exit(exc.returncode) | [
"def",
"lint",
"(",
")",
":",
"# report according to file extension",
"report_formats",
"=",
"{",
"\".html\"",
":",
"\"html\"",
",",
"\".log\"",
":",
"\"parseable\"",
",",
"\".txt\"",
":",
"\"text\"",
",",
"}",
"lint_build_dir",
"=",
"easy",
".",
"path",
"(",
... | report pylint results | [
"report",
"pylint",
"results"
] | train | https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/paver/quality.py#L37-L98 |
mikekatz04/BOWIE | snr_calculator_folder/gwsnrcalc/generate_contour_data.py | generate_contour_data | def generate_contour_data(pid):
"""
Main function for this program.
This will read in sensitivity_curves and binary parameters; calculate snrs
with a matched filtering approach; and then read the contour data out to a file.
Args:
pid (obj or dict): GenInput class or dictionary containing all of the input information for
the generation. See BOWIE documentation and example notebooks for usage of
this class.
"""
# check if pid is dicionary or GenInput class
# if GenInput, change to dictionary
if isinstance(pid, GenInput):
pid = pid.return_dict()
begin_time = time.time()
WORKING_DIRECTORY = '.'
if 'WORKING_DIRECTORY' not in pid['general'].keys():
pid['general']['WORKING_DIRECTORY'] = WORKING_DIRECTORY
# Generate the contour data.
running_process = GenProcess(**{**pid, **pid['generate_info']})
running_process.set_parameters()
running_process.run_snr()
# Read out
file_out = FileReadOut(running_process.xvals, running_process.yvals,
running_process.final_dict,
**{**pid['general'], **pid['generate_info'], **pid['output_info']})
print('outputing file:', pid['general']['WORKING_DIRECTORY'] + '/'
+ pid['output_info']['output_file_name'])
getattr(file_out, file_out.output_file_type + '_read_out')()
print(time.time()-begin_time)
return | python | def generate_contour_data(pid):
"""
Main function for this program.
This will read in sensitivity_curves and binary parameters; calculate snrs
with a matched filtering approach; and then read the contour data out to a file.
Args:
pid (obj or dict): GenInput class or dictionary containing all of the input information for
the generation. See BOWIE documentation and example notebooks for usage of
this class.
"""
# check if pid is dicionary or GenInput class
# if GenInput, change to dictionary
if isinstance(pid, GenInput):
pid = pid.return_dict()
begin_time = time.time()
WORKING_DIRECTORY = '.'
if 'WORKING_DIRECTORY' not in pid['general'].keys():
pid['general']['WORKING_DIRECTORY'] = WORKING_DIRECTORY
# Generate the contour data.
running_process = GenProcess(**{**pid, **pid['generate_info']})
running_process.set_parameters()
running_process.run_snr()
# Read out
file_out = FileReadOut(running_process.xvals, running_process.yvals,
running_process.final_dict,
**{**pid['general'], **pid['generate_info'], **pid['output_info']})
print('outputing file:', pid['general']['WORKING_DIRECTORY'] + '/'
+ pid['output_info']['output_file_name'])
getattr(file_out, file_out.output_file_type + '_read_out')()
print(time.time()-begin_time)
return | [
"def",
"generate_contour_data",
"(",
"pid",
")",
":",
"# check if pid is dicionary or GenInput class",
"# if GenInput, change to dictionary",
"if",
"isinstance",
"(",
"pid",
",",
"GenInput",
")",
":",
"pid",
"=",
"pid",
".",
"return_dict",
"(",
")",
"begin_time",
"="... | Main function for this program.
This will read in sensitivity_curves and binary parameters; calculate snrs
with a matched filtering approach; and then read the contour data out to a file.
Args:
pid (obj or dict): GenInput class or dictionary containing all of the input information for
the generation. See BOWIE documentation and example notebooks for usage of
this class. | [
"Main",
"function",
"for",
"this",
"program",
"."
] | train | https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/snr_calculator_folder/gwsnrcalc/generate_contour_data.py#L32-L71 |
jjmontesl/python-clementine-remote | clementineremote/clementine.py | ClementineRemote.send_message | def send_message(self, msg):
"""
Internal method used to send messages through Clementine remote network protocol.
"""
if self.socket is not None:
msg.version = self.PROTOCOL_VERSION
serialized = msg.SerializeToString()
data = struct.pack(">I", len(serialized)) + serialized
#print("Sending message: %s" % msg)
try:
self.socket.send(data)
except Exception as e:
#self.state = "Disconnected"
pass | python | def send_message(self, msg):
"""
Internal method used to send messages through Clementine remote network protocol.
"""
if self.socket is not None:
msg.version = self.PROTOCOL_VERSION
serialized = msg.SerializeToString()
data = struct.pack(">I", len(serialized)) + serialized
#print("Sending message: %s" % msg)
try:
self.socket.send(data)
except Exception as e:
#self.state = "Disconnected"
pass | [
"def",
"send_message",
"(",
"self",
",",
"msg",
")",
":",
"if",
"self",
".",
"socket",
"is",
"not",
"None",
":",
"msg",
".",
"version",
"=",
"self",
".",
"PROTOCOL_VERSION",
"serialized",
"=",
"msg",
".",
"SerializeToString",
"(",
")",
"data",
"=",
"st... | Internal method used to send messages through Clementine remote network protocol. | [
"Internal",
"method",
"used",
"to",
"send",
"messages",
"through",
"Clementine",
"remote",
"network",
"protocol",
"."
] | train | https://github.com/jjmontesl/python-clementine-remote/blob/af5198f8bb56a4845f4e081fd8a553f935c94cde/clementineremote/clementine.py#L103-L119 |
jjmontesl/python-clementine-remote | clementineremote/clementine.py | ClementineRemote._connect | def _connect(self):
"""
Connects to the server defined in the constructor.
"""
self.first_data_sent_complete = False
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((self.host, self.port))
msg = cr.Message()
msg.type = cr.CONNECT
msg.request_connect.auth_code = self.auth_code or 0
msg.request_connect.send_playlist_songs = False
msg.request_connect.downloader = False
self.send_message(msg) | python | def _connect(self):
"""
Connects to the server defined in the constructor.
"""
self.first_data_sent_complete = False
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((self.host, self.port))
msg = cr.Message()
msg.type = cr.CONNECT
msg.request_connect.auth_code = self.auth_code or 0
msg.request_connect.send_playlist_songs = False
msg.request_connect.downloader = False
self.send_message(msg) | [
"def",
"_connect",
"(",
"self",
")",
":",
"self",
".",
"first_data_sent_complete",
"=",
"False",
"self",
".",
"socket",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"self",
".",
"socket",
".",
"conn... | Connects to the server defined in the constructor. | [
"Connects",
"to",
"the",
"server",
"defined",
"in",
"the",
"constructor",
"."
] | train | https://github.com/jjmontesl/python-clementine-remote/blob/af5198f8bb56a4845f4e081fd8a553f935c94cde/clementineremote/clementine.py#L122-L137 |
jjmontesl/python-clementine-remote | clementineremote/clementine.py | ClementineRemote.play | def play(self):
"""
Sends a "play" command to the player.
"""
msg = cr.Message()
msg.type = cr.PLAY
self.send_message(msg) | python | def play(self):
"""
Sends a "play" command to the player.
"""
msg = cr.Message()
msg.type = cr.PLAY
self.send_message(msg) | [
"def",
"play",
"(",
"self",
")",
":",
"msg",
"=",
"cr",
".",
"Message",
"(",
")",
"msg",
".",
"type",
"=",
"cr",
".",
"PLAY",
"self",
".",
"send_message",
"(",
"msg",
")"
] | Sends a "play" command to the player. | [
"Sends",
"a",
"play",
"command",
"to",
"the",
"player",
"."
] | train | https://github.com/jjmontesl/python-clementine-remote/blob/af5198f8bb56a4845f4e081fd8a553f935c94cde/clementineremote/clementine.py#L147-L153 |
jjmontesl/python-clementine-remote | clementineremote/clementine.py | ClementineRemote.pause | def pause(self):
"""
Sends a "play" command to the player.
"""
msg = cr.Message()
msg.type = cr.PAUSE
self.send_message(msg) | python | def pause(self):
"""
Sends a "play" command to the player.
"""
msg = cr.Message()
msg.type = cr.PAUSE
self.send_message(msg) | [
"def",
"pause",
"(",
"self",
")",
":",
"msg",
"=",
"cr",
".",
"Message",
"(",
")",
"msg",
".",
"type",
"=",
"cr",
".",
"PAUSE",
"self",
".",
"send_message",
"(",
"msg",
")"
] | Sends a "play" command to the player. | [
"Sends",
"a",
"play",
"command",
"to",
"the",
"player",
"."
] | train | https://github.com/jjmontesl/python-clementine-remote/blob/af5198f8bb56a4845f4e081fd8a553f935c94cde/clementineremote/clementine.py#L155-L161 |
jjmontesl/python-clementine-remote | clementineremote/clementine.py | ClementineRemote.stop | def stop(self):
"""
Sends a "play" command to the player.
"""
msg = cr.Message()
msg.type = cr.STOP
self.send_message(msg) | python | def stop(self):
"""
Sends a "play" command to the player.
"""
msg = cr.Message()
msg.type = cr.STOP
self.send_message(msg) | [
"def",
"stop",
"(",
"self",
")",
":",
"msg",
"=",
"cr",
".",
"Message",
"(",
")",
"msg",
".",
"type",
"=",
"cr",
".",
"STOP",
"self",
".",
"send_message",
"(",
"msg",
")"
] | Sends a "play" command to the player. | [
"Sends",
"a",
"play",
"command",
"to",
"the",
"player",
"."
] | train | https://github.com/jjmontesl/python-clementine-remote/blob/af5198f8bb56a4845f4e081fd8a553f935c94cde/clementineremote/clementine.py#L163-L169 |
jjmontesl/python-clementine-remote | clementineremote/clementine.py | ClementineRemote.playpause | def playpause(self):
"""
Sends a "playpause" command to the player.
"""
msg = cr.Message()
msg.type = cr.PLAYPAUSE
self.send_message(msg) | python | def playpause(self):
"""
Sends a "playpause" command to the player.
"""
msg = cr.Message()
msg.type = cr.PLAYPAUSE
self.send_message(msg) | [
"def",
"playpause",
"(",
"self",
")",
":",
"msg",
"=",
"cr",
".",
"Message",
"(",
")",
"msg",
".",
"type",
"=",
"cr",
".",
"PLAYPAUSE",
"self",
".",
"send_message",
"(",
"msg",
")"
] | Sends a "playpause" command to the player. | [
"Sends",
"a",
"playpause",
"command",
"to",
"the",
"player",
"."
] | train | https://github.com/jjmontesl/python-clementine-remote/blob/af5198f8bb56a4845f4e081fd8a553f935c94cde/clementineremote/clementine.py#L171-L177 |
jjmontesl/python-clementine-remote | clementineremote/clementine.py | ClementineRemote.next | def next(self):
"""
Sends a "next" command to the player.
"""
msg = cr.Message()
msg.type = cr.NEXT
self.send_message(msg) | python | def next(self):
"""
Sends a "next" command to the player.
"""
msg = cr.Message()
msg.type = cr.NEXT
self.send_message(msg) | [
"def",
"next",
"(",
"self",
")",
":",
"msg",
"=",
"cr",
".",
"Message",
"(",
")",
"msg",
".",
"type",
"=",
"cr",
".",
"NEXT",
"self",
".",
"send_message",
"(",
"msg",
")"
] | Sends a "next" command to the player. | [
"Sends",
"a",
"next",
"command",
"to",
"the",
"player",
"."
] | train | https://github.com/jjmontesl/python-clementine-remote/blob/af5198f8bb56a4845f4e081fd8a553f935c94cde/clementineremote/clementine.py#L179-L185 |
jjmontesl/python-clementine-remote | clementineremote/clementine.py | ClementineRemote.previous | def previous(self):
"""
Sends a "previous" command to the player.
"""
msg = cr.Message()
msg.type = cr.PREVIOUS
self.send_message(msg) | python | def previous(self):
"""
Sends a "previous" command to the player.
"""
msg = cr.Message()
msg.type = cr.PREVIOUS
self.send_message(msg) | [
"def",
"previous",
"(",
"self",
")",
":",
"msg",
"=",
"cr",
".",
"Message",
"(",
")",
"msg",
".",
"type",
"=",
"cr",
".",
"PREVIOUS",
"self",
".",
"send_message",
"(",
"msg",
")"
] | Sends a "previous" command to the player. | [
"Sends",
"a",
"previous",
"command",
"to",
"the",
"player",
"."
] | train | https://github.com/jjmontesl/python-clementine-remote/blob/af5198f8bb56a4845f4e081fd8a553f935c94cde/clementineremote/clementine.py#L187-L193 |
jjmontesl/python-clementine-remote | clementineremote/clementine.py | ClementineRemote.set_volume | def set_volume(self, volume):
"""
Sets player volume (note, this does not change host computer main volume).
"""
msg = cr.Message()
msg.type = cr.SET_VOLUME
msg.request_set_volume.volume = int(volume)
self.send_message(msg) | python | def set_volume(self, volume):
"""
Sets player volume (note, this does not change host computer main volume).
"""
msg = cr.Message()
msg.type = cr.SET_VOLUME
msg.request_set_volume.volume = int(volume)
self.send_message(msg) | [
"def",
"set_volume",
"(",
"self",
",",
"volume",
")",
":",
"msg",
"=",
"cr",
".",
"Message",
"(",
")",
"msg",
".",
"type",
"=",
"cr",
".",
"SET_VOLUME",
"msg",
".",
"request_set_volume",
".",
"volume",
"=",
"int",
"(",
"volume",
")",
"self",
".",
"... | Sets player volume (note, this does not change host computer main volume). | [
"Sets",
"player",
"volume",
"(",
"note",
"this",
"does",
"not",
"change",
"host",
"computer",
"main",
"volume",
")",
"."
] | train | https://github.com/jjmontesl/python-clementine-remote/blob/af5198f8bb56a4845f4e081fd8a553f935c94cde/clementineremote/clementine.py#L195-L202 |
limix/limix-core | limix_core/covar/cov2kronSumLR.py | Cov2KronSumLR.solve_t | def solve_t(self, Mt):
"""
Mt is dim_r x dim_c x d tensor
"""
if len(Mt.shape)==2: _Mt = Mt[:, :, sp.newaxis]
else: _Mt = Mt
M = _Mt.transpose([0,2,1])
MLc = sp.tensordot(M, self.Lc().T, (2,0))
MLcLc = sp.tensordot(MLc, self.Lc(), (2,0))
WrMLcWc = sp.tensordot(sp.tensordot(self.Wr(), MLc, (1,0)), self.Wc().T, (2,0))
DWrMLcWc = sp.tensordot(self.D()[:,sp.newaxis,:]*WrMLcWc, self.Wc(), (2,0))
WrDWrMLcWcLc = sp.tensordot(self.Wr().T, sp.tensordot(DWrMLcWc, self.Lc(), (2,0)), (1,0))
RV = (MLcLc - WrDWrMLcWcLc).transpose([0,2,1])
if len(Mt.shape)==2: RV = RV[:, :, 0]
return RV | python | def solve_t(self, Mt):
"""
Mt is dim_r x dim_c x d tensor
"""
if len(Mt.shape)==2: _Mt = Mt[:, :, sp.newaxis]
else: _Mt = Mt
M = _Mt.transpose([0,2,1])
MLc = sp.tensordot(M, self.Lc().T, (2,0))
MLcLc = sp.tensordot(MLc, self.Lc(), (2,0))
WrMLcWc = sp.tensordot(sp.tensordot(self.Wr(), MLc, (1,0)), self.Wc().T, (2,0))
DWrMLcWc = sp.tensordot(self.D()[:,sp.newaxis,:]*WrMLcWc, self.Wc(), (2,0))
WrDWrMLcWcLc = sp.tensordot(self.Wr().T, sp.tensordot(DWrMLcWc, self.Lc(), (2,0)), (1,0))
RV = (MLcLc - WrDWrMLcWcLc).transpose([0,2,1])
if len(Mt.shape)==2: RV = RV[:, :, 0]
return RV | [
"def",
"solve_t",
"(",
"self",
",",
"Mt",
")",
":",
"if",
"len",
"(",
"Mt",
".",
"shape",
")",
"==",
"2",
":",
"_Mt",
"=",
"Mt",
"[",
":",
",",
":",
",",
"sp",
".",
"newaxis",
"]",
"else",
":",
"_Mt",
"=",
"Mt",
"M",
"=",
"_Mt",
".",
"tra... | Mt is dim_r x dim_c x d tensor | [
"Mt",
"is",
"dim_r",
"x",
"dim_c",
"x",
"d",
"tensor"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/covar/cov2kronSumLR.py#L294-L308 |
garyp/sifter | sifter/grammar/grammar.py | p_commands_list | def p_commands_list(p):
"""commands : commands command"""
p[0] = p[1]
# section 3.2: REQUIRE command must come before any other commands
if p[2].RULE_IDENTIFIER == 'REQUIRE':
if any(command.RULE_IDENTIFIER != 'REQUIRE'
for command in p[0].commands):
print("REQUIRE command on line %d must come before any "
"other non-REQUIRE commands" % p.lineno(2))
raise SyntaxError
# section 3.1: ELSIF and ELSE must follow IF or another ELSIF
elif p[2].RULE_IDENTIFIER in ('ELSIF', 'ELSE'):
if p[0].commands[-1].RULE_IDENTIFIER not in ('IF', 'ELSIF'):
print("ELSIF/ELSE command on line %d must follow an IF/ELSIF "
"command" % p.lineno(2))
raise SyntaxError
p[0].commands.append(p[2]) | python | def p_commands_list(p):
"""commands : commands command"""
p[0] = p[1]
# section 3.2: REQUIRE command must come before any other commands
if p[2].RULE_IDENTIFIER == 'REQUIRE':
if any(command.RULE_IDENTIFIER != 'REQUIRE'
for command in p[0].commands):
print("REQUIRE command on line %d must come before any "
"other non-REQUIRE commands" % p.lineno(2))
raise SyntaxError
# section 3.1: ELSIF and ELSE must follow IF or another ELSIF
elif p[2].RULE_IDENTIFIER in ('ELSIF', 'ELSE'):
if p[0].commands[-1].RULE_IDENTIFIER not in ('IF', 'ELSIF'):
print("ELSIF/ELSE command on line %d must follow an IF/ELSIF "
"command" % p.lineno(2))
raise SyntaxError
p[0].commands.append(p[2]) | [
"def",
"p_commands_list",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"# section 3.2: REQUIRE command must come before any other commands",
"if",
"p",
"[",
"2",
"]",
".",
"RULE_IDENTIFIER",
"==",
"'REQUIRE'",
":",
"if",
"any",
"(",
"comm... | commands : commands command | [
"commands",
":",
"commands",
"command"
] | train | https://github.com/garyp/sifter/blob/9c472af76853c1196387141e017114d282637474/sifter/grammar/grammar.py#L17-L36 |
garyp/sifter | sifter/grammar/grammar.py | p_command | def p_command(p):
"""command : IDENTIFIER arguments ';'
| IDENTIFIER arguments block"""
#print("COMMAND:", p[1], p[2], p[3])
tests = p[2].get('tests')
block = None
if p[3] != ';': block = p[3]
handler = sifter.handler.get('command', p[1])
if handler is None:
print("No handler registered for command '%s' on line %d" %
(p[1], p.lineno(1)))
raise SyntaxError
p[0] = handler(arguments=p[2]['args'], tests=tests, block=block) | python | def p_command(p):
"""command : IDENTIFIER arguments ';'
| IDENTIFIER arguments block"""
#print("COMMAND:", p[1], p[2], p[3])
tests = p[2].get('tests')
block = None
if p[3] != ';': block = p[3]
handler = sifter.handler.get('command', p[1])
if handler is None:
print("No handler registered for command '%s' on line %d" %
(p[1], p.lineno(1)))
raise SyntaxError
p[0] = handler(arguments=p[2]['args'], tests=tests, block=block) | [
"def",
"p_command",
"(",
"p",
")",
":",
"#print(\"COMMAND:\", p[1], p[2], p[3])",
"tests",
"=",
"p",
"[",
"2",
"]",
".",
"get",
"(",
"'tests'",
")",
"block",
"=",
"None",
"if",
"p",
"[",
"3",
"]",
"!=",
"';'",
":",
"block",
"=",
"p",
"[",
"3",
"]",... | command : IDENTIFIER arguments ';'
| IDENTIFIER arguments block | [
"command",
":",
"IDENTIFIER",
"arguments",
";",
"|",
"IDENTIFIER",
"arguments",
"block"
] | train | https://github.com/garyp/sifter/blob/9c472af76853c1196387141e017114d282637474/sifter/grammar/grammar.py#L42-L54 |
garyp/sifter | sifter/grammar/grammar.py | p_block | def p_block(p):
"""block : '{' commands '}' """
# section 3.2: REQUIRE command must come before any other commands,
# which means it can't be in the block of another command
if any(command.RULE_IDENTIFIER == 'REQUIRE'
for command in p[2].commands):
print("REQUIRE command not allowed inside of a block (line %d)" %
(p.lineno(2)))
raise SyntaxError
p[0] = p[2] | python | def p_block(p):
"""block : '{' commands '}' """
# section 3.2: REQUIRE command must come before any other commands,
# which means it can't be in the block of another command
if any(command.RULE_IDENTIFIER == 'REQUIRE'
for command in p[2].commands):
print("REQUIRE command not allowed inside of a block (line %d)" %
(p.lineno(2)))
raise SyntaxError
p[0] = p[2] | [
"def",
"p_block",
"(",
"p",
")",
":",
"# section 3.2: REQUIRE command must come before any other commands,",
"# which means it can't be in the block of another command",
"if",
"any",
"(",
"command",
".",
"RULE_IDENTIFIER",
"==",
"'REQUIRE'",
"for",
"command",
"in",
"p",
"[",
... | block : '{' commands '}' | [
"block",
":",
"{",
"commands",
"}"
] | train | https://github.com/garyp/sifter/blob/9c472af76853c1196387141e017114d282637474/sifter/grammar/grammar.py#L63-L72 |
garyp/sifter | sifter/grammar/grammar.py | p_arguments | def p_arguments(p):
"""arguments : argumentlist
| argumentlist test
| argumentlist '(' testlist ')'"""
p[0] = { 'args' : p[1], }
if len(p) > 2:
if p[2] == '(':
p[0]['tests'] = p[3]
else:
p[0]['tests'] = [ p[2] ] | python | def p_arguments(p):
"""arguments : argumentlist
| argumentlist test
| argumentlist '(' testlist ')'"""
p[0] = { 'args' : p[1], }
if len(p) > 2:
if p[2] == '(':
p[0]['tests'] = p[3]
else:
p[0]['tests'] = [ p[2] ] | [
"def",
"p_arguments",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"{",
"'args'",
":",
"p",
"[",
"1",
"]",
",",
"}",
"if",
"len",
"(",
"p",
")",
">",
"2",
":",
"if",
"p",
"[",
"2",
"]",
"==",
"'('",
":",
"p",
"[",
"0",
"]",
"[",
"'tes... | arguments : argumentlist
| argumentlist test
| argumentlist '(' testlist ') | [
"arguments",
":",
"argumentlist",
"|",
"argumentlist",
"test",
"|",
"argumentlist",
"(",
"testlist",
")"
] | train | https://github.com/garyp/sifter/blob/9c472af76853c1196387141e017114d282637474/sifter/grammar/grammar.py#L80-L89 |
inveniosoftware/invenio-config | invenio_config/module.py | InvenioConfigModule.init_app | def init_app(self, app):
"""Initialize Flask application."""
if self.module:
app.config.from_object(self.module) | python | def init_app(self, app):
"""Initialize Flask application."""
if self.module:
app.config.from_object(self.module) | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"if",
"self",
".",
"module",
":",
"app",
".",
"config",
".",
"from_object",
"(",
"self",
".",
"module",
")"
] | Initialize Flask application. | [
"Initialize",
"Flask",
"application",
"."
] | train | https://github.com/inveniosoftware/invenio-config/blob/8d1e63ac045cd9c58a3399c6b58845e6daa06102/invenio_config/module.py#L26-L29 |
stbraun/fuzzing | features/steps/ft_fuzzer.py | step_impl03 | def step_impl03(context):
"""Check assertions.
:param context: test context.
"""
assert len(context.buf) == len(context.fuzzed_buf)
count = number_of_modified_bytes(context.buf, context.fuzzed_buf)
assert count < 3
assert count >= 0 | python | def step_impl03(context):
"""Check assertions.
:param context: test context.
"""
assert len(context.buf) == len(context.fuzzed_buf)
count = number_of_modified_bytes(context.buf, context.fuzzed_buf)
assert count < 3
assert count >= 0 | [
"def",
"step_impl03",
"(",
"context",
")",
":",
"assert",
"len",
"(",
"context",
".",
"buf",
")",
"==",
"len",
"(",
"context",
".",
"fuzzed_buf",
")",
"count",
"=",
"number_of_modified_bytes",
"(",
"context",
".",
"buf",
",",
"context",
".",
"fuzzed_buf",
... | Check assertions.
:param context: test context. | [
"Check",
"assertions",
"."
] | train | https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/features/steps/ft_fuzzer.py#L28-L36 |
stbraun/fuzzing | features/steps/ft_fuzzer.py | step_impl | def step_impl(context, max_modified):
"""Check assertions.
:param max_modified: maximum expected number of modifications.
:param context: test context.
"""
assert len(context.buf) == len(context.fuzzed_buf)
count = number_of_modified_bytes(context.buf, context.fuzzed_buf)
assert count >= 0
assert count <= max_modified | python | def step_impl(context, max_modified):
"""Check assertions.
:param max_modified: maximum expected number of modifications.
:param context: test context.
"""
assert len(context.buf) == len(context.fuzzed_buf)
count = number_of_modified_bytes(context.buf, context.fuzzed_buf)
assert count >= 0
assert count <= max_modified | [
"def",
"step_impl",
"(",
"context",
",",
"max_modified",
")",
":",
"assert",
"len",
"(",
"context",
".",
"buf",
")",
"==",
"len",
"(",
"context",
".",
"fuzzed_buf",
")",
"count",
"=",
"number_of_modified_bytes",
"(",
"context",
".",
"buf",
",",
"context",
... | Check assertions.
:param max_modified: maximum expected number of modifications.
:param context: test context. | [
"Check",
"assertions",
"."
] | train | https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/features/steps/ft_fuzzer.py#L50-L59 |
stbraun/fuzzing | features/steps/ft_fuzzer.py | step_impl06 | def step_impl06(context, count):
"""Execute fuzzer.
:param count: number of string variants to generate.
:param context: test context.
"""
fuzz_factor = 11
context.fuzzed_string_list = fuzz_string(context.seed, count, fuzz_factor) | python | def step_impl06(context, count):
"""Execute fuzzer.
:param count: number of string variants to generate.
:param context: test context.
"""
fuzz_factor = 11
context.fuzzed_string_list = fuzz_string(context.seed, count, fuzz_factor) | [
"def",
"step_impl06",
"(",
"context",
",",
"count",
")",
":",
"fuzz_factor",
"=",
"11",
"context",
".",
"fuzzed_string_list",
"=",
"fuzz_string",
"(",
"context",
".",
"seed",
",",
"count",
",",
"fuzz_factor",
")"
] | Execute fuzzer.
:param count: number of string variants to generate.
:param context: test context. | [
"Execute",
"fuzzer",
"."
] | train | https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/features/steps/ft_fuzzer.py#L72-L79 |
stbraun/fuzzing | features/steps/ft_fuzzer.py | step_impl07 | def step_impl07(context, len_list):
"""Check assertions.
:param len_list: expected number of variants.
:param context: test context.
"""
assert len(context.fuzzed_string_list) == len_list
for fuzzed_string in context.fuzzed_string_list:
assert len(context.seed) == len(fuzzed_string)
count = number_of_modified_bytes(context.seed, fuzzed_string)
assert count >= 0 | python | def step_impl07(context, len_list):
"""Check assertions.
:param len_list: expected number of variants.
:param context: test context.
"""
assert len(context.fuzzed_string_list) == len_list
for fuzzed_string in context.fuzzed_string_list:
assert len(context.seed) == len(fuzzed_string)
count = number_of_modified_bytes(context.seed, fuzzed_string)
assert count >= 0 | [
"def",
"step_impl07",
"(",
"context",
",",
"len_list",
")",
":",
"assert",
"len",
"(",
"context",
".",
"fuzzed_string_list",
")",
"==",
"len_list",
"for",
"fuzzed_string",
"in",
"context",
".",
"fuzzed_string_list",
":",
"assert",
"len",
"(",
"context",
".",
... | Check assertions.
:param len_list: expected number of variants.
:param context: test context. | [
"Check",
"assertions",
"."
] | train | https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/features/steps/ft_fuzzer.py#L83-L93 |
stbraun/fuzzing | features/steps/ft_fuzzer.py | step_impl08 | def step_impl08(context):
"""Create file list.
:param context: test context.
"""
assert context.table, "ENSURE: table is provided."
context.file_list = [row['file_path'] for row in context.table.rows] | python | def step_impl08(context):
"""Create file list.
:param context: test context.
"""
assert context.table, "ENSURE: table is provided."
context.file_list = [row['file_path'] for row in context.table.rows] | [
"def",
"step_impl08",
"(",
"context",
")",
":",
"assert",
"context",
".",
"table",
",",
"\"ENSURE: table is provided.\"",
"context",
".",
"file_list",
"=",
"[",
"row",
"[",
"'file_path'",
"]",
"for",
"row",
"in",
"context",
".",
"table",
".",
"rows",
"]"
] | Create file list.
:param context: test context. | [
"Create",
"file",
"list",
"."
] | train | https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/features/steps/ft_fuzzer.py#L100-L106 |
stbraun/fuzzing | features/steps/ft_fuzzer.py | step_impl09 | def step_impl09(context):
"""Create application list.
:param context: test context.
"""
assert context.table, "ENSURE: table is provided."
context.app_list = [row['application'] for row in context.table.rows] | python | def step_impl09(context):
"""Create application list.
:param context: test context.
"""
assert context.table, "ENSURE: table is provided."
context.app_list = [row['application'] for row in context.table.rows] | [
"def",
"step_impl09",
"(",
"context",
")",
":",
"assert",
"context",
".",
"table",
",",
"\"ENSURE: table is provided.\"",
"context",
".",
"app_list",
"=",
"[",
"row",
"[",
"'application'",
"]",
"for",
"row",
"in",
"context",
".",
"table",
".",
"rows",
"]"
] | Create application list.
:param context: test context. | [
"Create",
"application",
"list",
"."
] | train | https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/features/steps/ft_fuzzer.py#L110-L116 |
stbraun/fuzzing | features/steps/ft_fuzzer.py | step_impl10 | def step_impl10(context):
"""Create application list.
:param context: test context.
"""
assert context.app_list and len(
context.app_list) > 0, "ENSURE: app list is provided."
assert context.file_list and len(
context.file_list) > 0, "ENSURE: file list is provided."
context.fuzz_executor = FuzzExecutor(context.app_list, context.file_list)
assert context.fuzz_executor, "VERIFY: fuzz executor created." | python | def step_impl10(context):
"""Create application list.
:param context: test context.
"""
assert context.app_list and len(
context.app_list) > 0, "ENSURE: app list is provided."
assert context.file_list and len(
context.file_list) > 0, "ENSURE: file list is provided."
context.fuzz_executor = FuzzExecutor(context.app_list, context.file_list)
assert context.fuzz_executor, "VERIFY: fuzz executor created." | [
"def",
"step_impl10",
"(",
"context",
")",
":",
"assert",
"context",
".",
"app_list",
"and",
"len",
"(",
"context",
".",
"app_list",
")",
">",
"0",
",",
"\"ENSURE: app list is provided.\"",
"assert",
"context",
".",
"file_list",
"and",
"len",
"(",
"context",
... | Create application list.
:param context: test context. | [
"Create",
"application",
"list",
"."
] | train | https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/features/steps/ft_fuzzer.py#L120-L130 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.