text stringlengths 4 1.02M | meta dict |
|---|---|
import unittest
import tempfile
from AlphaLineupPuzzle import lineup_puzzle
from AlphaLineupPuzzle.preprocessing import game_converter
class TestGameConverter(unittest.TestCase):
def setUp(self):
self.save = 'tests/data/save.json'
self.gs = lineup_puzzle.GameState.create()
def test_to_file(self):
temp_fn = tempfile.mktemp('.json', 'AlphaLineupPuzzle')
self.gs.move(0, (1, 2))
game_converter.Save.dump(self.gs, temp_fn)
def test_convert_game(self):
for state, action in game_converter.convert_game(self.save):
pass
def test_convert_to_hdf5(self):
output = 'tests/data/save.hdf5'
game_converter.to_hdf5((self.save,), output)
states, actions = game_converter.from_hdf5(output)
def test_stats_saves(self):
game_converter.stats_saves((self.save,))
| {
"content_hash": "7059cdbbdcca8b4d91a1646d666ee4e0",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 68,
"avg_line_length": 29.82758620689655,
"alnum_prop": 0.6682080924855491,
"repo_name": "zhaipro/AlphaLineupPuzzle",
"id": "808117df1d406b270e9ab8b1a3cad16e7547a18f",
"size": "881",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "tests/test_game_converter.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "31331"
}
],
"symlink_target": ""
} |
from msrest.serialization import Model
class BasicDependency(Model):
"""
Deployment dependency information.
:param id: Gets or sets the ID of the dependency.
:type id: str
:param resource_type: Gets or sets the dependency resource type.
:type resource_type: str
:param resource_name: Gets or sets the dependency resource name.
:type resource_name: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'resource_type': {'key': 'resourceType', 'type': 'str'},
'resource_name': {'key': 'resourceName', 'type': 'str'},
}
def __init__(self, id=None, resource_type=None, resource_name=None):
self.id = id
self.resource_type = resource_type
self.resource_name = resource_name
| {
"content_hash": "a58c0e40f17238cfd3a45a94430e0727",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 72,
"avg_line_length": 31.24,
"alnum_prop": 0.6209987195902689,
"repo_name": "BurtBiel/azure-cli",
"id": "3d7e750a316d3270d985b3a1948b3a61dbe14e8e",
"size": "1468",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "src/command_modules/azure-cli-network/azure/cli/command_modules/network/mgmt_lb/lib/models/basic_dependency.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "429"
},
{
"name": "Python",
"bytes": "2108820"
},
{
"name": "Shell",
"bytes": "3300"
}
],
"symlink_target": ""
} |
"""
Add FLAGS_GOLD to detection catalog.
Spencer Everett
"""
import sys
import fitsio
from astropy.table import Table, join
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument(
'detfile',
type=str,
help='Detection catalog filename'
)
parser.add_argument(
'matchfile',
type=str,
help='Matched catalog filename'
)
parser.add_argument(
'--match_type',
default='default',
choices=['default', 'mof_only', 'sof_only'],
type=str,
help='Set the type of MatchedCatalog created (NB: not the same as ngmix_type!)'
)
parser.add_argument(
'--ignore_ext',
action='store_true',
default=False,
help='Set to skip saving the extinction factors to the detection catalog'
)
parser.add_argument(
'--vb',
action='store_true',
default=False,
help='Set to print out more information'
)
def main():
args = parser.parse_args()
det_file = args.detfile
match_file = args.matchfile
match_type = args.match_type
ignore_ext = args.ignore_ext
vb = args.vb
if vb is True:
print('Loading catalogs...')
det_cat = Table.read(det_file)
# Can add more later
gold_cols = ['bal_id']
if match_type == 'default':
gold_cols += ['meas_FLAGS_GOLD', 'meas_EXTENDED_CLASS_MOF', 'meas_EXTENDED_CLASS_SOF']
elif match_type == 'mof_only':
gold_cols += ['meas_FLAGS_GOLD_MOF_ONLY', 'meas_EXTENDED_CLASS_MOF']
elif match_type == 'sof_only':
gold_cols += ['meas_FLAGS_GOLD_SOF_ONLY', 'meas_EXTENDED_CLASS_SOF']
else:
raise ValueError('Not a valid match_type!')
if ignore_ext is False :
gold_cols += ['ext_fact', 'ext_mag']
match_cat = Table(fitsio.read(match_file, columns=gold_cols))
if vb is True:
print('Joining catalogs...')
new_det_cat = join(det_cat, match_cat, join_type='left', keys='bal_id')
if vb is True:
print('Writing new detection catalog...')
outfile = det_file.replace('.fits', '_gold_added.fits')
new_det_cat.write(outfile)
if vb is True:
print('Done!')
return 0
if __name__ == "__main__":
sys.exit(main())
| {
"content_hash": "09dd833fc6d518de45790d907acc1e22",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 94,
"avg_line_length": 24.280898876404493,
"alnum_prop": 0.6260990282276724,
"repo_name": "sweverett/Balrog-GalSim",
"id": "e0ff73a1c594e1e4cdcd6d0575eba932253f5986",
"size": "2183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/det-add-gold.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "3133"
},
{
"name": "Python",
"bytes": "687989"
},
{
"name": "Shell",
"bytes": "8409"
}
],
"symlink_target": ""
} |
import unittest
from maskgen.algorithms.retinex import *
from tests.test_support import TestSupport
import os
from maskgen.image_wrap import ImageWrapper, openImageFile
import numpy as np
#import colorcorrect.algorithm
from maskgen.image_wrap import ImageWrapper
class TestRetinex(TestSupport):
def test_retinex(self):
img = openImageFile(self.locateFile('tests/images/test_project4.jpg'))
for f in [MultiScaleResinex([15,80,125],
G=30,
b=-6,
alpha=125.0,
beta=1.0,
colorBalance=(0.01,0.99)),
MultiScaleResinexLab([15,80,125],
G=30,
b=-6,
alpha=125.0,
beta=1.0,
colorBalance=(0.01, 0.99)),
MultiScaleResinexChromaPerservation([15,80,125],
G=30,
b=-6,
alpha=125.0,
beta=1.0,
colorBalance=(0.01, 0.99))
]:
res = f(img.to_array())
self.assertTrue(np.mean(res) > np.mean(img.to_array()))
#ImageWrapper(res).save('cr_{}_ret.png'.format(f.__class__.__name__))
if __name__ == '__main__':
unittest.main()
| {
"content_hash": "c56a1054ac29ae5792e98fb40f7187f5",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 85,
"avg_line_length": 28.80952380952381,
"alnum_prop": 0.5421487603305785,
"repo_name": "rwgdrummer/maskgen",
"id": "7facce05620e49c93ea9773e23b7a4708accc2c0",
"size": "1210",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/algorithms/test_retinex.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "544"
},
{
"name": "Dockerfile",
"bytes": "4825"
},
{
"name": "NSIS",
"bytes": "4907"
},
{
"name": "Python",
"bytes": "2768871"
},
{
"name": "Shell",
"bytes": "8086"
}
],
"symlink_target": ""
} |
import os
"""
the get_password function tries to find a file called
<arg>_password.txt containing the txt.
By default it looks in application root folder parent.
get_password('db') - > ../db_password.txt
Import it if you want to pass some password to your configs.
"""
# from quokka.utils.settings import get_password
"""
DB for localhost
"""
MONGODB_DB = "quokka"
MONGODB_HOST = '192.168.5.82'
MONGODB_PORT = 27017
MONGODB_USERNAME = "qkkuser"
MONGODB_PASSWORD = "12345678"
"""
This should really be secret for security
use os.random, urandom or uuid4 to generate
in your shell
$ python -c "import uuid;print uuid.uuid4()"
then use the generated key
"""
SECRET_KEY = "S3cr3Tk3Y" # noqa
"""
Take a look at Flask-Cache documentation
"""
CACHE_TYPE = "simple"
"""
Not needed by flask, but those root folders are used
by FLask-Admin file manager
"""
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'mediafiles')
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
ROOT_DIR = os.path.abspath(os.path.join(PROJECT_ROOT, '..'))
# For starting with sample data
POPULATE_FILEPATH = os.path.join(
ROOT_DIR, 'etc', 'fixtures', 'initial_data.json'
)
"""
Files on MAP_STATIC_ROOT will be served from /static/
example: /static/favicon.ico will be served by site.com/favicon.ico
"""
MAP_STATIC_ROOT = ('/robots.txt', '/sitemap.xml', '/favicon.ico')
"""
If enabled admin will leave creation of repeated slugs
but will append a random int i.e: blog-post-2342342
"""
SMART_SLUG_ENABLED = False
"""
Blueprints are quokka-modules, you don't need to install
just develop or download and drop in your modules folder
by default it is in /modules, you can change if needed
"""
BLUEPRINTS_PATH = 'modules'
BLUEPRINTS_OBJECT_NAME = 'module'
"""
Default configuration for FLask-Admin instance
:name: - will be the page title
:url: - is the ending point
"""
ADMIN = {'name': 'Quokka admin', 'url': '/admin'}
"""
File admin can expose folders, you just need to have them
mapped in your server or in flask, see quooka.ext.views
"""
DEFAULT_EDITABLE_EXTENSIONS = (
'html', 'css', 'js', 'py', 'txt', 'md', 'cfg', 'coffee', 'html', 'json',
'xml', 'yaml', 'yml', 'HTML', 'CSS', 'JS', 'PY', 'TXT', 'MD', 'CFG',
'COFFEE', 'HTML', 'JSON', 'XML', 'YAML', 'YML'
)
FILE_ADMIN = [
{
"name": "Template files",
"category": "Files",
"path": os.path.join(PROJECT_ROOT, 'templates'),
"url": "/template_files/", # create nginx rule
"endpoint": "template_files",
"roles_accepted": ("admin", "editor"),
"editable_extensions": DEFAULT_EDITABLE_EXTENSIONS
},
{
"name": "Static files",
"category": "Files",
"path": STATIC_ROOT,
"url": "/static/", # create nginx rule
"endpoint": "static_files",
"roles_accepted": ("admin", "editor"),
"editable_extensions": DEFAULT_EDITABLE_EXTENSIONS
},
{
"name": "Media files",
"category": "Files",
"path": MEDIA_ROOT,
"url": "/mediafiles/", # Create nginx rule
"endpoint": "media_files",
"roles_accepted": ("admin", "editor"),
"editable_extensions": DEFAULT_EDITABLE_EXTENSIONS
}
]
"""
Activates Flask-Weasyprint extension
so that Posts can be rendered to PDF just by
changing the extension from .html to .pdf
please install Flask-Weasyprint in your python env
pip install flask-weasyprint
"""
ENABLE_TO_PDF = False
"""
Never change it here, use local_settings for this.
"""
MODE = 'production'
DEBUG = False
"""
Debug toolbar only works if installed
pip install flask-debugtoolbar
"""
DEBUG_TB_INTERCEPT_REDIRECTS = False
DEBUG_TB_PROFILER_ENABLED = True
DEBUG_TB_TEMPLATE_EDITOR_ENABLED = True
DEBUG_TB_PANELS = (
'flask_debugtoolbar.panels.versions.VersionDebugPanel',
'flask_debugtoolbar.panels.timer.TimerDebugPanel',
'flask_debugtoolbar.panels.headers.HeaderDebugPanel',
'flask_debugtoolbar.panels.request_vars.RequestVarsDebugPanel',
'flask_debugtoolbar.panels.template.TemplateDebugPanel',
'flask.ext.mongoengine.panels.MongoDebugPanel',
'flask_debugtoolbar.panels.logger.LoggingPanel',
'flask_debugtoolbar.panels.profiler.ProfilerDebugPanel',
'flask_debugtoolbar.panels.config_vars.ConfigVarsDebugPanel',
)
"""
By default DEBUG_TOOLBAR is disabled
do not change it here, do it in local_settings.py
DEBUG_TOOLBAR_ENABLED = True
"""
DEBUG_TOOLBAR_ENABLED = False
"""
Flask-Gravatar can take avatar urls in jinja templates
do: {{ current_user.email | gravatar }} or
{{ 'some@server.com' | gravatar(size=50) }}
"""
GRAVATAR = {
'size': 100,
'rating': 'g',
'default': 'retro',
'force_default': False,
'force_lower': False
}
"""
Emails go to shell until you configure this
http://pythonhosted.org/Flask-Mail/
MAIL_SERVER = 'smtp.gmail.com'
MAIL_PORT = 587
# MAIL_USE_SSL = True
MAIL_USE_TLS = True
MAIL_USERNAME = 'rochacbruno@gmail.com'
# Create a .email_password.txt in ../
MAIL_PASSWORD = get_password('email')
DEFAULT_MAIL_SENDER = None
"""
"""
Take a look at Flask-Security docs
http://pythonhosted.org/Flask-Security/configuration.html
"""
SECURITY_PASSWORD_HASH = 'pbkdf2_sha512' # noqa
SECURITY_URL_PREFIX = '/accounts'
SECURITY_PASSWORD_SALT = '6e95b1ed-a8c3-4da0-8bac-6fcb11c39ab4' # noqa
SECURITY_EMAIL_SENDER = 'reply@localhost'
SECURITY_REGISTERABLE = False
SECURITY_CHANGEABLE = True
SECURITY_RECOVERABLE = True
SECURITY_TRACKABLE = True
# Configurations below should be changes in local_settings
# when email system got setted up
SECURITY_SEND_REGISTER_EMAIL = False
SECURITY_LOGIN_WITHOUT_CONFIRMATION = True
SECURITY_SEND_PASSWORD_CHANGE_EMAIL = False
SECURITY_SEND_PASSWORD_RESET_NOTICE_EMAIL = False
"Recaptcha for user register form"
SECURITY_RECAPTCHA_ENABLED = False
# RECAPTCHA_DATA_ATTRS = {'theme': 'dark'}
# RECAPTCHA_PUBLIC_KEY = ''
# RECAPTCHA_PRIVATE_KEY = ''
"""
Internationalization for Flask-Admin
if want to use in your site home page, read babel docs.
"""
BABEL_LANGUAGES = ['en', 'pt-br']
BABEL_DEFAULT_LOCALE = 'en'
# WTForms
CSRF_ENABLED = True
"""
It is good to use uuid here
$ python -c "import uuid;print uuid.uuid4()"
"""
CSRF_SESSION_KEY = "somethingimpossibletoguess"
# configure logger in your local_settings
LOGGER_ENABLED = False
LOGGER_LEVEL = 'DEBUG'
LOGGER_FORMAT = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'
LOGGER_DATE_FORMAT = '%d.%m %H:%M:%S'
# media module
MEDIA_IMAGE_ALLOWED_EXTENSIONS = ('jpg', 'jpeg', 'png', 'tiff', 'gif', 'bmp')
MEDIA_AUDIO_ALLOWED_EXTENSIONS = ('mp3', 'wmv', 'ogg')
MEDIA_VIDEO_ALLOWED_EXTENSIONS = ('avi', 'mp4', 'mpeg')
MEDIA_FILE_ALLOWED_EXTENSIONS = ('pdf', 'txt', 'doc', 'docx', 'xls', 'xmlsx')
# default admin THEME
ADMIN_THEME = 'admin'
"""
https://bootswatch.com/2/ themes available:
amelia cerulean cosmo cyborg default flatly
journal readable simplex slate spacelab
spruce superhero united
"""
ADMIN_SWATCH = 'default'
ADMIN_ICONS = [
('post.create_view', 'pencil', 'Write'),
('post.index_view', 'th-list', 'Posts'),
('config.index_view', 'cog', 'Config'),
('user.index_view', 'user', 'Users'),
('image.index_view', 'picture', 'Images'),
('image.create_view', 'arrow-up', 'Upload'),
('channel.index_view', 'th-list', 'Channels')
]
# front end theme
DEFAULT_THEME = 'pure'
# default content extension for url buildind
CONTENT_EXTENSION = "html"
SENTRY_ENABLED = False
SENTRY_DSN = ""
# html or markdown
DEFAULT_TEXT_FORMAT = "html"
"Shortner urls configuration"
SHORTENER_ENABLED = False
"Note: if you enable shortener you have to define a SERVER_NAME"
# SERVER_NAME = 'localhost'
"Config shorter information"
SHORTENER_SETTINGS = {"name": "BitlyShortener",
"bitly_api_key": "R_7d84f09c68be4c749cac2a56ace2e73f",
"bitly_token":
"9964d1f9c8c8b4215f7690449f0980c4fe1a6906",
"bitly_login": "quokkabitly"}
| {
"content_hash": "6772fcd5a9566b87b72df07dc2cfd4c8",
"timestamp": "",
"source": "github",
"line_count": 291,
"max_line_length": 77,
"avg_line_length": 27.38487972508591,
"alnum_prop": 0.6837746266783787,
"repo_name": "SiryjVyiko/quokka",
"id": "b246f99a0b7a3286ae746e125f17cfddaaf0497e",
"size": "7985",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "quokka/settings.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "104"
},
{
"name": "CSS",
"bytes": "33014"
},
{
"name": "HTML",
"bytes": "120339"
},
{
"name": "JavaScript",
"bytes": "494398"
},
{
"name": "Makefile",
"bytes": "503"
},
{
"name": "Python",
"bytes": "199705"
},
{
"name": "Shell",
"bytes": "9877"
}
],
"symlink_target": ""
} |
def hello():
print("Hello world!")
| {
"content_hash": "7a820db47dbeaab07e90d820bdb6f74e",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 25,
"avg_line_length": 19.5,
"alnum_prop": 0.5897435897435898,
"repo_name": "jdgwartney/fabric-examples",
"id": "e64f971ebd8760b723360894d7707a5a19f75a19",
"size": "39",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hello/fabfile.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "39"
}
],
"symlink_target": ""
} |
from mxnet.test_utils import *
from common import setup_module, with_seed
import random
import warnings
def is_scalar(var):
return False if hasattr(var, "__len__") else True
def get_result_type(call, dflt_stype):
"""Try to infer result storage type for a sparse matrix and a given unary operation"""
if call is not None and dflt_stype != 'default':
zero = np.zeros(([1]))
result = do_normalize(call(zero))
if not almost_equal(result, zero, equal_nan=True):
expected_result_type = 'default'
else:
if dflt_stype is not None:
expected_result_type = dflt_stype;
else:
expected_result_type = 'default'
else:
expected_result_type = 'default'
return expected_result_type
def get_result_type_with_scalar(call, dflt_stype):
"""Try to infer result storage type when operating a sparse matrices and a scalar"""
if call is not None and dflt_stype != 'default':
zero = np.zeros(([1]))
result = call(zero, 5)
if not almost_equal(result, zero, equal_nan=True):
expected_result_type = 'default'
else:
if dflt_stype is not None:
expected_result_type = dflt_stype;
else:
expected_result_type = 'default'
else:
expected_result_type = 'default'
return expected_result_type
def get_result_type_2(call, dflt_stype):
"""Try to infer result storage type when operating on two sparse matrices"""
if call is not None and dflt_stype != 'default':
zero = np.zeros(([1]))
need_default = False
for outer in [zero, np.ones(zero.shape)]:
for inner in [zero, np.ones(zero.shape)]:
result = do_normalize(call(outer, inner))
if not almost_equal(result, zero, equal_nan=True):
need_default = True
break
if need_default is True:
break
if not need_default and dflt_stype is not None:
expected_result_type = dflt_stype
else:
expected_result_type = 'default'
else:
expected_result_type = 'default'
return expected_result_type
def get_result_type_3(call, dflt_stype):
"""Try to infer result storage type when operating on three sparse matrices"""
if call is not None and dflt_stype != 'default':
zero = np.zeros(([1]))
need_default = False
for moon in [zero]:
for outer in [zero]:
for inner in [zero]:
res_1, res_2 = call(moon, outer, inner)
result = do_normalize(res_1)
if not almost_equal(result, zero, equal_nan=True):
need_default = True
break
result = do_normalize(res_2)
if not almost_equal(result, zero, equal_nan=True):
need_default = True
break
if need_default is True:
break
if need_default is True:
break
if not need_default and dflt_stype is not None:
expected_result_type = dflt_stype
else:
expected_result_type = 'default'
else:
expected_result_type = 'default'
return expected_result_type
def get_fw_bw_result_types(forward_numpy_call, fwd_res_dflt,
backward_numpy_call, bwd_res_dflt):
return (get_result_type(forward_numpy_call, fwd_res_dflt),
get_result_type(backward_numpy_call, bwd_res_dflt))
def get_fw_bw_result_types_2(forward_numpy_call, fwd_res_dflt,
backward_numpy_call, bwd_res_dflt):
return (get_result_type(forward_numpy_call, fwd_res_dflt),
get_result_type_2(backward_numpy_call, bwd_res_dflt))
def get_fw_bw_result_types_with_scalar(forward_numpy_call, fwd_res_dflt,
backward_numpy_call, bwd_res_dflt):
return (get_result_type_with_scalar(forward_numpy_call, fwd_res_dflt),
get_result_type_with_scalar(backward_numpy_call, bwd_res_dflt))
def gen_rsp_random_indices(shape, density=.5, force_indices=None):
assert density >= 0 and density <= 1
indices = set()
if force_indices is not None:
for val in force_indices:
indices.add(int(val))
if not np.isclose(density, .0, rtol=1.e-3, atol=1.e-3, equal_nan=True) and len(shape) > 0:
row_count = shape[0]
for i in range(row_count):
r = random.uniform(0, 1)
if r <= density and len(indices) < shape[0]:
indices.add(i)
assert len(indices) <= shape[0]
return list(indices)
def all_zero(var):
return 0
@with_seed()
def test_elemwise_binary_ops():
def test_elemwise_binary_op(name, lhs_stype, rhs_stype, shape,
forward_mxnet_call, forward_numpy_call, backward_numpy_call,
lhs_grad_stype,
rhs_grad_stype,
expected_result_storage_type=None,
modifier_func=None,
lhs_density=.5,
rhs_density=.5,
force_lr_overlap=False,
force_grad_overlap=False,
ograd_density=0.0,
skip_gradient_check=False,
shuffle_csr_indices=True,
verbose=False):
if lhs_grad_stype is None:
lhs_grad_stype = lhs_stype
if rhs_grad_stype is None:
rhs_grad_stype = rhs_stype
lhs_grad_stype = get_result_type_3(backward_numpy_call, lhs_grad_stype)
rhs_grad_stype = get_result_type_3(backward_numpy_call, rhs_grad_stype)
if verbose is True:
print("testing: {} lhs={}, rhs={}, lhs_grad_stype={}, rhs_grad_stype={}"
.format(name, lhs_stype, rhs_stype, lhs_grad_stype, rhs_grad_stype))
# Output type should be same as lvalue type, unless otherwise specified
if expected_result_storage_type is None:
if lhs_stype == 'default' or rhs_stype == 'default':
expected_result_storage_type = 'default'
else:
expected_result_storage_type = lhs_stype
lhs = mx.symbol.Variable('lhs', stype=lhs_stype)
rhs = mx.symbol.Variable('rhs', stype=rhs_stype)
grad_stypes = dict()
grad_stypes['lhs'] = lhs_grad_stype
grad_stypes['rhs'] = rhs_grad_stype
if lhs_stype == 'default':
lhs_nd = rand_ndarray(shape, 'default')
if abs(lhs_density) < 1e-4:
func = all_zero
else:
func = modifier_func
lhs_nd = mx.nd.array(assign_each(lhs_nd.asnumpy(), func))
else:
lhs_nd = create_sparse_array_zd(
shape, lhs_stype, density=lhs_density,
modifier_func=modifier_func,
shuffle_csr_indices=shuffle_csr_indices,
rsp_indices=gen_rsp_random_indices(
shape,
density=lhs_density,
force_indices=[(shape[0]/2)] if force_lr_overlap is True else None
))
if rhs_stype == 'default':
rhs_nd = rand_ndarray(shape, 'default')
if abs(rhs_density) < 1e-4:
func = all_zero
else:
func = modifier_func
rhs_nd = mx.nd.array(assign_each(rhs_nd.asnumpy(), func))
else:
rhs_nd = create_sparse_array_zd(
shape, rhs_stype, density=rhs_density,
modifier_func=modifier_func,
shuffle_csr_indices=shuffle_csr_indices,
rsp_indices=gen_rsp_random_indices(
shape,
density=rhs_density,
force_indices=[(shape[0]/2)] if force_lr_overlap is True else None
))
lhs_np = lhs_nd.asnumpy()
rhs_np = rhs_nd.asnumpy()
if verbose is True:
print("lhs input: {}".format(lhs_np))
print("rhs input: {}".format(rhs_np))
out_np = forward_numpy_call(lhs_np, rhs_np)
if verbose is True:
print("out_np: {}".format(out_np))
test = forward_mxnet_call(lhs, rhs)
location = {'lhs': lhs_nd, 'rhs': rhs_nd}
outputs = check_symbolic_forward(test, location, [out_np], equal_nan=True)
assert len(outputs) == 1
assert outputs[0].stype == expected_result_storage_type
if verbose is True:
print ("mx forward output: ", outputs[0].asnumpy())
print ("lhs_nd: ", lhs_nd.stype)
print ("rhs_nd: ", rhs_nd.stype)
print ("forward output: ", outputs[0].stype)
if outputs[0].stype != 'default':
out_grad = create_sparse_array_zd(
shape, outputs[0].stype, density=ograd_density,
data_init=1,
modifier_func=lambda x: 2,
shuffle_csr_indices=shuffle_csr_indices,
rsp_indices=gen_rsp_random_indices(
shape,
density=ograd_density,
force_indices=[(shape[0]/2)] if force_grad_overlap is True else None
))
else:
if abs(ograd_density) < 1e-4:
out_grad = mx.nd.array(np.zeros(shape))
else:
out_grad = mx.nd.array(np.ones(shape))
out_grad_np = out_grad.asnumpy()
if verbose is True:
print("out_grad_np", out_grad_np)
ingrad_lhs_np, ingrad_rhs_np = backward_numpy_call(out_grad_np, lhs_np, rhs_np)
if verbose is True:
print("out_grad", out_grad.asnumpy())
print("ingrad_lhs_np", ingrad_lhs_np)
print("ingrad_rhs_np", ingrad_rhs_np)
igrads_result = check_symbolic_backward(test, location, [out_grad],
[ingrad_lhs_np, ingrad_rhs_np],
grad_stypes=grad_stypes,
equal_nan=True)
if verbose is True:
print("ingrad_lhs", igrads_result['lhs'].asnumpy())
print("ingrad_rhs", igrads_result['rhs'].asnumpy())
assert len(igrads_result) == 2
if lhs_grad_stype is not None:
assert igrads_result['lhs'].stype == lhs_grad_stype
if rhs_grad_stype is not None:
assert igrads_result['rhs'].stype == rhs_grad_stype
if skip_gradient_check is not True:
check_numeric_gradient(test, location,
grad_stype_dict=grad_stypes)
def check_all(l, r, check_function):
assert l.shape == r.shape
return check_function(l, r)
def gt(l, r):
return check_all(l, r, lambda a, b: a > b)
def ge(l, r):
return check_all(l, r, lambda a, b: a >= b)
def lt(l, r):
return check_all(l, r, lambda a, b: a < b)
def le(l, r):
return check_all(l, r, lambda a, b: a <= b)
def least_sparse(lstype, rstype):
if lstype == 'default' and rstype == 'default':
return 'default'
elif rstype != 'default':
return rstype
return lstype
def most_dense(lstype, rstype):
if lstype == rstype:
return lstype
return 'default'
def check_elemwise_binary_ops(lhs_stype, rhs_stype, shape,
lhs_grad_stype=None, rhs_grad_stype=None,
lhs_density=.5, rhs_density=.5,
force_lr_overlap=False,
force_grad_overlap=False,
ograd_density=0.0):
test_elemwise_binary_op("elemwise_add", lhs_stype, rhs_stype, shape,
lambda l, r: mx.sym.sparse.elemwise_add(l, r),
lambda l, r: l + r,
lambda outg, l, r: (outg, outg),
lhs_grad_stype, rhs_grad_stype,
ograd_density=ograd_density,
force_lr_overlap=force_lr_overlap,
force_grad_overlap=force_grad_overlap,
lhs_density=lhs_density, rhs_density=rhs_density,
verbose=False)
test_elemwise_binary_op("elemwise_sub", lhs_stype, rhs_stype, shape,
lambda l, r: mx.sym.sparse.elemwise_sub(l, r),
lambda l, r: l - r,
lambda outg, l, r: (outg, -outg),
lhs_grad_stype, rhs_grad_stype,
ograd_density=ograd_density,
force_lr_overlap=force_lr_overlap,
force_grad_overlap=force_grad_overlap,
lhs_density=lhs_density,
rhs_density=rhs_density,
verbose=False)
test_elemwise_binary_op("elemwise_mul", lhs_stype, rhs_stype, shape,
lambda l, r: mx.sym.sparse.elemwise_mul(l, r),
lambda l, r: l * r,
lambda outg, l, r: (outg * r, outg * l),
least_sparse(lhs_stype, rhs_stype),
least_sparse(lhs_stype, rhs_stype),
expected_result_storage_type=most_dense(lhs_stype, rhs_stype),
ograd_density=ograd_density,
force_lr_overlap=force_lr_overlap,
force_grad_overlap=force_grad_overlap,
lhs_density=lhs_density, rhs_density=rhs_density,
verbose=False)
test_elemwise_binary_op("elemwise_div", lhs_stype, rhs_stype, shape,
lambda l, r: mx.sym.sparse.elemwise_div(l, r),
lambda l, r: l / r,
lambda outg, l, r: (outg * (1/r), outg * (-l/(r*r))),
lhs_grad_stype, rhs_grad_stype,
modifier_func=lambda a: a if abs(a) > 0.25 else abs(a) + 1,
force_lr_overlap=force_lr_overlap,
force_grad_overlap=force_grad_overlap,
lhs_density=lhs_density, rhs_density=rhs_density,
ograd_density=ograd_density,
expected_result_storage_type='default',
skip_gradient_check=True,
verbose=False)
test_elemwise_binary_op("maximum", lhs_stype, rhs_stype, shape,
lambda l, r: mx.sym._internal._maximum(l, r),
lambda l, r: np.maximum(l, r),
lambda outg, l, r: (outg * ge(l, r), outg * lt(l, r)),
lhs_grad_stype, rhs_grad_stype,
modifier_func=lambda a: a if abs(a) > 0.25 else abs(a) + 1,
force_lr_overlap=force_lr_overlap,
force_grad_overlap=force_grad_overlap,
lhs_density=lhs_density, rhs_density=rhs_density,
skip_gradient_check=True,
ograd_density=ograd_density,
verbose=False)
test_elemwise_binary_op("minimum", lhs_stype, rhs_stype, shape,
lambda l, r: mx.sym._internal._minimum(l, r),
lambda l, r: np.minimum(l, r),
lambda outg, l, r: (outg * le(l, r), outg * gt(l, r)),
lhs_grad_stype, rhs_grad_stype,
modifier_func=lambda a: a if abs(a) > 0.25 else abs(a) + 1,
force_lr_overlap=force_lr_overlap,
force_grad_overlap=force_grad_overlap,
lhs_density=lhs_density, rhs_density=rhs_density,
ograd_density=ograd_density,
skip_gradient_check=True,
verbose=False)
test_elemwise_binary_op("hypot", lhs_stype, rhs_stype, shape,
lambda l, r: mx.sym._internal._hypot(l, r),
lambda l, r: np.hypot(l, r),
lambda outg, l, r: (
outg * assign_each2(
l, r, lambda a, b: a/np.sqrt(a * a + b * b)),
outg * assign_each2(
l, r, lambda a, b: b/np.sqrt(a * a + b * b))
),
lhs_grad_stype, rhs_grad_stype,
force_lr_overlap=force_lr_overlap,
force_grad_overlap=force_grad_overlap,
lhs_density=lhs_density, rhs_density=rhs_density,
ograd_density=ograd_density,
skip_gradient_check=True,
verbose=False)
# Run basic tests
with warnings.catch_warnings():
warnings.simplefilter("ignore")
for ii in range(1):
# Run defaults
check_elemwise_binary_ops('default', 'default', rand_shape_2d())
# Try different densities
for lhs_density in [0.0, random.uniform(0, 1), 1.0]:
for rhs_density in [0.0, random.uniform(0, 1), 1.0]:
for ograd_density in [0.0, random.uniform(0, 1), 1.0]:
shape = rand_shape_2d()
print("lhs_density={}, rhs_density={}, ograd_density={}, shape: {}".format(
lhs_density, rhs_density, ograd_density, shape))
# Try row_sparse overlaps
for force_lr_overlap in [False, True]:
for force_grad_overlap in [False, True]:
shape = rand_shape_2d()
print(" force_lr_overlap={}, force_grad_overlap={}, shape={}".
format(force_lr_overlap, force_grad_overlap, shape))
# Left and right always overlap when one is default storage
# (assuming the row_sparse one has some entries in it)
if force_lr_overlap is False:
check_elemwise_binary_ops('default', 'row_sparse', shape,
lhs_density=lhs_density,
rhs_density=rhs_density,
force_lr_overlap=force_lr_overlap,
force_grad_overlap=force_grad_overlap,
ograd_density=ograd_density)
check_elemwise_binary_ops('row_sparse', 'default', shape,
lhs_density=lhs_density,
rhs_density=rhs_density,
force_lr_overlap=force_lr_overlap,
force_grad_overlap=force_grad_overlap,
ograd_density=ograd_density)
# Back to left-right overlap possiblities
check_elemwise_binary_ops('row_sparse', 'row_sparse', shape,
lhs_grad_stype='row_sparse',
rhs_grad_stype='row_sparse',
lhs_density=lhs_density,
rhs_density=rhs_density,
force_lr_overlap=force_lr_overlap,
force_grad_overlap=force_grad_overlap,
ograd_density=ograd_density)
# No overlap flags for CSR
check_elemwise_binary_ops('csr', 'csr', shape,
lhs_grad_stype='csr',
rhs_grad_stype='csr',
lhs_density=lhs_density,
rhs_density=rhs_density,
ograd_density=ograd_density)
check_elemwise_binary_ops('csr', 'csr', shape,
lhs_grad_stype='default',
rhs_grad_stype='default',
lhs_density=lhs_density,
rhs_density=rhs_density,
ograd_density=ograd_density)
check_elemwise_binary_ops('default', 'csr', shape,
lhs_grad_stype='csr',
rhs_grad_stype='csr',
lhs_density=lhs_density,
rhs_density=rhs_density,
ograd_density=ograd_density)
check_elemwise_binary_ops('csr', 'default', shape,
lhs_grad_stype='csr',
rhs_grad_stype='csr',
lhs_density=lhs_density,
rhs_density=rhs_density,
ograd_density=ograd_density)
@with_seed()
def test_elemwise_csr_same_zeros():
# Zeroes
a = mx.nd.sparse.zeros('csr', (1,1))
b = mx.nd.elemwise_add(a,a)
res = a.asnumpy() + a.asnumpy()
assert_almost_equal(b.asnumpy(), res)
def as_dense(arr):
if arr.stype != 'default':
return mx.nd.cast_storage(arr, stype='default')
else:
return arr;
# Make sure that 0's look like 0's when we do a comparison
def do_normalize(arr):
ret = arr.copy()
idx = np.isclose(arr, -0, rtol=1.e-3, atol=1.e-3, equal_nan=True)
ret[idx] = 0
return ret
def check_sparse_mathematical_core(name, stype,
forward_mxnet_call, forward_numpy_call, backward_numpy_call=None,
rhs_arg=None, data_init=9., grad_init=2., output_grad_stype=None,
input_grad_stype=None, force_overlap=False, density=.5,
ograd_density=.5, verbose=False, shuffle_csr_indices=True):
if verbose is True:
print("TESTING: " + name)
data = mx.symbol.Variable('data', stype=stype)
temp_input_grad_stype = input_grad_stype
if temp_input_grad_stype is None:
temp_input_grad_stype = stype
if rhs_arg is not None:
if is_scalar(rhs_arg):
expected_result_type, expected_grad_result_type = \
get_fw_bw_result_types_with_scalar(forward_numpy_call, stype,
backward_numpy_call, temp_input_grad_stype)
else:
expected_result_type, expected_grad_result_type = \
get_fw_bw_result_types_2(forward_numpy_call, stype,
backward_numpy_call, temp_input_grad_stype)
else:
expected_result_type, expected_grad_result_type = \
get_fw_bw_result_types(forward_numpy_call, stype,
backward_numpy_call, temp_input_grad_stype)
if input_grad_stype is not None and input_grad_stype != expected_grad_result_type:
print("{}: explicit override of deduced input grad type '{}' with '{}'".format(
name, expected_grad_result_type, input_grad_stype))
expected_grad_result_type = input_grad_stype
shape = rand_shape_2d()
if verbose is True:
print("Shape: ", shape, "density: ", density, "force_overlap", force_overlap)
if stype == 'default':
data_tmp = np.zeros(shape)
if abs(density) >= 1e-4:
data_tmp[:] = data_init
arr_data = mx.nd.array(data_tmp)
else:
arr_data = create_sparse_array_zd(
shape, stype, density=density,
data_init=data_init,
shuffle_csr_indices=shuffle_csr_indices,
rsp_indices=gen_rsp_random_indices(
shape,
density=density,
force_indices=[(shape[0]/2)] if force_overlap is True else None
)
)
data_tmp = arr_data.asnumpy()
if verbose is True:
print("arr_data indices", arr_data.indices.asnumpy())
if verbose is True:
print("input", data_tmp)
if backward_numpy_call is None:
arr_grad = None
elif expected_grad_result_type == 'default':
if abs(density) < 1e-4:
arr_grad = mx.nd.zeros(shape)
else:
arr_grad = mx.nd.ones(shape)
else:
arr_grad = create_sparse_array_zd(
shape,
expected_grad_result_type,
density=density,
data_init=1,
shuffle_csr_indices=shuffle_csr_indices,
rsp_indices=gen_rsp_random_indices(
shape,
density=density,
force_indices=[(shape[0]/2)] if force_overlap is True else None
)
)
if rhs_arg is not None:
test = forward_mxnet_call(data, rhs_arg)
else:
test = forward_mxnet_call(data)
args = list()
args.append(arr_data)
if arr_grad is not None:
exe_test = test.bind(default_context(), args=args, args_grad=[arr_grad])
else:
exe_test = test.bind(default_context(), args=args)
exe_test.forward(is_train=True)
assert exe_test.outputs[0].stype == expected_result_type
out = exe_test.outputs[0].asnumpy()
if rhs_arg is not None:
npout = forward_numpy_call(data_tmp, rhs_arg)
else:
npout = forward_numpy_call(data_tmp)
if verbose is True:
print("out", out)
print("npout", npout)
assert_almost_equal(out, npout, equal_nan=True)
if backward_numpy_call is not None:
if output_grad_stype == 'default' or output_grad_stype is None:
out_grad = mx.nd.empty(shape)
out_grad[:] = grad_init
else:
out_grad = create_sparse_array_zd(
shape, output_grad_stype,
density=density,
data_init=grad_init,
shuffle_csr_indices=shuffle_csr_indices,
rsp_indices=gen_rsp_random_indices(
shape,
density=ograd_density,
force_indices=[(shape[0]/2)] if force_overlap is True else None))
npout_grad = out_grad.asnumpy()
if verbose is True:
print("npout_grad", npout_grad)
if rhs_arg is not None:
temp = backward_numpy_call(data_tmp, rhs_arg)
else:
temp = backward_numpy_call(data_tmp)
input_grad = npout_grad * temp
if verbose is True:
print(arr_grad.asnumpy())
exe_test.backward(out_grad)
if verbose is True:
print(arr_grad.asnumpy())
assert arr_grad.stype == expected_grad_result_type
arr_grad = arr_grad.asnumpy()
if verbose is True:
print(name)
print("arr_grad", arr_grad)
print("input_grad", input_grad)
assert_almost_equal(arr_grad, input_grad, equal_nan=True)
@with_seed()
def test_sparse_mathematical_core():
def util_sign(a):
if np.isclose(a, -0, rtol=1.e-3, atol=1.e-3, equal_nan=True):
return 0
elif np.isclose(a, 0, rtol=1.e-3, atol=1.e-3, equal_nan=True):
return 0
elif a < 0.0:
return -1
else: # a > 0.0:
return 1
# Check scalar binary operators
def check_binary_op_with_scalar(stype,
output_grad_stype=None,
input_grad_stype=None,
density=.5, ograd_density=.5,
force_overlap=False,):
# mul_scalar
check_sparse_mathematical_core("mul_scalar", stype,
lambda x, y: x * y,
lambda x, y: x * y,
lambda input, rhs: rhs,
rhs_arg=5.0,
data_init=2, grad_init=3,
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
density=density, ograd_density=ograd_density,
force_overlap=force_overlap,
verbose=False)
# plus_scalar
check_sparse_mathematical_core("plus_scalar", stype,
lambda x, y: x + y,
lambda x, y: x + y,
lambda input, rhs: 1,
rhs_arg=5.0,
data_init=2, grad_init=3,
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
density=density, ograd_density=ograd_density,
force_overlap=force_overlap,
verbose=False)
# minus_scalar
check_sparse_mathematical_core("minus_scalar", stype,
lambda x, y: x - y,
lambda x, y: x - y,
lambda input, rhs: 1,
rhs_arg=5.0,
data_init=2, grad_init=3,
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
density=density, ograd_density=ograd_density,
force_overlap=force_overlap,
verbose=False)
# Check many basic unary operators
def check_mathematical_core(stype, output_grad_stype=None,
input_grad_stype=None, force_overlap=False,
density=.5, ograd_density=.5):
# negative
check_sparse_mathematical_core("negative", stype,
lambda x: mx.sym.sparse.negative(x),
lambda x: np.negative(x),
force_overlap=force_overlap,
density=density,
input_grad_stype=input_grad_stype,
ograd_density=ograd_density)
# square
check_sparse_mathematical_core("square", stype,
lambda x: mx.sym.sparse.square(x),
lambda x: np.square(x),
lambda x: 2 * x,
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap,
density=density, ograd_density=ograd_density,
verbose=False)
if stype != "csr":
# sqrt
check_sparse_mathematical_core("sqrt", stype,
lambda x: mx.sym.sparse.sqrt(x),
lambda x: np.sqrt(x),
lambda x: 1.0/(2.0 * np.sqrt(x)),
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap,
density=density, ograd_density=ograd_density,
verbose=False)
# rsqrt
check_sparse_mathematical_core("rsqrt", stype,
lambda x: mx.sym.sparse.rsqrt(x),
lambda x: 1 / np.sqrt(x),
lambda x: -(1.0 / (2.0 * x * np.sqrt(x))),
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap,
density=density, ograd_density=ograd_density)
# tan
check_sparse_mathematical_core("tan", stype,
lambda x: mx.sym.sparse.tan(x),
lambda x: np.tan(x),
lambda x: np.tan(x) ** 2 + 1,
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
density=density,
ograd_density=ograd_density)
# abs
check_sparse_mathematical_core("abs", stype,
lambda x: mx.sym.sparse.abs(x),
lambda x: np.abs(x),
lambda x: assign_each(x, function=util_sign),
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap,
density=density, ograd_density=ograd_density)
# floor
check_sparse_mathematical_core("floor", stype, lambda x: mx.sym.sparse.floor(x),
lambda x: np.floor(x),
force_overlap=force_overlap,
input_grad_stype=input_grad_stype,
density=density, ograd_density=ograd_density)
# ceil
check_sparse_mathematical_core("ceil", stype,
lambda x: mx.sym.sparse.ceil(x),
lambda x: np.ceil(x),
force_overlap=force_overlap,
input_grad_stype=input_grad_stype,
density=density, ograd_density=ograd_density)
# sign
check_sparse_mathematical_core("sign", stype,
lambda x: mx.sym.sparse.sign(x),
lambda x: np.sign(x),
lambda x: np.zeros(x.shape),
output_grad_stype=output_grad_stype,
force_overlap=force_overlap,
density=density, ograd_density=ograd_density)
# cos
check_sparse_mathematical_core("cos", stype,
lambda x: mx.sym.sparse.cos(x),
lambda x: np.cos(x),
lambda x: -np.sin(x),
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap,
density=density, ograd_density=ograd_density)
# sin
check_sparse_mathematical_core("sin", stype,
lambda x: mx.sym.sparse.sin(x),
lambda x: np.sin(x),
lambda x: np.cos(x),
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap,
density=density, ograd_density=ograd_density)
# arcsin
check_sparse_mathematical_core("arcsin", stype,
lambda x: mx.sym.sparse.arcsin(x),
lambda x: np.arcsin(x),
lambda x: 1. / (1. - x ** 2) ** (1. / 2.),
data_init=0.5, grad_init=0.5,
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap,
density=density, ograd_density=ograd_density)
# arccos
check_sparse_mathematical_core("arccos", stype,
lambda x: mx.sym.sparse.arccos(x),
lambda x: np.arccos(x),
lambda x: -1. / (1. - x ** 2.) ** (1. / 2.),
data_init=0.5, grad_init=0.5,
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap, density=density,
ograd_density=ograd_density)
# arctan
check_sparse_mathematical_core("arctan", stype,
lambda x: mx.sym.sparse.arctan(x),
lambda x: np.arctan(x),
lambda x: 1. / (x ** 2. + 1.),
data_init=0.5, grad_init=0.5,
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap,
density=density, ograd_density=ograd_density)
# degrees
check_sparse_mathematical_core("degrees", stype,
lambda x: mx.sym.sparse.degrees(x),
lambda x: np.degrees(x),
lambda x: assign_each(x, lambda a: 180./np.pi),
data_init=0.5, grad_init=0.5,
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap,
density=density, ograd_density=ograd_density)
# radians
check_sparse_mathematical_core("radians", stype,
lambda x: mx.sym.sparse.radians(x),
lambda x: np.radians(x),
lambda x: assign_each(x, lambda a: np.pi / 180.),
data_init=0.6, grad_init=1,
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap,
density=density, ograd_density=ograd_density)
# sinh
check_sparse_mathematical_core("sinh", stype,
lambda x: mx.sym.sparse.sinh(x),
lambda x: np.sinh(x),
lambda x: np.cosh(x),
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap,
density=density, ograd_density=ograd_density)
# cosh
check_sparse_mathematical_core("cosh", stype,
lambda x: mx.sym.sparse.cosh(x),
lambda x: np.cosh(x),
lambda x: np.sinh(x),
data_init=5, grad_init=5,
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap,
density=density, ograd_density=ograd_density)
# tanh
check_sparse_mathematical_core("tanh", stype,
lambda x: mx.sym.sparse.tanh(x),
lambda x: np.tanh(x),
lambda x: 1. - np.tanh(x) ** 2,
data_init=0.5, grad_init=1,
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap, density=density,
ograd_density=ograd_density)
# arcsinh
check_sparse_mathematical_core("arcsinh", stype,
lambda x: mx.sym.sparse.arcsinh(x),
lambda x: np.arcsinh(x),
lambda x: 1./(x**2 + 1.)**(1./2.),
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap, density=density,
ograd_density=ograd_density)
# arccosh
check_sparse_mathematical_core("arccosh", stype,
lambda x: mx.sym.sparse.arccosh(x),
lambda x: np.arccosh(x),
lambda x: 1./(x**2 - 1.)**(1./2.),
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap, density=density,
ograd_density=ograd_density)
# arctanh
check_sparse_mathematical_core("arctanh", stype,
lambda x: mx.sym.sparse.arctanh(x),
lambda x: np.arctanh(x),
lambda x: -1./(x**2 - 1.),
data_init=0.5,
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap, density=density,
ograd_density=ograd_density)
# log1p
check_sparse_mathematical_core("log1p", stype,
lambda x: mx.sym.sparse.log1p(x),
lambda x: np.log1p(x),
lambda x: 1. / (1.0 + x),
data_init=0.5, grad_init=0.5,
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap, density=density,
ograd_density=ograd_density)
# expm1
check_sparse_mathematical_core("expm1", stype,
lambda x: mx.sym.sparse.expm1(x),
lambda x: np.expm1(x),
lambda x: np.exp(x),
data_init=0.5, grad_init=0.5,
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap, density=density,
ograd_density=ograd_density)
# log10
check_sparse_mathematical_core("log10", stype,
lambda x: mx.sym.sparse.log10(x),
lambda x: np.log10(x),
lambda x: 1. / (x * np.log(10.)),
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap, density=density,
ograd_density=ograd_density)
# log2
check_sparse_mathematical_core("log2", stype,
lambda x: mx.sym.sparse.log2(x),
lambda x: np.log2(x),
lambda x: 1. / (x * np.log(2.)),
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap, density=density,
ograd_density=ograd_density)
# rint
check_sparse_mathematical_core("rint", stype,
lambda x: mx.sym.sparse.rint(x),
lambda x: np.rint(x),
force_overlap=force_overlap, density=density,
input_grad_stype=input_grad_stype,
ograd_density=ograd_density)
# fix
check_sparse_mathematical_core("fix", stype,
lambda x: mx.sym.sparse.fix(x),
lambda x: np.fix(x),
force_overlap=force_overlap, density=density,
input_grad_stype=input_grad_stype,
ograd_density=ograd_density)
try:
from scipy import special as scipy_special
import_succeeded = True
# gamma
check_sparse_mathematical_core("gamma", stype,
lambda x: mx.sym.sparse.gamma(x),
lambda x: scipy_special.gamma(x),
lambda x: scipy_special.gamma(x) * scipy_special.psi(x),
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap,
density=density, ograd_density=ograd_density)
# gammaln
check_sparse_mathematical_core("gammaln", stype,
lambda x: mx.sym.sparse.gammaln(x),
lambda x: scipy_special.gammaln(x),
lambda x: scipy_special.psi(x),
output_grad_stype=output_grad_stype,
input_grad_stype=input_grad_stype,
force_overlap=force_overlap,
density=density, ograd_density=ograd_density)
except:
if import_succeeded == False:
print("Could not import scipy. Skipping unit tests for special functions")
else:
raise
for i in range(1):
print("pass", i)
for density in [0.0, random.uniform(0, 1), 1.0]:
for ograd_density in [0.0, random.uniform(0, 1), 1.0]:
for force_overlap in [False, True]:
print("{}, {}, {}".format(density, ograd_density, force_overlap))
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# Check unary ops (unary fwd, binary bwd)
check_mathematical_core('default', force_overlap=force_overlap,
density=density, ograd_density=ograd_density)
check_mathematical_core('row_sparse', force_overlap=force_overlap,
density=density, ograd_density=ograd_density)
check_mathematical_core('row_sparse', output_grad_stype='default',
force_overlap=force_overlap,
density=density, ograd_density=ograd_density)
check_mathematical_core('row_sparse', output_grad_stype='row_sparse',
force_overlap=force_overlap,
density=density, ograd_density=ograd_density)
check_mathematical_core('csr', output_grad_stype='default',
force_overlap=force_overlap,
density=density, ograd_density=ograd_density)
check_mathematical_core('csr', output_grad_stype='csr',
force_overlap=force_overlap,
density=density, ograd_density=ograd_density)
# Check binary with scalar ops
check_binary_op_with_scalar('default',
density=density,
ograd_density=ograd_density,
force_overlap=force_overlap)
check_binary_op_with_scalar('row_sparse',
density=density,
ograd_density=ograd_density,
force_overlap=force_overlap)
check_binary_op_with_scalar('row_sparse', output_grad_stype='default',
density=density,
ograd_density=ograd_density,
force_overlap=force_overlap)
check_binary_op_with_scalar('row_sparse',
output_grad_stype='row_sparse',
density=density, ograd_density=ograd_density,
force_overlap=force_overlap)
check_binary_op_with_scalar('csr',
output_grad_stype='csr',
input_grad_stype='default',
density=density,
ograd_density=ograd_density,
force_overlap=force_overlap)
check_binary_op_with_scalar('csr',
output_grad_stype='csr',
input_grad_stype='csr',
density=density,
ograd_density=ograd_density,
force_overlap=force_overlap)
check_binary_op_with_scalar('csr',
output_grad_stype='default',
density=density,
ograd_density=ograd_density,
force_overlap=force_overlap)
@with_seed()
def test_elemwise_add_ex():
def check_elemwise_add_ex(lhs_stype, rhs_stype, shape, lhs_grad_stype=None, rhs_grad_stype=None):
lhs = mx.symbol.Variable('lhs', stype=lhs_stype)
rhs = mx.symbol.Variable('rhs', stype=rhs_stype)
lhs_nd = rand_ndarray(shape, lhs_stype)
rhs_nd = rand_ndarray(shape, rhs_stype)
lhs_np = lhs_nd.asnumpy()
rhs_np = rhs_nd.asnumpy()
out_np = lhs_np + rhs_np
test = mx.symbol.sparse.elemwise_add(lhs, rhs)
location = {'lhs': lhs_nd, 'rhs': rhs_nd}
check_symbolic_forward(test, location, [out_np])
check_numeric_gradient(test, location)
grad_stypes = {}
if lhs_grad_stype is not None and lhs_grad_stype != 'default':
grad_stypes['lhs'] = lhs_grad_stype
if rhs_grad_stype is not None and rhs_grad_stype != 'default':
grad_stypes['rhs'] = rhs_grad_stype
check_symbolic_backward(test, location, [out_np], [out_np, out_np],
grad_stypes=grad_stypes)
shapes = [rand_shape_2d(), rand_shape_3d()]
for shape in shapes:
check_elemwise_add_ex('default', 'default', shape)
check_elemwise_add_ex('row_sparse', 'row_sparse', shape,
lhs_grad_stype='row_sparse', rhs_grad_stype='row_sparse')
@with_seed()
def test_cast_storage_ex():
def check_cast_storage(shape, density, from_stype, to_stype, check_numeric_grad=True):
x = mx.symbol.Variable('x', stype=from_stype)
x_nd = rand_ndarray(shape, from_stype, density=density)
x_np = x_nd.asnumpy()
out_np = x_np
test = mx.symbol.cast_storage(x, stype=to_stype)
location = {'x': x_nd}
check_symbolic_forward(test, location, [out_np])
# consider disable the numeric grad check for gpu block kernel since the input is large
if check_numeric_grad:
check_numeric_gradient(test, location)
grad_stypes = {'x': to_stype}
check_symbolic_backward(test, location, [out_np], [out_np], grad_stypes=grad_stypes)
density = [1.00, 0.50, 0.01]
for d in density:
shape_2d = rand_shape_2d()
shape_3d = rand_shape_3d()
check_cast_storage(shape_2d, d, 'csr', 'default')
check_cast_storage(shape_2d, d, 'default', 'csr')
check_cast_storage(shape_2d, d, 'csr', 'csr')
check_cast_storage(shape_2d, d, 'row_sparse', 'default')
check_cast_storage(shape_2d, d, 'default', 'row_sparse')
check_cast_storage(shape_2d, d, 'row_sparse', 'row_sparse')
check_cast_storage(shape_3d, d, 'row_sparse', 'default')
check_cast_storage(shape_3d, d, 'default', 'row_sparse')
check_cast_storage(shape_3d, d, 'row_sparse', 'row_sparse')
for i in range(4, 6):
shape = rand_shape_nd(i, 5)
check_cast_storage(shape, d, 'default', 'row_sparse')
check_cast_storage(shape, d, 'row_sparse', 'default')
# Test specific gpu kernels
if default_context().device_type is 'gpu':
dim0 = rnd.randint(1, 10)
# test gpu thread kernel
check_cast_storage((dim0, rnd.randint( 1, 32)), d, 'default', 'csr')
# test gpu warp kernel
check_cast_storage((dim0, rnd.randint( 32, 512)), d, 'default', 'csr')
# test gpu block kernel
check_cast_storage((dim0, rnd.randint(512, 1024)), d, 'default', 'csr',
check_numeric_grad=False)
# test gpu thread kernel
check_cast_storage((dim0, rnd.randint( 1, 32)), d, 'default', 'row_sparse')
# test gpu warp kernel
check_cast_storage((dim0, rnd.randint( 32, 512)), d, 'default', 'row_sparse')
# test gpu block kernel
check_cast_storage((dim0, rnd.randint(512, 1024)), d, 'default', 'row_sparse',
check_numeric_grad=False)
@with_seed()
def test_sparse_dot():
def test_dot_csr(lhs_shape, rhs_shape, rhs_stype, trans_lhs, lhs_density, rhs_density):
lhs_nd = rand_ndarray(lhs_shape, 'csr', density=lhs_density, shuffle_csr_indices=False)
lhs_dns = lhs_nd.tostype('default')
rhs_nd = rand_ndarray(rhs_shape, rhs_stype, density=rhs_density)
rhs_dns = rhs_nd if rhs_stype == 'default' else rhs_nd.tostype('default')
out = mx.nd.dot(lhs_nd, rhs_nd, transpose_a=trans_lhs)
out_dns = mx.nd.dot(lhs_dns, rhs_dns, transpose_a=trans_lhs)
out_np = out_dns.asnumpy()
assert_almost_equal(out.asnumpy(), out_np, rtol=1e-4, atol=1e-5)
# test symbolic forward
lhs = mx.symbol.Variable('lhs', stype='csr')
rhs = mx.symbol.Variable('rhs', stype=rhs_stype)
out = mx.symbol.sparse.dot(lhs, rhs, transpose_a=trans_lhs)
location = {'lhs': lhs_nd, 'rhs': rhs_nd}
check_symbolic_forward(out, location, [out_np], rtol=1e-3, atol=1e-4)
# test symbolic backward
backward_trans = not trans_lhs
rhs_backward_grad = mx.nd.dot(lhs_dns, out_dns, transpose_a=backward_trans).asnumpy()
expected = {'rhs': rhs_backward_grad}
check_symbolic_backward(out, location, [out_np], expected,
grad_req={'lhs': 'null', 'rhs': 'write'},
rtol=1e-3, atol=1e-4)
def test_dot_dns_csr(lhs_shape, rhs_shape, lhs_density, rhs_density, trans_lhs=False, trans_rhs=False):
lhs_nd = rand_ndarray(lhs_shape, stype='default', density=lhs_density)
rhs_nd = rand_ndarray(rhs_shape, stype='csr', density=rhs_density)
rhs_dns = rhs_nd.tostype('default')
out = mx.nd.sparse.dot(lhs_nd, rhs_nd, transpose_a=trans_lhs, transpose_b=trans_rhs)
out_dns = mx.nd.dot(lhs_nd, rhs_dns, transpose_a=trans_lhs, transpose_b=trans_rhs)
out_np = out_dns.asnumpy()
assert_almost_equal(out.asnumpy(), out_np, rtol=1e-4, atol=1e-5)
# test symbolic forward
lhs = mx.symbol.Variable('lhs', stype='default')
rhs = mx.symbol.Variable('rhs', stype='csr')
out = mx.symbol.sparse.dot(lhs, rhs, transpose_a=trans_lhs, transpose_b=trans_rhs)
location = {'lhs': lhs_nd, 'rhs': rhs_nd}
check_symbolic_forward(out, location, [out_np], rtol=1e-3, atol=1e-4)
# test symbolic backward
backward_trans = not trans_lhs
rhs_backward_grad = mx.nd.dot(lhs_nd, out_dns, transpose_a=backward_trans).asnumpy()
expected = {'rhs': rhs_backward_grad}
check_symbolic_backward(out, location, [out_np], expected,
grad_req={'lhs': 'null', 'rhs': 'write'},
rtol=1e-3, atol=1e-4)
def test_sparse_dot_zero_output(lhs_shape, trans_lhs, rhs_num_cols):
"""Test for nnr_out = 0. Before the fix, the test would fail."""
lhs = mx.nd.zeros(lhs_shape)
irow = np.random.randint(0, lhs_shape[0])
icol = np.random.randint(0, lhs_shape[1])
lhs[irow, icol] = 1.0
if trans_lhs:
rhs = rand_ndarray(shape=(lhs_shape[0], rhs_num_cols), stype='default')
rhs[irow, :] = 0
else:
rhs = rand_ndarray(shape=(lhs_shape[1], rhs_num_cols), stype='default')
rhs[icol, :] = 0
dns_out = mx.nd.dot(lhs, rhs, transpose_a=trans_lhs)
assert mx.nd.sum(mx.nd.abs(dns_out)).asscalar() == 0
sps_out = mx.nd.sparse.dot(lhs.tostype('csr'), rhs.tostype('row_sparse'), transpose_a=trans_lhs)
assert same(dns_out.asnumpy(), sps_out.asnumpy())
density = [1.00, 0.50, 0.01]
for lhs_d in density:
lhs_shape = rand_shape_2d(50, 200)
rhs_d = 1
test_dot_csr(lhs_shape, (lhs_shape[1], 1), 'default', False, lhs_d, rhs_d) # test gpu SpMV
test_dot_csr(lhs_shape, (lhs_shape[0], 1), 'default', True, lhs_d, rhs_d) # (vector kernel)
test_dot_csr(lhs_shape, (lhs_shape[1], rnd.randint(5, 10)), 'default', False, lhs_d, rhs_d) # test gpu SpMM
test_dot_csr(lhs_shape, (lhs_shape[0], rnd.randint(5, 10)), 'default', True, lhs_d, rhs_d) # (scalar kernel)
test_dot_dns_csr(lhs_shape, (lhs_shape[1], rnd.randint(50, 200)), lhs_d, lhs_d)
for rhs_d in density:
test_dot_csr(lhs_shape, (lhs_shape[1], rnd.randint(1, 10)), 'row_sparse', False, lhs_d, rhs_d)
test_dot_csr(lhs_shape, (lhs_shape[0], rnd.randint(1, 10)), 'row_sparse', True, lhs_d, rhs_d)
test_sparse_dot_zero_output(rand_shape_2d(50, 200), False, 40)
test_sparse_dot_zero_output(rand_shape_2d(50, 200), True, 40)
@with_seed()
def test_sparse_slice():
def check_csr_slice(shape, slice_input):
storage_type = 'csr'
B, _ = rand_sparse_ndarray(shape, storage_type)
np = B.asnumpy()
begin = rnd.randint(0, B.shape[0] - 1)
end = rnd.randint(begin + 1, B.shape[0])
nd_slice = mx.nd.crop(B, begin=begin, end=end)
assert same(nd_slice.asnumpy(), np[begin:end]), (nd_slice.asnumpy(), np[begin:end])
shape = (rnd.randint(7, 15), rnd.randint(1, 10))
check_csr_slice(shape, True)
check_csr_slice(shape, False)
@with_seed()
def test_sparse_retain():
def check_sparse_retain(shape, density, index_type=np.int64):
num_rows = shape[0]
rsp, _ = rand_sparse_ndarray(shape=shape, stype='row_sparse', density=density)
length = np.random.randint(1, num_rows + 1)
idx = random_sample(list(range(0, num_rows)), length)
idx.sort()
dns = rsp.asnumpy()
tensor_retained_expected = np.zeros(shape)
for i in idx:
tensor_retained_expected[i][:] = dns[i]
indices = mx.nd.array(idx, dtype=index_type)
rsp_retained = mx.nd.sparse.retain(rsp, indices=indices)
assert same(tensor_retained_expected, rsp_retained.asnumpy())
# check numeric gradient
data = mx.symbol.Variable('data')
idx = mx.symbol.Variable('indices')
sym = mx.sym.sparse.retain(data=data, indices=idx)
check_numeric_gradient(sym, [rsp, indices], grad_nodes=['data'],
grad_stype_dict={'data': 'row_sparse'})
shape = rand_shape_2d()
shape_3d = rand_shape_3d()
densities = [0.01, 0.5, 1.0]
index_types = [np.float32, np.int32, np.int64]
for density in densities:
for itype in index_types:
check_sparse_retain(shape, density, itype)
check_sparse_retain(shape_3d, density, itype)
@with_seed()
def test_sparse_unary_with_numerics():
def check_sparse_simple(name, stype, mxnet_func, forward_numpy_call,
backward_numpy_call, output_grad_stype=None,
backward_is_use_output=False):
if output_grad_stype is None:
output_grad_stype = stype
expected_result_type, expected_grad_result_type = \
get_fw_bw_result_types_2(forward_numpy_call, stype, backward_numpy_call, output_grad_stype)
if backward_is_use_output is True:
expected_grad_result_type = expected_result_type
shape = (3, 4)
data = mx.symbol.Variable("data")
grad_stypes = {'data' : expected_grad_result_type}
y = mxnet_func(data)
if stype == 'default':
xa = np.random.uniform(low=-1.0, high=1.0, size=shape)
xa_np = xa
else:
xa = create_sparse_array(shape, stype, data_init=None, rsp_indices=[1],
modifier_func=lambda a: a - 0.5,
shuffle_csr_indices=True)
xa_np = xa.asnumpy()
if output_grad_stype != 'default':
out_grad = create_sparse_array(shape, output_grad_stype, data_init=None,
rsp_indices=[1, 2],
modifier_func=lambda a: a - 0.5,
shuffle_csr_indices=True)
out_grad_np = out_grad.asnumpy()
else:
out_grad_np = np.ones(xa.shape)
out_grad = mx.nd.array(out_grad_np)
output_np = forward_numpy_call(xa_np)
input_grad_np = backward_numpy_call(output_np, out_grad_np)
outputs = check_symbolic_forward(y, [xa], [output_np])
output = outputs[0]
assert output.stype == expected_result_type
input_grad_dict = check_symbolic_backward(y, location=[xa], out_grads=[out_grad],
expected=[input_grad_np],
grad_stypes=grad_stypes)
inp_grad = input_grad_dict["data"]
assert inp_grad.stype == expected_grad_result_type
def check_sparse_function(name, mxnet_func, forward_numpy_call, backward_numpy_call,
backward_is_use_output=False):
check_sparse_simple(name, 'default', mxnet_func, forward_numpy_call, backward_numpy_call)
for output_grad_stype in [None, "row_sparse", "default"]:
check_sparse_simple(name, 'row_sparse', mxnet_func, forward_numpy_call, backward_numpy_call,
output_grad_stype=output_grad_stype,
backward_is_use_output=backward_is_use_output)
check_sparse_function('relu',
lambda x: mx.sym.relu(x),
lambda x: np.maximum(x, 0.0),
lambda output, outg: outg * assign_each(output, lambda x: x > 0.0), backward_is_use_output=True)
check_sparse_function('sigmoid',
lambda x: mx.sym.sigmoid(x),
lambda x: np.divide(1.0, (1.0 + np.exp(-x))),
lambda output, outg: outg * assign_each(output, lambda x: x * (1.0 - x)),
backward_is_use_output=True)
@with_seed()
def test_sparse_nd_zeros():
def check_sparse_nd_zeros(stype, shape):
zero = mx.nd.zeros(shape)
sparse_zero = mx.nd.zeros(shape=shape, stype=stype)
assert_almost_equal(sparse_zero.asnumpy(), zero.asnumpy())
shape = rand_shape_2d()
check_sparse_nd_zeros('row_sparse', shape)
check_sparse_nd_zeros('csr', shape)
check_sparse_nd_zeros('default', shape)
@with_seed()
def test_sparse_nd_zeros_like():
def check_sparse_nd_zeros_like(stype, shape):
zero = mx.nd.zeros(shape, stype=stype)
zero_like = mx.nd.sparse.zeros_like(zero)
assert_almost_equal(zero.asnumpy(), zero_like.asnumpy())
shape = rand_shape_2d()
check_sparse_nd_zeros_like('row_sparse', shape)
check_sparse_nd_zeros_like('csr', shape)
@with_seed()
def test_sparse_axis_operations():
def test_variations(func_name):
dim0 = 30
dim1 = 100
axes = [0, 1]
densities = [0, 0.5, 1]
for density in densities:
shape = rand_shape_2d(dim0, dim1)
csr_array = rand_ndarray(shape=shape, stype='csr', density=density)
dns = csr_array.tostype('default')
for axis in axes:
ret = func_name(csr_array, axis=axis)
assert ret.stype == 'default'
ret_expected = func_name(dns, axis=axis)
assert_almost_equal(ret.asnumpy(), ret_expected.asnumpy())
def test_fallback(func_name, axis=0, keepdims=True, exclude=True):
dim0 = 30
dim1 = 100
shape = rand_shape_2d(dim0, dim1)
csr_array = rand_ndarray(shape=shape, stype='csr', density=0.01)
ret= func_name(csr_array, axis=axis, keepdims=keepdims,
exclude=exclude)
test_variations(mx.nd.sum)
test_fallback(mx.nd.sum, axis=0, keepdims=True, exclude=True)
test_variations(mx.nd.mean)
test_fallback(mx.nd.mean, axis=0, keepdims=True, exclude=True)
@with_seed()
def test_sparse_square_sum():
dim0 = 30
dim1 = 30
axes = [0, 1]
keepdims = [False, True]
densities = [0, 0.01, 0.2, 0.5, 1.0]
for density in densities:
shape = rand_shape_2d(dim0, dim1)
rsp = rand_ndarray(shape, 'row_sparse', density)
dns = rsp.tostype('default')
for axis in axes:
for keepdim in keepdims:
ret = mx.nd._internal._square_sum(rsp, axis=axis, keepdims=keepdim)
if axis == 1 and keepdim:
assert ret.stype == 'row_sparse'
else:
assert ret.stype == 'default'
ret_expected = mx.nd.sum(dns*dns, axis=axis, keepdims=keepdim)
# check forward result
assert_almost_equal(ret.asnumpy(), ret_expected.asnumpy())
rsp_data = mx.sym.Variable('data', stype='row_sparse')
test = mx.symbol._internal._square_sum(rsp_data, axis=axis, keepdims=keepdim)
# check symbolic backward since ograd can be an rsp
# and cannot be checked through check_numeric_gradient
# because it will add a loss layer as the output layer
# which makes ograd of the square_sum dense
if axis == 1 and keepdim:
dns_data = mx.sym.Variable('data')
baseline = mx.sym.sum(mx.sym.square(dns_data), axis=axis, keepdims=keepdim)
igrad_expected = mx.nd.empty(dns.shape)
baseline_exec = baseline.bind(default_context(), args=[dns],
args_grad=[igrad_expected])
baseline_exec.forward(is_train=True)
baseline_exec.backward([ret_expected])
# check backward when ograd is row sparse
check_symbolic_backward(test, [rsp], [ret_expected.tostype('row_sparse')],
[igrad_expected.asnumpy()], grad_stypes={'data': 'row_sparse'})
# check backward when ograd is dense
# the stype of output of the square_sum is deteremined in symbol binding stage.
# The ograd stype of the last layer is the same as the output stype of the last layer.
# Need to add one more layer after square_sum to trigger the kernel for ograd
# with default stype in square_sum op.
baseline1 = baseline + 1
baseline_exec1 = baseline1.bind(default_context(), args=[dns],
args_grad=[igrad_expected])
baseline_exec1.forward(is_train=True)
baseline_exec1.backward([ret_expected])
test1 = test + 1
check_symbolic_backward(test1, [rsp], [ret_expected], [igrad_expected.asnumpy()],
grad_stypes={'data': 'row_sparse'})
# check numeric gradient
check_numeric_gradient(test, [rsp], grad_stype_dict={'data': 'row_sparse'},
atol=1e-2, rtol=0.1)
@with_seed()
def test_sparse_storage_fallback():
""" test operators which don't implement FComputeEx or FStatefulComputeEx """
def check_broadcast_add(shape, lhs_stype, rhs_stype):
lhs = mx.symbol.Variable('lhs', stype=lhs_stype)
rhs = mx.symbol.Variable('rhs', stype=rhs_stype)
lhs_nd = rand_ndarray(shape, lhs_stype)
rhs_nd = rand_ndarray(shape, rhs_stype)
lhs_dns = mx.nd.cast_storage(lhs_nd, stype='default')
rhs_dns = mx.nd.cast_storage(rhs_nd, stype='default')
out_dns = (lhs_dns + rhs_dns).asnumpy()
test = mx.symbol.broadcast_add(lhs, rhs)
location = {'lhs': lhs_nd, 'rhs': rhs_nd}
check_symbolic_forward(test, location, [out_dns])
check_numeric_gradient(test, location)
check_symbolic_backward(test, location, [out_dns], [out_dns, out_dns])
def np_softmax(x, axis=-1):
# fix for old numpy on Travis not supporting keepdims
x = x - np.max(x, axis=axis, keepdims=True)
x = np.exp(x)
x /= np.sum(x, axis=axis, keepdims=True)
return x
def check_softmax_with_shape(lhs_stype, rhs_stype, shape, preserve_shape=False):
# bind with label
ctx = default_context()
X = mx.symbol.Variable('X', stype=lhs_stype)
L = mx.symbol.Variable('L', stype=rhs_stype)
Y = mx.symbol.SoftmaxOutput(data=X, label=L, preserve_shape=preserve_shape)
x = rand_ndarray(shape, lhs_stype)
l = rand_ndarray(shape, rhs_stype)
l[:] = np_softmax(l.asnumpy())
grad = mx.nd.empty(shape, ctx=ctx)
exec1 = Y.bind(ctx, args = [x, l], args_grad = {'X': grad})
exec1.forward(is_train=True)
out = exec1.outputs[0].asnumpy()
assert_almost_equal(out, np_softmax(x.asnumpy()), rtol=1e-4)
exec1.backward()
assert_almost_equal(grad.asnumpy(), np_softmax(x.asnumpy()) - l.asnumpy(),
rtol=1e-3, atol=1e-4)
def check_concat(shape, lhs_stype, rhs_stype):
x = mx.symbol.Variable('x', stype=lhs_stype)
w = mx.symbol.Variable('w', stype=rhs_stype)
test = mx.sym.Concat(x, w)
x_nd = rand_ndarray(shape, lhs_stype)
w_nd = rand_ndarray(shape, rhs_stype)
location = {'x': x_nd, 'w': w_nd}
check_numeric_gradient(test, location)
def check_operator_with_temp_resource(shape, stype):
x = mx.symbol.Variable('x', stype=stype)
test = mx.sym.sum(x)
x_nd = rand_ndarray(shape, stype)
location = {'x': x_nd}
check_numeric_gradient(test, location)
shape = rand_shape_2d()
stypes = ['default', 'csr', 'row_sparse']
for lhs in stypes:
check_operator_with_temp_resource(shape, lhs)
for rhs in stypes:
check_broadcast_add(shape, lhs, rhs)
check_concat(shape, lhs, rhs)
check_softmax_with_shape(lhs, rhs, shape, preserve_shape=False)
check_softmax_with_shape(rhs, rhs, shape, preserve_shape=True)
@with_seed()
def test_sparse_elementwise_sum():
def check_sparse_elementwise_sum_with_shape(stype, shape, n):
# forward
inputs = [mx.symbol.Variable('arg%d' % i) for i in range(n)]
out = mx.symbol.sparse.add_n(*inputs, name='esum')
arr = []
arr_grad = [mx.nd.empty(shape, stype=stype) for _ in range(n)]
densities = [0, 0.01, 0.5, 1.0]
for i in range(n):
arr.append(rand_ndarray(shape, stype, densities[np.random.randint(0, len(densities))]))
exec1 = out.bind(default_context(),
args=arr,
args_grad=arr_grad)
exec1.forward(is_train=True)
out1 = exec1.outputs[0].asnumpy()
out = sum(a.asnumpy() for a in arr)
assert_almost_equal(out, out1)
out_grad = mx.nd.empty(shape)
out_grad[:] = np.random.uniform(-10, 10, shape)
# backward
exec1.backward([out_grad])
for a in arr_grad:
assert_almost_equal(a.asnumpy(), out_grad.asnumpy())
for dim in range(2, 4):
shape = tuple(np.random.randint(5, 10, size=dim))
check_sparse_elementwise_sum_with_shape('row_sparse', shape, np.random.randint(1, 9))
@with_seed()
def test_sparse_embedding():
''' test sparse embedding operator '''
def check_sparse_embedding(in_dim, out_dim, batch, densities, deterministic):
# init executor
data = mx.sym.Variable("data")
weight = mx.sym.Variable("embed_weight", stype='row_sparse')
embed = mx.sym.contrib.SparseEmbedding(data=data, weight=weight, input_dim=in_dim,
output_dim=out_dim, deterministic=deterministic,
name="embed")
grad_req = {'data': 'null', 'embed_weight': 'write'}
exe_test = embed.simple_bind(default_context(), grad_req=grad_req, data=(batch,))
arg_map = dict(zip(embed.list_arguments(), exe_test.arg_arrays))
grad_map = dict(zip(embed.list_arguments(), exe_test.grad_arrays))
# init data
np_data = np.random.randint(low=0, high=in_dim, size=batch)
np_onehot = np.zeros((batch, in_dim)).astype(np.float32)
np_onehot[np.arange(batch), np_data] = 1.0
arg_map["data"][:] = np_data
# init grad
np_grad = np.random.uniform(-1, 1, exe_test.outputs[0].shape)
grad = mx.nd.zeros(np_grad.shape)
grad[:] = np_grad
# weight
weight = arg_map["embed_weight"]
for density in densities:
# update weight based on density
weight[:] = rand_ndarray(weight.shape, 'row_sparse', density=density)
# check forward
exe_test.forward(is_train=True)
assert_almost_equal(exe_test.outputs[0].asnumpy(), np.dot(np_onehot, weight.asnumpy()), atol=1e-4)
# check backward
exe_test.backward([grad])
assert_almost_equal(grad_map["embed_weight"].asnumpy(), np.dot(np_onehot.T, grad.asnumpy()), atol=1e-4)
densities = [0, 0.5, 1]
in_dim = 50
out_dim = 3
batch = 8
check_sparse_embedding(in_dim, out_dim, batch, densities, True)
check_sparse_embedding(in_dim, out_dim, batch, densities, False)
@with_seed()
def test_sparse_broadcast_mul_div():
def check_broadcast_mul(mx_lhs, mx_rhs, np_lhs, np_rhs, dtype):
assert_almost_equal(mx.nd.sparse.multiply(mx_lhs, mx_rhs).asnumpy(), np.multiply(np_lhs, np_rhs), atol=1e-4)
def check_broadcast_div(mx_lhs, mx_rhs, np_lhs, np_rhs, dtype):
assert_almost_equal(mx.nd.sparse.divide(mx_lhs, mx_rhs).asnumpy(), np.divide(np_lhs, np_rhs), atol=1e-4)
stype = 'csr'
shape = rand_shape_2d()
num_rows = shape[0]
num_cols = shape[1]
for density in [0.1 * i for i in range(10)]:
mx_lhs = rand_ndarray(shape, stype, density)
np_lhs = mx_lhs.asnumpy()
mx_rhs_row_2D = rand_ndarray((1, num_cols), 'default')
mx_rhs_row_1D = mx_rhs_row_2D.reshape((num_cols))
mx_rhs_col = rand_ndarray((num_rows, 1), 'default')
mx_rhs_scalar_2D = rand_ndarray((1, 1), 'default')
mx_rhs_scalar_1D = mx_rhs_scalar_2D.reshape((1, ))
for mx_rhs in [mx_rhs_row_2D, mx_rhs_row_1D, mx_rhs_col, mx_rhs_scalar_2D, mx_rhs_scalar_1D]:
np_rhs = mx_rhs.asnumpy()
check_broadcast_mul(mx_lhs, mx_rhs, np_lhs, np_rhs, np.float32)
check_broadcast_div(mx_lhs, mx_rhs, np_lhs, np_rhs, np.float32)
@with_seed()
def test_scatter_ops():
def csr_get_seen_points(name, csr_array, verbose=False):
"""Get a unique list of points int he CSR array as well as a
corresponding parallel list of points and values"""
seen_points = set()
seen_point_list = list()
values = list()
row_count = csr_array.shape[0]
row_pointers = csr_array.indptr.asnumpy()
col_indexes = csr_array.indices.asnumpy()
data = csr_array.data.asnumpy()
for row in range(row_count):
start_pos = row_pointers[row]
end_pos = row_pointers[row + 1]
for col_index in range(start_pos, end_pos):
col = col_indexes[col_index]
val = data[col_index]
if verbose is True:
print("{}: (row, col = ({}, {}) = {}".format(name, row, col, val))
seen_points.add((row, col))
seen_point_list.append((row, col))
values.append(val)
return seen_points, values, seen_point_list
def check_scatter_ops(name, shape, lhs_stype, rhs_stype, forward_mxnet_call, forward_numpy_call,
density=0.25, rhs_is_scalar=False, verbose=False):
lhs = mx.symbol.Variable('lhs', stype=lhs_stype)
if rhs_is_scalar is False:
rhs = mx.symbol.Variable('rhs', stype=rhs_stype)
if verbose is True:
print(name)
if lhs_stype != 'default':
lhs_nd = create_sparse_array_zd(
shape, lhs_stype, density=density,
rsp_indices=gen_rsp_random_indices(
shape,
density=density,
force_indices=[(shape[0]/2)] # force at least one overlap
))
else:
lhs_nd = rand_ndarray(shape, 'default')
if rhs_is_scalar is False:
if rhs_stype != 'default':
rhs_nd = create_sparse_array_zd(
shape, rhs_stype, density=density,
rsp_indices=gen_rsp_random_indices(
shape,
density=density,
force_indices=[(shape[0]/2)] # force at least one overlap
))
else:
rhs_nd = rand_ndarray(shape, 'default')
else:
rhs_nd = 9
rhs = rhs_nd
lhs_np = lhs_nd.asnumpy()
rhs_np = rhs_nd if rhs_is_scalar is True else rhs_nd.asnumpy()
if verbose is True:
print("lhs = {}".format(lhs_np))
print("rhs = {}".format(rhs_np))
out_np = forward_numpy_call(lhs_np, rhs_np)
if verbose is True:
print("Numpy: out_np = {}".format(out_np))
location = {'lhs': lhs_nd, 'rhs': rhs_nd}
out = forward_mxnet_call(lhs, rhs)
exe_test = out.bind(default_context(), args=location)
exe_test.forward(is_train=False)
out_nd = exe_test.outputs[0]
if verbose is True:
print("Sym: out_nd = {}".format(out_nd.asnumpy()))
# For row_sparse, check that rows only exist for rows that are
# either int lhs or rhs, and if they exist, they should equal
# the numpy values
if lhs_stype == 'default':
almost_equal(out_nd.asnumpy(), out_np, equal_nan=True)
elif lhs_stype == 'row_sparse':
seen_rows = set()
indices = lhs_nd.indices.asnumpy()
for i in range(len(indices)):
seen_rows.add(indices[i])
assert len(out_nd.indices.asnumpy()) == len(seen_rows)
out_nd_np = out_nd.asnumpy()
for row in seen_rows:
row_nd = out_nd_np[row]
row_np = out_np[row]
almost_equal(row_nd, row_np, equal_nan=True)
elif lhs_stype == 'csr' and rhs_is_scalar is False:
almost_equal(out_nd.asnumpy(), out_np, equal_nan=True)
else:
assert rhs_is_scalar
lhs_seen_points, _, _ = csr_get_seen_points("lhs", lhs_nd, verbose)
if rhs_is_scalar is False:
rhs_seen_points, _, _ = csr_get_seen_points("rhs", rhs_nd, verbose)
else:
rhs_seen_points = set()
input_seen_points = lhs_seen_points.union(rhs_seen_points)
out_seen_pounts, out_values, seen_point_list = csr_get_seen_points("out_nd", out_nd, verbose)
# Some may have been zero
assert len(out_seen_pounts) <= len(input_seen_points)
out_nd_np = out_nd.asnumpy()
val_index = 0
for row_col in seen_point_list:
row = row_col[0]
col = row_col[1]
val = out_values[val_index]
val_np = out_nd_np[row, col]
almost_equal(val, val_np, equal_nan=True)
val_index += 1
shape = (10, 5)
for lhs_stype in ['row_sparse', 'default', 'csr']:
for rhs_stype in ['row_sparse', 'default', 'csr']:
print("op: {}, lhs_stype: {}, rhs_stype: {}".format('_scatter_elemwise_div',
lhs_stype, rhs_stype))
check_scatter_ops('_scatter_elemwise_div', shape, lhs_stype, rhs_stype,
lambda l, r: mx.sym._internal._scatter_elemwise_div(l, r),
lambda l, r: l / r,
verbose=False)
for lhs_stype in ['row_sparse', 'default', 'csr']:
print("op: {}, lhs_stype: {}".format('_scatter_plus', lhs_stype))
check_scatter_ops('_scatter_plus', shape, lhs_stype, 'scalar',
lambda l, r: mx.sym._internal._scatter_plus_scalar(l, r),
lambda l, r: l + r,
rhs_is_scalar=True, verbose=False)
print("op: {}, lhs_stype: {}".format('_scatter_minus', lhs_stype))
check_scatter_ops('_scatter_minus', shape, lhs_stype, 'scalar',
lambda l, r: mx.sym._internal._scatter_minus_scalar(l, r),
lambda l, r: l + r,
rhs_is_scalar=True, verbose=False, density=0.5)
@with_seed()
def test_mkldnn_sparse():
# This test is trying to create a race condition describedd in
# https://github.com/apache/incubator-mxnet/issues/10189
arr = mx.nd.random.uniform(shape=(10, 10, 32, 32))
weight1 = mx.nd.random.uniform(shape=(10, 10, 3, 3))
arr = mx.nd.Convolution(data=arr, weight=weight1, no_bias=True, kernel=(3, 3), num_filter=10)
rs_arr = mx.nd.sparse.row_sparse_array((mx.nd.zeros_like(arr), np.arange(arr.shape[0])))
weight2 = mx.nd.random.uniform(shape=(10, np.prod(arr.shape[1:4])))
fc_res = mx.nd.FullyConnected(data=arr, weight=weight2, no_bias=True, num_hidden=10)
sum_res = mx.nd.elemwise_sub(arr, rs_arr)
res1 = np.dot(mx.nd.flatten(sum_res).asnumpy(), weight2.asnumpy().T)
print(res1 - fc_res.asnumpy())
almost_equal(res1, fc_res.asnumpy())
@with_seed()
def test_sparse_nd_where():
def get_forward_expected_output(condition, x, y):
original_shape = x.shape
out = np.zeros(original_shape)
if condition.shape == x.shape:
for index, c in np.ndenumerate(condition):
if c != 0:
out[index] = x[index]
else:
out[index] = y[index]
else:
raise RuntimeError("Invalid condition shape for where op")
out = out.reshape(original_shape)
return out
def get_forward_inputs_same_shape(shape):
condition_np = np.random.randint(0, 2, np.prod(shape)).reshape(shape)
x_np = np.random.randint(1, 6, np.prod(shape)).reshape(shape)
y_np = np.random.randint(7, 11, np.prod(shape)).reshape(shape)
return condition_np, x_np, y_np
def get_backward_input(shape):
return np.random.randint(20, 30, np.prod(shape)).reshape(shape)
def get_backward_expected_outputs(grad_in, condition):
shape = grad_in.shape
grad_cond = np.zeros(condition.shape)
grad_x = np.empty(shape)
grad_y = np.empty(shape)
for index, c in np.ndenumerate(condition):
if 0 != c:
grad_x[index] = grad_in[index]
grad_y[index] = 0
else:
grad_x[index] = 0
grad_y[index] = grad_in[index]
return grad_cond, grad_x, grad_y
def test_where_helper(shape):
condition_np, x_np, y_np = get_forward_inputs_same_shape(shape)
out_expected = get_forward_expected_output(condition_np, x_np, y_np)
grad_in_np = get_backward_input(shape)
grad_expected_cond, grad_expected_x, grad_expected_y \
= get_backward_expected_outputs(grad_in_np, condition_np)
condition = mx.sym.Variable('condition', stype='csr')
x = mx.sym.Variable('x')
y = mx.sym.Variable('y')
grad_in_mx = mx.nd.array(grad_in_np, dtype=np.int32)
where_sym = mx.sym.where(condition, x, y)
# test req='write'
where_exe_write = where_sym.simple_bind(ctx=default_context(),
condition=condition_np.shape,
x=x_np.shape, y=y_np.shape,
grad_req='write')
# test forward req='write'
cond_nd = mx.nd.array(condition_np).tostype('csr')
outputs = where_exe_write.forward(is_train=True, \
condition=cond_nd, x=x_np, y=y_np)
assert same(outputs[0].asnumpy(), out_expected)
# test backward req='write'
where_exe_write.backward(grad_in_mx)
assert same(where_exe_write.grad_dict['x'].asnumpy(), grad_expected_x)
assert same(where_exe_write.grad_dict['y'].asnumpy(), grad_expected_y)
assert same(where_exe_write.grad_dict['condition'].asnumpy(), grad_expected_cond)
# test req='add'
x_grad_init = np.random.randint(30, 40, np.prod(shape)).reshape(shape)
y_grad_init = np.random.randint(40, 50, np.prod(shape)).reshape(shape)
where_exe_add = where_sym.simple_bind(ctx=default_context(),
condition=cond_nd.shape,
x=x_np.shape, y=y_np.shape,
grad_req='add')
where_exe_add.grad_dict['x'][:] = x_grad_init
where_exe_add.grad_dict['y'][:] = y_grad_init
# test forward req='add'
outputs = where_exe_add.forward(is_train=True, condition=cond_nd, x=x_np, y=y_np)
assert same(outputs[0].asnumpy(), out_expected)
def test_where_numeric_gradient(shape):
condition = mx.sym.Variable('condition', stype='csr')
x = mx.sym.Variable('x')
y = mx.sym.Variable('y')
where_sym = mx.sym.where(condition, x, y)
condition_np, x_np, y_np = get_forward_inputs_same_shape(shape)
check_numeric_gradient(where_sym, [condition_np, x_np, y_np], grad_nodes=['x', 'y'])
test_where_helper((5, 9))
test_where_numeric_gradient((5, 9))
@with_seed()
def test_sparse_quadratic_function():
def f(x, a, b, c):
return a * x**2 + b * x + c
def check_sparse_quadratic_function(a, b, c, expected_stype):
# check forward and compare the result with dense op
ndim = 2
shape = rand_shape_nd(ndim, 5)
data = rand_ndarray(shape=shape, stype='csr')
data_np = data.asnumpy()
expected = f(data_np, a, b, c)
output = mx.nd.contrib.quadratic(data, a=a, b=b, c=c)
assert(output.stype == expected_stype)
assert_almost_equal(output.asnumpy(), expected)
a = np.random.random_sample()
b = np.random.random_sample()
check_sparse_quadratic_function(a, b, 0.0, 'csr')
check_sparse_quadratic_function(a, b, 1.0, 'default')
if __name__ == '__main__':
import nose
nose.runmodule()
| {
"content_hash": "34fd96b2a333ab1d5fa29a9575a1cb44",
"timestamp": "",
"source": "github",
"line_count": 1968,
"max_line_length": 122,
"avg_line_length": 47.8714430894309,
"alnum_prop": 0.4781925677468661,
"repo_name": "CodingCat/mxnet",
"id": "347948665461e8d0fc726da9ebe357d6a0635c5f",
"size": "94997",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/python/unittest/test_sparse_operator.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "1731"
},
{
"name": "Batchfile",
"bytes": "13130"
},
{
"name": "C",
"bytes": "118418"
},
{
"name": "C++",
"bytes": "5034573"
},
{
"name": "CMake",
"bytes": "80188"
},
{
"name": "Cuda",
"bytes": "866667"
},
{
"name": "Groovy",
"bytes": "1020"
},
{
"name": "Java",
"bytes": "122297"
},
{
"name": "Jupyter Notebook",
"bytes": "1275177"
},
{
"name": "Makefile",
"bytes": "54557"
},
{
"name": "Matlab",
"bytes": "34903"
},
{
"name": "Perl",
"bytes": "1256723"
},
{
"name": "Perl 6",
"bytes": "7280"
},
{
"name": "Python",
"bytes": "5349689"
},
{
"name": "R",
"bytes": "311001"
},
{
"name": "Scala",
"bytes": "988042"
},
{
"name": "Shell",
"bytes": "268407"
},
{
"name": "Smalltalk",
"bytes": "43774"
}
],
"symlink_target": ""
} |
"""XmlDumper server class for uicd.
This class does the following things:
1. check&install&start xml dumper server on Device
2. fetches current xml.
"""
import json
import logging
import sys
import time
from .adb import Adb
from .constant import DEFAULT_APK_DUMPER_VERSION
from .constant import DEFAULT_DUMPER_PORT
# pylint: disable=g-import-not-at-top
if sys.version_info[0] <= 2:
import httplib
else:
import http.client
# pylint: enable=g-import-not-at-top
class AndroidDeviceDriver(object):
"""Built-in Android Device Driver for python in uicd.
Attributes:
runner_prefix: runner prefix for server initializer
adb: adb command wrapper for adb commands
uicd_base_folder: uicd base folder for xml apk if needed
xml_dumper_port: port where xml dumper server is running
device_dumper_port: port where xml dumper server is running on device
drag_in_process: if a drag move is in progress
xml_dumper_version: version of xml dumper
use_xml_dumper: if we will get xml via dumper apk or adb
"""
XML_DUMPER_PACKAGE_PREFIX = "com.google.uicd.xmldumper"
MINIMUM_API_LEVEL_FOR_PERMISSION_GRANT_FLAG = 23
UICD_DEP_FOLDER_PATH = "deps"
XML_DUMPER_APK_FOLDER_NAME = "xmldumper_apks"
PACKAGE_NOT_FOUND = "package not found"
DUMP_XML_ENDPOINT = "/action/dump"
LOCALHOST = "localhost"
DRAG_START_ENDPOINT = "/action/touch/down"
DRAG_MOVE_ENDPOINT = "/action/touch/move"
DRAG_STOP_ENDPOINT = "/action/touch/up"
MOTION_EVENT_ENDPOINT = "/action/touch/motion"
_XML_DUMPER_RESTART_DELAY_IN_SEC = 2
def __init__(self,
uicd_base_folder,
adb_path=None,
serial=None,
xml_dumper_port=DEFAULT_DUMPER_PORT,
device_dumper_port=DEFAULT_DUMPER_PORT,
xml_dumper_version=DEFAULT_APK_DUMPER_VERSION,
runner_prefix="androidx",
use_xml_dumper=True):
self.runner_prefix = runner_prefix
self.adb = Adb(adb_path, serial)
self.uicd_base_folder = uicd_base_folder
self.xml_dumper_port = xml_dumper_port
self.device_dumper_port = device_dumper_port
self.drag_in_process = False
self.xml_dumper_version = xml_dumper_version
self.use_xml_dumper = use_xml_dumper
def start_xml_dumper_server(self):
"""Starts xml dumper server on device if not initialized yet.
Returns:
A subprocess.Popen instance which contains the xml dumper server starting
command.
Raises:
OSError: if adb is not found in $ANDROID_HOME path or $ANDROID_HOME is not
set.
"""
logging.info("start_xml_dumper_server")
version = self.get_xml_dumper_version()
if version == self.PACKAGE_NOT_FOUND:
api_level = self.adb.exec_adb_cmd(
"shell getprop ro.build.version.sdk").communicate()[0].decode("utf-8")
self.install_xml_dumper_server_apk(api_level)
version = self.get_xml_dumper_version()
self.adb.forward(self.xml_dumper_port, self.device_dumper_port)
start_xml_dumper_prefix = "shell am instrument -w -e debug false -e class "
dumper_server_apk = "'{package_prefix}.DumperServerInstrumentation#startServer'".format(
package_prefix=self.XML_DUMPER_PACKAGE_PREFIX)
dumper_runner = "{runner_prefix}.test.runner.AndroidJUnitRunner &".format(
runner_prefix=self.runner_prefix)
if self.compare_xml_dumper_apk_version(version, DEFAULT_APK_DUMPER_VERSION):
dumper_test_apk = " {test_prefix}/".format(
test_prefix=self.XML_DUMPER_PACKAGE_PREFIX)
else:
dumper_test_apk = " {test_prefix}.test/".format(
test_prefix=self.XML_DUMPER_PACKAGE_PREFIX)
start_xml_dumper_server_command = start_xml_dumper_prefix + dumper_server_apk + dumper_test_apk + dumper_runner
self.adb.exec_adb_cmd(start_xml_dumper_server_command)
def stop_xml_dumper_server(self):
"""Stops xml dumper server on device.
Returns:
A subprocess.Popen instance which contains the xml dumper server starting
command.
"""
self.adb.exec_adb_cmd("shell am force-stop {xmldumper_prefix}".format(
xmldumper_prefix=self.XML_DUMPER_PACKAGE_PREFIX)).wait()
self.adb.exec_adb_cmd(
"shell am force-stop {xmldumper_prefix}.test".format(
xmldumper_prefix=self.XML_DUMPER_PACKAGE_PREFIX)).wait()
def restart_xml_dumper_server(self):
"""Restart the xml dumper server on device.
Returns:
A subprocess.Popen instance which contains the xml dumper server starting
command.
Raises:
OSError: if adb is not found in $ANDROID_HOME path or $ANDROID_HOME is not
set.
"""
self.stop_xml_dumper_server()
self.start_xml_dumper_server()
time.sleep(self._XML_DUMPER_RESTART_DELAY_IN_SEC)
def install_xml_dumper_server_apk(self, api_level):
"""Install xml dumper server apk on the device.
Args:
api_level: Api level from adb.
Raises:
OSError: if adb is not found in $ANDROID_HOME path or $ANDROID_HOME is not
set.
"""
if self.uicd_base_folder is None:
raise EnvironmentError(
"UICD base folder is not set. Can't find xml dumper packages")
if int(api_level) > self.MINIMUM_API_LEVEL_FOR_PERMISSION_GRANT_FLAG:
install_cmd = "install -r -d -t -g "
else:
install_cmd = "install -r -d -t "
install_path = "{install_cmd}{base}/{dep}/{apk}".format(
install_cmd=install_cmd,
base=self.uicd_base_folder,
dep=self.UICD_DEP_FOLDER_PATH,
apk=self.XML_DUMPER_APK_FOLDER_NAME)
install_cmd1 = "{install_path}/uicd-xmldumper-server-v{version}.apk".format(
install_path=install_path, version=self.xml_dumper_version)
if not self.compare_xml_dumper_apk_version(self.xml_dumper_version,
DEFAULT_APK_DUMPER_VERSION):
install_cmd2 = "{install_path}/uicd-xmldumper-server-test-v{version}.apk".format(
install_path=install_path, version=self.xml_dumper_version)
self.adb.exec_adb_cmd(install_cmd2).wait()
self.adb.exec_adb_cmd(install_cmd1).wait()
def compare_xml_dumper_apk_version(self, current_version, target_version):
"""Compares xml dumper apk version against each other.
Args:
current_version: Version string in form of "1.0.0".
target_version: Target Version string in form of "1.0.0".
Returns:
True if version1 is larger than or equal to target version,
otherwise false.
"""
version_number1 = int(current_version.split(".")[0]) * 100 + int(
current_version.split(
".")[1]) * 10 + int(current_version.split(".")[2])
version_number2 = int(target_version.split(".")[0]) * 100 + int(
target_version.split(
".")[1]) * 10 + int(target_version.split(".")[2])
return int(version_number1) >= int(version_number2)
def get_xml_dumper_version(self):
"""Function to check for xml_dumper_version.
Returns:
A string of version info, 1.0.0
Raises:
OSError: if adb is not found in $ANDROID_HOME path or $ANDROID_HOME is not
set.
"""
get_dumper_version_cmd = "shell dumpsys package %s | grep versionName" % (
self.XML_DUMPER_PACKAGE_PREFIX)
output = self.adb.exec_adb_cmd(get_dumper_version_cmd).communicate(
)[0].decode("utf-8").strip().splitlines()
if output:
# installed dumper Version from adb will be something like this:
# "versionName=1.0.0"
return output[0].split("=")[1]
else:
return self.PACKAGE_NOT_FOUND
def fetch_current_xml(self):
"""Function to fecth current xml with retry.
If xml dumper server haven't started, the first attempt will fail
and restart the server.
Returns:
A json string of xml info.
Raises:
OSError: Requrest is invalid.
"""
if self.use_xml_dumper:
for attempt in range(3):
try:
if attempt > 0:
self.restart_xml_dumper_server()
return self.__fetch_xml__(self.xml_dumper_port)
except EnvironmentError as e:
# first retry, may caused by the
if attempt > 0:
logging.info("Failed to connect to the xmldumper server, retrying")
if attempt == 2:
raise e
else:
return self.adb.get_xml_dump_adb()
def __fetch_xml__(self, xml_dumper_port):
"""Function to fecth current xml.
Args:
xml_dumper_port: Port where xml dumper server is running on.
Returns:
A json string of xml info.
Raises:
OSError: Requrest is invalid.
"""
if xml_dumper_port:
response = self.get_request(xml_dumper_port, self.DUMP_XML_ENDPOINT)
else:
response = self.get_request(self.xml_dumper_port, self.DUMP_XML_ENDPOINT)
if response.status == 200:
if sys.version_info[0] > 2:
encoding = response.headers.get_content_charset("utf-8")
return response.read().decode(encoding)
else:
return response.read().decode("utf-8")
else:
raise EnvironmentError("Error: Unexpected response {}".format(response))
def drag_start(self, x, y):
"""Function to invoke drag start.
Args:
x: x coordinate to be dragged.
y: y coordinate to be dragged.
Returns:
Nothing.
Raises:
OSError: If request fails.
"""
coordinate_dict = {"x": x, "y": y}
data_string = json.dumps(coordinate_dict)
data_dict = {"params": data_string}
json_data = json.dumps(data_dict)
response = self.post_request(self.xml_dumper_port, self.DRAG_START_ENDPOINT,
json_data)
if response.status == 200:
self.drag_in_process = True
else:
raise EnvironmentError("Error: Unexpected response {}".format(response))
def drag_move(self, x, y):
"""Function to invoke drag move.
Args:
x: x coordinate to be dragged.
y: y coordinate to be dragged.
Returns:
Nothing.
Raises:
OSError: If invalid response is received.
"""
if not self.drag_in_process:
return
coordinate_dict = {"x": x, "y": y}
data_string = json.dumps(coordinate_dict)
data_dict = {"params": data_string}
json_data = json.dumps(data_dict)
response = self.post_request(self.xml_dumper_port, self.DRAG_MOVE_ENDPOINT,
json_data)
if response.status != 200:
raise EnvironmentError("Error: Unexpected response {}".format(response))
def drag_stop(self, x, y):
"""Function to invoke drag move.
Args:
x: x coordinate to be dragged.
y: y coordinate to be dragged.
Returns:
Nothing.
Raises:
OSError: If invalid response is received.
"""
if not self.drag_in_process:
return
coordinate_dict = {"x": x, "y": y}
data_string = json.dumps(coordinate_dict)
data_dict = {"params": data_string}
json_data = json.dumps(data_dict)
response = self.post_request(self.xml_dumper_port, self.DRAG_STOP_ENDPOINT,
json_data)
if response.status == 200:
self.drag_in_process = False
else:
raise EnvironmentError("Error: Unexpected response {}".format(response))
def send_motion_event(self, point, motion_event):
"""Function to inject motion event.
Args:
point: point of where the motion event will happen.
motion_event: motion event of the action.
Returns:
Nothing.
Raises:
OSError: If invalid response is received.
"""
coordinate_dict = {
"x": point.x,
"y": point.y,
"action": motion_event,
"duration": 0
}
data_string = json.dumps(coordinate_dict)
data_dict = {"params": data_string}
json_data = json.dumps(data_dict)
response = self.post_request(self.xml_dumper_port,
self.MOTION_EVENT_ENDPOINT, json_data)
if response.status != 200:
raise EnvironmentError("Error: Unexpected response {}".format(response))
def get_request(self, port, end_point):
"""Function to perform get request.
Args:
port: port number of xml dumper.
end_point: end point of request URI.
Returns:
Response object.
"""
if sys.version_info[0] > 2:
conn = http.client.HTTPConnection(self.LOCALHOST, port)
else:
conn = httplib.HTTPConnection(self.LOCALHOST, port)
conn.request("GET", end_point)
return conn.getresponse()
def post_request(self, port, end_point, json_data):
"""Function to perform json post request.
Args:
port: port number of xml dumper.
end_point: end point of request URI.
json_data: json data for request param.
Returns:
Response object.
"""
if sys.version_info[0] > 2:
conn = http.client.HTTPConnection(self.LOCALHOST, port)
else:
conn = httplib.HTTPConnection(self.LOCALHOST, port)
headers = {"Content-type": "application/json"}
conn.request("POST", end_point, json_data, headers)
return conn.getresponse()
def swipe(self, x1, y1, x2, y2):
"""Function to invoke custom swipe.
Args:
x1: x coordinate for start position.
y1: y cooridnate for start position.
x2: x coordinate for end position.
y2: y cooridnate for end position.
Returns:
Nothing, Subprocess.Popen.wait() should resolve automatically.
"""
cmd = "shell input swipe {x1} {y1} {x2} {y2}".format(
x1=str(x1), y1=str(y1), x2=str(x2), y2=str(y2))
self.adb.exec_adb_cmd(cmd).wait()
def click(self, x, y):
"""Function to invoke click on certain place button.
Args:
x: x coordinate for click position.
y: y cooridnate for click position.
Returns:
Nothing, Subprocess.Popen.wait() should resolve automatically.
"""
# adb click 0,0 will have a weird behavior
if x <= 0 and y <= 0:
return
cmd = "shell input tap {x} {y}".format(x=str(x), y=str(y))
self.adb.exec_adb_cmd(cmd).wait()
| {
"content_hash": "9af554e1ada9f48fce54849d8d5894ad",
"timestamp": "",
"source": "github",
"line_count": 423,
"max_line_length": 115,
"avg_line_length": 33.05673758865248,
"alnum_prop": 0.6425659729671744,
"repo_name": "google/android-uiconductor",
"id": "fe853bccd7c3aff9ba7f824ac874b319d3c1fabf",
"size": "14598",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "python_uiautomator/android_device_driver.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "32627"
},
{
"name": "HTML",
"bytes": "89545"
},
{
"name": "Java",
"bytes": "828653"
},
{
"name": "JavaScript",
"bytes": "1744"
},
{
"name": "Python",
"bytes": "96486"
},
{
"name": "Shell",
"bytes": "5238"
},
{
"name": "TypeScript",
"bytes": "296901"
}
],
"symlink_target": ""
} |
import requests
from datetime import datetime, timedelta
from jobs import AbstractJob
from lxml import etree
class Yr(AbstractJob):
def __init__(self, conf):
self.url = conf['url']
self.interval = conf['interval']
self.timeout = conf.get('timeout')
def _parse_tree(self, tree, date=None):
if date is None:
tabular = tree.xpath('/weatherdata/forecast/tabular/time[1]').pop()
data_root = tree.xpath(
'/weatherdata/observations/weatherstation[1]').pop()
else:
date_xpath = ('/weatherdata/forecast/tabular/time[@period=2 and'
' starts-with(@from, "{date}")]').format(
date=date.strftime('%F'))
tabular = tree.xpath(date_xpath).pop()
data_root = tabular
windSpeed = data_root.xpath('windSpeed').pop()
return {
'location': tree.xpath('/weatherdata/location/name').pop().text,
'temperature': data_root.xpath('temperature').pop().get('value'),
'description': tabular.xpath('symbol').pop().get('name'),
'wind': {
'speed': windSpeed.get('mps'),
'description': windSpeed.get('name'),
'direction': data_root.xpath('windDirection').pop().get('name')
}
}
def _parse(self, xml):
tree = etree.fromstring(xml)
tomorrow = datetime.now().date() + timedelta(days=1)
return {
'today': self._parse_tree(tree),
'tomorrow': self._parse_tree(tree, tomorrow)
}
def get(self):
r = requests.get(self.url, timeout=self.timeout)
if r.status_code == 200 and len(r.content) > 0:
return self._parse(r.content)
return {}
| {
"content_hash": "4ba7b22c569045e992a5b8ddbf974c05",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 79,
"avg_line_length": 35.15686274509804,
"alnum_prop": 0.5488008923591746,
"repo_name": "Foxboron/Frank",
"id": "039d89609c893a1deb838da52fc425337f728032",
"size": "1816",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/jobs/yr.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5780"
},
{
"name": "HTML",
"bytes": "174941"
},
{
"name": "JavaScript",
"bytes": "60625"
},
{
"name": "Makefile",
"bytes": "667"
},
{
"name": "Python",
"bytes": "52032"
}
],
"symlink_target": ""
} |
import urlparse
import logging
from django.views.generic import FormView, TemplateView
from django.contrib import auth
from django.contrib.auth import REDIRECT_FIELD_NAME, login
from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect, HttpResponseGone
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.generic.base import RedirectView
from django.conf import settings
from .forms import SurmandlAuthForm
logger = logging.getLogger(__name__)
class LoginView(FormView):
"""View to handle our login process."""
form_class = SurmandlAuthForm
redirect_field_name = REDIRECT_FIELD_NAME
template_name = "login.html"
@method_decorator(csrf_protect)
@method_decorator(never_cache)
def dispatch(self, *args, **kwargs):
return super(LoginView, self).dispatch(*args, **kwargs)
def form_valid(self, form):
login(self.request, form.get_user())
return HttpResponseRedirect(self.get_success_url())
def get_success_url(self):
if self.success_url:
redirect_to = self.success_url
else:
redirect_to = self.request.REQUEST.get(self.redirect_field_name, '')
netloc = urlparse.urlparse(redirect_to)[1]
if not redirect_to:
redirect_to = settings.LOGIN_REDIRECT_URL
# Security check -- don't allow redirection to a different host.
elif netloc and netloc != self.request.get_host():
redirect_to = settings.LOGIN_REDIRECT_URL
return redirect_to
class HomePageView(TemplateView):
"""Basic view for the homepage"""
template_name = "home.html"
@method_decorator(csrf_protect)
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(HomePageView, self).dispatch(request, *args, **kwargs)
class LogOutView(RedirectView):
"""And here is the logout view, taking the user back to the login page. """
url = settings.LOGIN_URL
permanent = False
def get(self, request, *args, **kwargs):
url = self.get_redirect_url(**kwargs)
if self.request.user.is_authenticated:
auth.logout(self.request)
if url:
if self.permanent:
return HttpResponsePermanentRedirect(url)
else:
return HttpResponseRedirect(url)
else:
logger.warning('Gone: %s', self.request.path,
extra={
'status_code': 410,
'request': self.request
})
return HttpResponseGone() | {
"content_hash": "0bc0d6c3945a0ad9e6978d165bbb01a0",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 93,
"avg_line_length": 35.5,
"alnum_prop": 0.6644998194293968,
"repo_name": "dsimandl/teamsurmandl",
"id": "bc61cfe47b784792f7b5002d8dc6e43ffb7f9ab9",
"size": "2769",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "teamsurmandl/views.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "16525"
},
{
"name": "HTML",
"bytes": "40578"
},
{
"name": "JavaScript",
"bytes": "14846"
},
{
"name": "Python",
"bytes": "72505"
}
],
"symlink_target": ""
} |
import sys
import os
from invoke import task
# You might need the following line so that alembic can traverse
# the application properly
# export PYTHONPATH=$(pwd)
IS_TTY = False if os.getenv('DOCKER') else sys.stdout.isatty()
@task
def clean(ctx):
patterns = (
'**/*.pyc',
'**/__pycache__',
'.cache',
)
for pattern in patterns:
ctx.run("rm -rf {}".format(pattern))
@task
def lint(ctx, full=False):
if full:
ctx.run('python3 -m pylint tmeister migrate tests', pty=IS_TTY)
else:
ctx.run('python3 -m flake8 tmeister migrate tests', pty=IS_TTY)
@task(pre=[clean])
def test(ctx):
"""
test the code!
:param ctx:
:param headless:
:param coverage: use --no-coverage to skip coverage results
:param x: use -x to stop at first test
:param v: use -v to increase verbosity
:return:
"""
cmd = 'python3 -m pytest --cov tmeister'
ctx.run(cmd, env={'IS_LOCAL': 'true'})
@task
def install(ctx):
"""
install dependencies
NOT to be used in docker. Only for local dev
:param ctx:
:param docker: if this is installing in a docker container
"""
ctx.run('poetry install --no-dev', pty=IS_TTY)
@task
def serve(ctx):
ctx.run('python3 run.py', pty=IS_TTY)
@task
def migrate(ctx):
ctx.run('alembic upgrade head', pty=IS_TTY)
@task
def down(ctx, all=False):
if all:
num = 'base'
else:
num = '-1'
ctx.run('alembic downgrade ' + num, pty=IS_TTY)
@task(pre=[migrate])
def seed(ctx):
print('no seed script yet')
@task
def run(ctx):
ctx.run('python3 run.py', pty=IS_TTY)
@task
def hooks(ctx):
ctx.run('ln -sf $(pwd)/hooks/pre-commit.sh .git/hooks/pre-commit')
| {
"content_hash": "9604ea8d33db5d132778a5a0f11f931e",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 71,
"avg_line_length": 19.75,
"alnum_prop": 0.6127733026467204,
"repo_name": "CanopyTax/toggle-meister",
"id": "a826233a3cfb9029dbf0a08af4d0b9f0f7c72ba4",
"size": "1738",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tasks.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1981"
},
{
"name": "Dockerfile",
"bytes": "836"
},
{
"name": "HTML",
"bytes": "680"
},
{
"name": "JavaScript",
"bytes": "80026"
},
{
"name": "Mako",
"bytes": "494"
},
{
"name": "Python",
"bytes": "85035"
},
{
"name": "Shell",
"bytes": "358"
}
],
"symlink_target": ""
} |
import base64
import datetime
import os
import re
import StringIO
import tempfile
from functools import wraps
import bleach
from flask import Blueprint, g, jsonify, request
from PIL import Image
from PIL.ExifTags import TAGS
from sqlalchemy.orm.exc import NoResultFound
import settings
from database import db
from models import Message, User
IMAGE_WIDTH = 300
ALLOWED_EXTENSIONS = ('gif', 'jpg', 'jpeg', 'png')
EMAIL_RE = re.compile('[^@]+@[^@]+\.[^@]+')
api = Blueprint('api', __name__)
#@mod.route('/')
#def index():
# pass # link to docs?
def api_response(data, code, msg):
content = {}
if data is not None:
content['data'] = data
content['meta'] = {'code': code, 'message': msg}
return jsonify(**content), code
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if g.user is None:
return api_response(None, 403, 'not authorized')
return f(*args, **kwargs)
return decorated_function
@api.route('/me', methods=['GET', 'PUT'])
@login_required
def me():
if request.method == 'GET':
return api_response(g.user.to_json(), 200,
'profile retrieved successfully')
elif request.method == 'PUT':
notify = request.form.get('email_notification') == 'true'
if g.user.notification != notify:
g.user.notification = notify
db.session.add(g.user)
db.session.commit()
return api_response({'email_notification': g.user.notification}, 200,
'profile updated successfully')
@api.route('/contact', methods=['POST'])
@login_required
def post_contact():
email = request.form.get('email')
if email:
email = email.strip()
if not EMAIL_RE.match(email):
return api_response(None, 400, 'Contact not a valid email address')
try:
contact = User.query.filter(User.email==email).one()
except NoResultFound:
contact = User(email=email)
db.session.add(contact)
g.user.contacts.append(contact)
db.session.commit()
return api_response(contact.to_json(), 200,
'contact added successfully')
else:
return api_response(None, 400, 'Contact cannot be empty')
@api.route('/contact/<int:contact_id>', methods=['DELETE'])
@login_required
def delete_contact(contact_id):
try:
contact = User.query.filter(User.id==contact_id).one()
except NoResultFound:
return api_response(None, 404, 'contact not found')
g.user.contacts.remove(contact)
db.session.commit()
return api_response(contact.to_json(), 200,
'contact removed successfully')
@api.route('/contacts')
@login_required
def get_contacts():
return api_response([c.to_json() for c in g.user.contacts], 200,
'contacts retrieved successfully')
@api.route('/messages/unread')
@login_required
def get_unread_messages():
messages = (
Message.query.filter(Message.to_user==g.user)
.filter(db.or_(
Message.expire == None,
Message.expire > datetime.datetime.now()))
.order_by('created'))
return api_response(
[dict(id=m.id, email=m.from_user.email, avatar=m.from_user.avatar,
has_media=bool(m.photo), created=m.created_stamp)
for m in messages], 200, 'messages retrieved successfully')
@api.route('/message/<int:message_id>')
@login_required
def get_message(message_id):
try:
message = (
Message.query.filter(Message.id==message_id,
Message.to_user==g.user)
.filter(db.or_(
Message.expire == None,
Message.expire > datetime.datetime.now()))).one()
except NoResultFound:
return api_response(None, 404, 'message not found')
# Update message with expired to schedule it for removal.
if message.ttl > 10:
message.expire = (datetime.datetime.now() +
datetime.timedelta(seconds=message.ttl))
else:
message.expire = datetime.datetime.now()
db.session.commit()
return api_response(message.to_json(), 200,
'message retrieved successfully')
@api.route('/message', methods=['POST'])
@login_required
def post_message():
if not request.form.get('email'):
return api_response(None, 400, 'Must specify `email` to send to.')
if not (request.form.get('message') or request.files.get('photo')):
return api_response(None, 400,
'Must specify `message` and/or `photo`.')
def set_target(attrs, new=False):
attrs['target'] = '_blank'
return attrs
email = request.form.get('email')
message = bleach.linkify(request.form.get('message'), [set_target])
ttl = request.form.get('ttl', settings.DEFAULT_TTL)
photo = request.files.get('photo')
# Look for "to" user in contacts. If not found, ignore message.
# Note: We return the same message in the response to not leak who is
# already in our db and who isn't.
try:
to_user = User.query.filter(User.email==email).one()
except NoResultFound:
return api_response(None, 400, 'recipient not a user')
if not to_user in g.user.contacts:
g.user.contacts.append(to_user)
db.session.commit()
# Handle photo.
b64photo = ''
if (photo and '.' in photo.filename):
ext = photo.filename.rsplit('.', 1)[1]
if ext.lower() in ALLOWED_EXTENSIONS:
path = tempfile.mkstemp()[1]
photo.save(path)
img = Image.open(path)
# Get orientation.
if hasattr(img, '_getexif') and img._getexif():
exif = dict((TAGS.get(k, k), v)
for k, v in img._getexif().items())
orientation = exif.get('Orientation')
if orientation:
if orientation == 1: # Horizontal (normal).
pass # Image is ok.
elif orientation == 2: # Mirrored horizontal.
img = img.transpose(Image.FLIP_LEFT_RIGHT)
elif orientation == 3: # Rotated 180.
img = img.transpose(Image.ROTATE_180)
elif orientation == 4: # Mirrored vertical.
img = img.transpose(Image.FLIP_TOP_BOTTOM)
elif orientation == 5: # Mirrored horiz, rotated 90 CCW.
img = (img.transpose(Image.FLIP_TOP_BOTTOM)
.transpose(Image.ROTATE_270))
elif orientation == 6: # Rotated 90 CW.
img = img.transpose(Image.ROTATE_270)
elif orientation == 7: # Mirrored horiz, rotated 90 CW.
img = (img.transpose(Image.FLIP_LEFT_RIGHT)
.transpose(Image.ROTATE_270))
elif orientation == 8: # Rotated 90 CCW.
img = img.transpose(Image.ROTATE_90)
# Find ratio to scale to IMAGE_WIDTH and keep aspect ratio.
x, y = img.size
ratio = float(IMAGE_WIDTH) / x
img = img.resize((int(x * ratio), int(y * ratio)), Image.ANTIALIAS)
buf = StringIO.StringIO()
img.save(buf, 'JPEG')
buf.seek(0)
b64photo = 'data:image/jpg;base64,%s' % (
base64.b64encode(buf.read()))
os.unlink(path)
message = Message(to_user=to_user, from_user=g.user,
message=message, photo=b64photo, ttl=ttl)
db.session.add(message)
db.session.commit()
# TODO: Queue this instead so we don't have to wait.
message.send_notification()
return api_response(None, 200, 'message created successfully')
| {
"content_hash": "f458277e33ee21845a916589535b2cc4",
"timestamp": "",
"source": "github",
"line_count": 231,
"max_line_length": 79,
"avg_line_length": 34.76623376623377,
"alnum_prop": 0.5687959158261736,
"repo_name": "ednapiranha/detour",
"id": "96ff663b6b71e641da1acd7d78bb32e748b83906",
"size": "8031",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "detour/api.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "123757"
},
{
"name": "Python",
"bytes": "27786"
}
],
"symlink_target": ""
} |
from PyObjCTools.TestSupport import *
from Quartz.CoreGraphics import *
class TestCGAffineTransform (TestCase):
def testStruct(self):
v = CGAffineTransform()
self.assertTrue(hasattr(v, "a"))
self.assertTrue(hasattr(v, "b"))
self.assertTrue(hasattr(v, "c"))
self.assertTrue(hasattr(v, "d"))
self.assertTrue(hasattr(v, "tx"))
self.assertTrue(hasattr(v, "ty"))
def testConstants(self):
self.assertIsInstance(CGAffineTransformIdentity, CGAffineTransform)
self.assertIsInstance(CGAffineTransformIdentity.a, float)
self.assertIsInstance(CGAffineTransformIdentity.b, float)
self.assertIsInstance(CGAffineTransformIdentity.c, float)
self.assertIsInstance(CGAffineTransformIdentity.d, float)
self.assertIsInstance(CGAffineTransformIdentity.tx, float)
self.assertIsInstance(CGAffineTransformIdentity.ty, float)
def testFunctions(self):
tf = CGAffineTransformMake(1.5, 2.5, 3.5, 4.5, 5.5, 6.5)
self.assertIsInstance(tf, CGAffineTransform)
self.assertEqual(tf.a, 1.5)
self.assertEqual(tf.b, 2.5)
self.assertEqual(tf.c, 3.5)
self.assertEqual(tf.d, 4.5)
self.assertEqual(tf.tx, 5.5)
self.assertEqual(tf.ty, 6.5)
tf = CGAffineTransformMakeTranslation(2.5, 3.5)
self.assertIsInstance(tf, CGAffineTransform)
self.assertEqual(tf.a, 1.0)
self.assertEqual(tf.b, 0.0)
self.assertEqual(tf.c, 0.0)
self.assertEqual(tf.d, 1.0)
self.assertEqual(tf.tx, 2.5)
self.assertEqual(tf.ty, 3.5)
tf = CGAffineTransformMakeScale(2.5, 3.5)
self.assertIsInstance(tf, CGAffineTransform)
self.assertEqual(tf.a, 2.5)
self.assertEqual(tf.b, 0.0)
self.assertEqual(tf.c, 0.0)
self.assertEqual(tf.d, 3.5)
self.assertEqual(tf.tx, 0.0)
self.assertEqual(tf.ty, 0.0)
tf = CGAffineTransformMakeRotation(3.4)
self.assertIsInstance(tf, CGAffineTransform)
self.assertResultHasType(CGAffineTransformIsIdentity, objc._C_BOOL)
self.assertTrue(CGAffineTransformIsIdentity(tf) is False)
self.assertTrue(CGAffineTransformIsIdentity(CGAffineTransformIdentity) is True)
tf = CGAffineTransformTranslate(tf, 2.5, 3.5)
self.assertIsInstance(tf, CGAffineTransform)
tf = CGAffineTransformScale(tf, 5.5, 9.5)
self.assertIsInstance(tf, CGAffineTransform)
tf = CGAffineTransformRotate(tf, 0.8)
self.assertIsInstance(tf, CGAffineTransform)
tf = CGAffineTransformInvert(tf)
self.assertIsInstance(tf, CGAffineTransform)
tf2 = CGAffineTransformConcat(tf,
CGAffineTransformMake(1.0, 1.0, 1.0, 1.0, 1.0, 1.0))
self.assertIsInstance(tf2, CGAffineTransform)
self.assertResultHasType(CGAffineTransformEqualToTransform, objc._C_BOOL)
self.assertTrue(CGAffineTransformEqualToTransform(tf, tf2) is False)
self.assertTrue(CGAffineTransformEqualToTransform(tf2, tf2) is True)
pt = CGPointApplyAffineTransform((2.5, 3.5), tf)
self.assertIsInstance(pt, CGPoint)
sz = CGSizeApplyAffineTransform((2.5, 3.5), tf)
self.assertIsInstance(sz, CGSize)
rct = CGRectApplyAffineTransform(((2.5, 3.5), (4.5, 5.5)), tf)
self.assertIsInstance(rct, CGRect)
if __name__ == "__main__":
main()
| {
"content_hash": "7dc4db7a0af8e6951252983d04cff0c0",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 87,
"avg_line_length": 39.18181818181818,
"alnum_prop": 0.6635730858468677,
"repo_name": "albertz/music-player",
"id": "3726e1188ec55602763cfb1e8b2a282e4d0408f2",
"size": "3449",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mac/pyobjc-framework-Quartz/PyObjCTest/test_cgaffinetransform.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Assembly",
"bytes": "47481"
},
{
"name": "C",
"bytes": "435926"
},
{
"name": "C++",
"bytes": "149133"
},
{
"name": "CSS",
"bytes": "16435"
},
{
"name": "HTML",
"bytes": "914432"
},
{
"name": "JavaScript",
"bytes": "52869"
},
{
"name": "M",
"bytes": "10808"
},
{
"name": "Makefile",
"bytes": "13304"
},
{
"name": "Mathematica",
"bytes": "61418"
},
{
"name": "Objective-C",
"bytes": "2082720"
},
{
"name": "Objective-C++",
"bytes": "62427"
},
{
"name": "PostScript",
"bytes": "2783"
},
{
"name": "Prolog",
"bytes": "217"
},
{
"name": "Python",
"bytes": "7789845"
},
{
"name": "QMake",
"bytes": "9667"
},
{
"name": "Roff",
"bytes": "8329"
},
{
"name": "Shell",
"bytes": "3521"
}
],
"symlink_target": ""
} |
"""
Script for plotting cross sections generated by FEFF found in xmu.dat files.
"""
__author__ = "Alan Dozier"
__credits__ = "Anubhav Jain, Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "1.0.2"
__maintainer__ = "Alan Dozier"
__email__ = "adozier@uky.edu"
__date__ = "April 7, 2013"
import argparse
from pymatgen.io.feff.outputs import Xmu
from pymatgen.util.plotting import pretty_plot
def main():
"""
Main function.
"""
parser = argparse.ArgumentParser(description='''
Convenient DOS Plotter for Feff runs.
Author: Alan Dozier
Version: 1.0
Last updated: April, 2013''')
parser.add_argument('filename', metavar='filename', type=str, nargs=1,
help='xmu file to plot')
parser.add_argument('filename1', metavar='filename1', type=str, nargs=1,
help='feff.inp filename to import')
plt = pretty_plot(12, 8)
color_order = ['r', 'b', 'g', 'c', 'k', 'm', 'y']
args = parser.parse_args()
xmu = Xmu.from_file(args.filename[0], args.filename1[0])
data = xmu.to_dict
plt.title(data['calc'] + ' Feff9.6 Calculation for ' + data['atom'] + ' in ' +
data['formula'] + ' unit cell')
plt.xlabel('Energies (eV)')
plt.ylabel('Absorption Cross-section')
x = data['energies']
y = data['scross']
tle = 'Single ' + data['atom'] + ' ' + data['edge'] + ' edge'
plt.plot(x, y, color_order[1 % 7], label=tle)
y = data['across']
tle = data['atom'] + ' ' + data['edge'] + ' edge in ' + data['formula']
plt.plot(x, y, color_order[2 % 7], label=tle)
plt.legend()
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize=15)
plt.tight_layout()
plt.show()
if __name__ == "__main__":
main()
| {
"content_hash": "aa9227174c08e1ab1f257a7f66aef02a",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 82,
"avg_line_length": 28.70769230769231,
"alnum_prop": 0.5884244372990354,
"repo_name": "mbkumar/pymatgen",
"id": "909c1ecd8f4d9bd247fcc236db6404594e7ca10c",
"size": "2000",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pymatgen/cli/feff_plot_cross_section.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "5100"
},
{
"name": "CSS",
"bytes": "7550"
},
{
"name": "Common Lisp",
"bytes": "3029065"
},
{
"name": "HTML",
"bytes": "827"
},
{
"name": "Makefile",
"bytes": "5573"
},
{
"name": "Perl",
"bytes": "229104"
},
{
"name": "Propeller Spin",
"bytes": "4026362"
},
{
"name": "Python",
"bytes": "6933839"
},
{
"name": "Roff",
"bytes": "1135003"
}
],
"symlink_target": ""
} |
import json
from flask import request
from redash import models
from redash.handlers.base import BaseResource
from redash.permissions import (require_access,
require_object_modify_permission,
require_permission, view_only)
class WidgetListResource(BaseResource):
@require_permission('edit_dashboard')
def post(self):
widget_properties = request.get_json(force=True)
dashboard = models.Dashboard.get_by_id_and_org(widget_properties.pop('dashboard_id'), self.current_org)
require_object_modify_permission(dashboard, self.current_user)
widget_properties['options'] = json.dumps(widget_properties['options'])
widget_properties.pop('id', None)
widget_properties['dashboard'] = dashboard
visualization_id = widget_properties.pop('visualization_id')
if visualization_id:
visualization = models.Visualization.get_by_id_and_org(visualization_id, self.current_org)
require_access(visualization.query.groups, self.current_user, view_only)
else:
visualization = None
widget_properties['visualization'] = visualization
widget = models.Widget.create(**widget_properties)
layout = json.loads(widget.dashboard.layout)
new_row = True
if len(layout) == 0 or widget.width == 2:
layout.append([widget.id])
elif len(layout[-1]) == 1:
neighbour_widget = models.Widget.get(models.Widget.id == layout[-1][0])
if neighbour_widget.width == 1:
layout[-1].append(widget.id)
new_row = False
else:
layout.append([widget.id])
else:
layout.append([widget.id])
widget.dashboard.layout = json.dumps(layout)
widget.dashboard.save()
return {'widget': widget.to_dict(), 'layout': layout, 'new_row': new_row, 'version': dashboard.version}
class WidgetResource(BaseResource):
@require_permission('edit_dashboard')
def post(self, widget_id):
# This method currently handles Text Box widgets only.
widget = models.Widget.get_by_id_and_org(widget_id, self.current_org)
require_object_modify_permission(widget.dashboard, self.current_user)
widget_properties = request.get_json(force=True)
widget.text = widget_properties['text']
widget.save()
return widget.to_dict()
@require_permission('edit_dashboard')
def delete(self, widget_id):
widget = models.Widget.get_by_id_and_org(widget_id, self.current_org)
require_object_modify_permission(widget.dashboard, self.current_user)
widget.delete_instance()
return {'layout': widget.dashboard.layout, 'version': widget.dashboard.version}
| {
"content_hash": "c51e566c8eab2907d79a6d2a215b6ff0",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 111,
"avg_line_length": 39.22222222222222,
"alnum_prop": 0.6444759206798867,
"repo_name": "easytaxibr/redash",
"id": "530e217dc8a5981425ea6714f0602a9228bbe7be",
"size": "2824",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "redash/handlers/widgets.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "239558"
},
{
"name": "HTML",
"bytes": "137424"
},
{
"name": "JavaScript",
"bytes": "283653"
},
{
"name": "Makefile",
"bytes": "955"
},
{
"name": "Nginx",
"bytes": "577"
},
{
"name": "Python",
"bytes": "529123"
},
{
"name": "Ruby",
"bytes": "709"
},
{
"name": "Shell",
"bytes": "43388"
}
],
"symlink_target": ""
} |
import os
import re
from subprocess import PIPE, Popen
from textwrap import dedent
from zipfile import ZipFile
from pants.base.build_environment import get_buildroot
from pants.testutil.pants_run_integration_test import PantsRunIntegrationTest
from pants.util.contextutil import temporary_dir
class ScopeRuntimeIntegrationTest(PantsRunIntegrationTest):
@classmethod
def _spec(cls, name):
return f"testprojects/src/java/org/pantsbuild/testproject/runtime:{name}"
def test_run_runtime_pass(self):
self.assert_success(
self.run_pants(["--no-java-strict-deps", "run", self._spec("runtime-pass"),])
)
def test_run_runtime_fail(self):
self.assert_failure(
self.run_pants(["--no-java-strict-deps", "run", self._spec("runtime-fail"),])
)
def test_compile_compile_pass(self):
self.assert_success(
self.run_pants(["--no-java-strict-deps", "compile", self._spec("compile-pass"),])
)
def test_compile_compile_fail(self):
self.assert_failure(
self.run_pants(["--no-java-strict-deps", "compile", self._spec("compile-fail"),])
)
def test_run_compile_fail(self):
self.assert_failure(
self.run_pants(["--no-java-strict-deps", "run", self._spec("compile-pass"),])
)
def test_runtime_binary_has_correct_contents_and_runs(self):
with temporary_dir() as distdir:
run = self.run_pants(
[
f"--pants-distdir={distdir}",
"--no-java-strict-deps",
"binary",
self._spec("runtime-pass"),
]
)
self.assert_success(run)
binary = os.path.join(distdir, "runtime-pass.jar")
self.assertTrue(os.path.exists(binary))
with ZipFile(binary, "r") as f:
self.assertIn("com/google/gson/stream/JsonReader.class", f.namelist())
p = Popen(["java", "-jar", binary], stdout=PIPE, stderr=PIPE)
p.communicate()
self.assertEqual(0, p.returncode)
def test_compile_binary_has_correct_contents_and_runs(self):
with temporary_dir() as distdir:
run = self.run_pants(
[
f"--pants-distdir={distdir}",
"--no-java-strict-deps",
"binary",
self._spec("compile-pass"),
]
)
self.assert_success(run)
binary = os.path.join(distdir, "compile-pass.jar")
self.assertTrue(os.path.exists(binary))
with ZipFile(binary, "r") as f:
self.assertNotIn("com/google/gson/stream/JsonReader.class", f.namelist())
p = Popen(["java", "-jar", binary], stdout=PIPE, stderr=PIPE)
p.communicate()
self.assertNotEqual(0, p.returncode)
def test_runtime_bundle_contents(self):
spec = self._spec("runtime-pass")
with temporary_dir() as distdir:
with self.pants_results(
[f"--pants-distdir={distdir}", "--no-java-strict-deps", "bundle", spec,]
) as run:
self.assert_success(run)
bundle_dir = os.path.join(distdir, f"{re.sub('[:/]', '.', spec)}-bundle")
binary = os.path.join(bundle_dir, "runtime-pass.jar")
self.assertTrue(os.path.exists(binary))
self.assertTrue(
any(
name.startswith("3rdparty.gson")
for name in os.listdir(os.path.join(bundle_dir, "libs"))
)
)
def test_compile_bundle_contents(self):
spec = self._spec("compile-pass")
with temporary_dir() as distdir:
with self.pants_results(
[f"--pants-distdir={distdir}", "--no-java-strict-deps", "bundle", spec,]
) as run:
self.assert_success(run)
bundle_dir = os.path.join(distdir, f"{re.sub('[:/]', '.', spec)}-bundle")
binary = os.path.join(bundle_dir, "compile-pass.jar")
self.assertTrue(os.path.exists(binary))
self.assertFalse(
any(
name.startswith("3rdparty.gson")
for name in os.listdir(os.path.join(bundle_dir, "libs"))
)
)
class ScopeChangesCacheInvalidationIntegrationTest(PantsRunIntegrationTest):
def test_invalidate_compiles_when_scopes_change(self):
with temporary_dir(root_dir=get_buildroot()) as workdir_parent:
workdir = os.path.join(workdir_parent, ".pants.d")
os.makedirs(workdir)
with temporary_dir(root_dir=get_buildroot()) as tmp_project:
with open(os.path.join(tmp_project, "Foo.java"), "w") as f:
f.write("public class Foo {}")
with open(os.path.join(tmp_project, "Bar.java"), "w") as f:
f.write("public class Bar extends Foo {}")
def spec(name):
return f"{os.path.basename(tmp_project)}:{name}"
def write_build(scope):
with open(os.path.join(tmp_project, "BUILD"), "w") as f:
f.write(
dedent(
"""
java_library(name='foo',
sources=['Foo.java'],
)
java_library(name='bar',
sources=['Bar.java'],
dependencies=[
scoped(scope='{scope}', address=':foo'),
],
)
jvm_binary(name='bin',
main='Foo',
dependencies=[':foo'],
)
"""
)
.strip()
.format(scope=scope)
)
write_build("")
self.assert_success(
self.run_pants_with_workdir(
["--no-java-strict-deps", "compile", spec("bar"),], workdir=workdir
),
msg="Normal build from a clean cache failed. Something may be wrong "
"with the test setup.",
)
write_build("runtime")
self.assert_failure(
self.run_pants_with_workdir(
["--no-java-strict-deps", "compile", spec("bar"),], workdir=workdir
),
msg="Build from a dirty cache with the dependency on :foo scoped to "
"runtime passed, when it should have had a compile failure. The "
"cache may not have been invalidated.",
)
write_build("compile")
self.assert_success(
self.run_pants_with_workdir(
["--no-java-strict-deps", "compile", spec("bar"),], workdir=workdir
),
msg="Build from a dirty cache with the scope changed to compile "
"failed. The cache may not have been invalidated.",
)
write_build("compile")
self.assert_failure(
self.run_pants_with_workdir(
["--no-java-strict-deps", "run", spec("bin"),], workdir=workdir
),
msg="Attempt to run binary with the dependency on :foo scoped to "
"compile passed. This should have caused a runtime failure.",
)
| {
"content_hash": "6ffd39c6f69ed923efb1e4cb8875cf80",
"timestamp": "",
"source": "github",
"line_count": 188,
"max_line_length": 93,
"avg_line_length": 42.47872340425532,
"alnum_prop": 0.48221888304532934,
"repo_name": "wisechengyi/pants",
"id": "d323d2ada3252562f3a445604c5fcb06a1424d3a",
"size": "8118",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/python/pants_test/backend/jvm/tasks/test_scope_runtime_integration.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "655"
},
{
"name": "C++",
"bytes": "2010"
},
{
"name": "CSS",
"bytes": "9444"
},
{
"name": "Dockerfile",
"bytes": "6634"
},
{
"name": "GAP",
"bytes": "1283"
},
{
"name": "Gherkin",
"bytes": "919"
},
{
"name": "Go",
"bytes": "2765"
},
{
"name": "HTML",
"bytes": "44381"
},
{
"name": "Java",
"bytes": "507948"
},
{
"name": "JavaScript",
"bytes": "22906"
},
{
"name": "Python",
"bytes": "7608990"
},
{
"name": "Rust",
"bytes": "1005243"
},
{
"name": "Scala",
"bytes": "106520"
},
{
"name": "Shell",
"bytes": "105217"
},
{
"name": "Starlark",
"bytes": "489739"
},
{
"name": "Thrift",
"bytes": "2953"
}
],
"symlink_target": ""
} |
"""Tests for the EcoData Retriever"""
import os
from StringIO import StringIO
from retriever.lib.engine import Engine
from retriever.lib.table import Table
from retriever.lib.templates import BasicTextTemplate
from retriever.lib.tools import getmd5
from retriever import DATA_WRITE_PATH
from nose.tools import with_setup
# Create simple engine fixture
test_engine = Engine()
test_engine.table = Table("test")
test_engine.script = BasicTextTemplate(tables={'test':test_engine.table},
shortname='test')
test_engine.opts = {'database_name': '{db}_abc'}
HOMEDIR = os.path.expanduser('~')
def test_auto_get_columns():
"""Basic test of getting column labels from header"""
test_engine.table.delimiter = ","
columns, column_values = test_engine.table.auto_get_columns("a,b,c,d")
assert columns == [['a', None], ['b', None], ['c', None], ['d', None]]
def test_auto_get_columns_cleanup():
"""Test of automatically cleaning up column labels from header"""
test_engine.table.delimiter = ","
columns, column_values = test_engine.table.auto_get_columns("a),b.b,c/c,d___d,group")
assert columns == [['a', None], ['b_b', None], ['c_c', None], ['d_d', None],
['grp', None]]
def test_auto_get_delimiter_comma():
"""Test if commas are properly detected as delimiter"""
test_engine.auto_get_delimiter("a,b,c;,d")
assert test_engine.table.delimiter == ","
def test_auto_get_delimiter_tab():
"""Test if commas are properly detected as delimiter"""
test_engine.auto_get_delimiter("a\tb\tc\td,")
assert test_engine.table.delimiter == "\t"
def test_auto_get_delimiter_semicolon():
"""Test if semicolons are properly detected as delimiter"""
test_engine.auto_get_delimiter("a;b;c;,d")
assert test_engine.table.delimiter == ";"
def test_create_db_statement():
"""Test creating the create database SQL statement"""
assert test_engine.create_db_statement() == 'CREATE DATABASE test_abc'
def test_database_name():
"""Test creating database name"""
assert test_engine.database_name() == 'test_abc'
def test_drop_statement():
"Test the creation of drop statements"
assert test_engine.drop_statement('TABLE', 'tablename') == "DROP TABLE IF EXISTS tablename"
def test_escape_single_quotes():
"""Test escaping of single quotes"""
assert test_engine.escape_single_quotes("1,2,3,'a'") == "1,2,3,\\'a\\'"
def test_escape_double_quotes():
"""Test escaping of double quotes"""
assert test_engine.escape_double_quotes('"a",1,2,3') == '\\"a\\",1,2,3'
def test_extract_values():
"""Test extraction of values from line of data with already know delimiter"""
test_engine.table.delimiter = ","
assert test_engine.table.extract_values('abcd,1,2,3.3') == ['abcd', '1', '2', '3.3']
def test_extract_values_fixed_width():
"""Test extraction of values from line of fixed width data"""
test_engine.table.fixed_width = [5, 2, 2, 3, 4]
assert test_engine.table.extract_values('abc 1 2 3 def ') == ['abc', '1', '2', '3', 'def']
def test_find_file_absent():
"""Test if find_file() properly returns false if no file is present"""
assert test_engine.find_file('missingfile.txt') is False
def test_find_file_present():
"""Test if existing datafile is found
Using the AvianBodySize dataset which is included for regression testing
Because all testing code and data is located in ./test/ it is necessary to
move into this directory for DATA_SEARCH_PATHS to work properly.
"""
test_engine.script.shortname = 'AvianBodySize'
os.chdir('./test/')
assert test_engine.find_file('avian_ssd_jan07.txt') == os.path.normpath('raw_data/AvianBodySize/avian_ssd_jan07.txt')
os.chdir('..')
def test_format_data_dir():
"Test if directory for storing data is properly formated"
test_engine.script.shortname = "TestName"
assert os.path.normpath(test_engine.format_data_dir()) == os.path.normpath(os.path.join(HOMEDIR,
'.retriever/raw_data/TestName'))
def test_format_filename():
"Test if filenames for stored files are properly formated"
test_engine.script.shortname = "TestName"
assert os.path.normpath(test_engine.format_filename('testfile.csv')) == os.path.normpath(os.path.join(HOMEDIR,
'.retriever/raw_data/TestName/testfile.csv'))
def test_format_insert_value_int():
"""Test formatting of values for insert statements"""
assert test_engine.format_insert_value(42, 'int') == 42
def test_format_insert_value_double():
"""Test formatting of values for insert statements"""
assert test_engine.format_insert_value(26.22, 'double') == '26.22'
def test_format_insert_value_string_simple():
"""Test formatting of values for insert statements"""
assert test_engine.format_insert_value('simple text', 'char') == "'simple text'"
def test_format_insert_value_string_complex():
"""Test formatting of values for insert statements"""
assert test_engine.format_insert_value('my notes: "have extra, stuff"', 'char') == '\'my notes: \\"have extra, stuff\\"\''
def test_getmd5():
"""Test md5 sum calculation"""
lines = ['a,b,c\n', '1,2,3\n', '4,5,6\n']
assert getmd5(lines) == '0bec5bf6f93c547bc9c6774acaf85e1a'
| {
"content_hash": "38d67bf4da28807367171ba904ba2647",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 126,
"avg_line_length": 37.26896551724138,
"alnum_prop": 0.6615470022205774,
"repo_name": "davharris/retriever",
"id": "7f171fef1f97f556e113db263dbf5320d239cffe",
"size": "5404",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/test_retriever.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "9124"
},
{
"name": "Inno Setup",
"bytes": "8881"
},
{
"name": "Python",
"bytes": "334293"
},
{
"name": "Shell",
"bytes": "511"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("hordak", "0001_initial")]
operations = [
migrations.RunSQL(
"""
CREATE OR REPLACE FUNCTION check_leg()
RETURNS trigger AS
$$
DECLARE
transaction_sum DECIMAL(13, 2);
BEGIN
IF (TG_OP = 'DELETE') THEN
SELECT SUM(amount) INTO transaction_sum FROM hordak_leg WHERE transaction_id = OLD.transaction_id;
ELSE
SELECT SUM(amount) INTO transaction_sum FROM hordak_leg WHERE transaction_id = NEW.transaction_id;
END IF;
IF transaction_sum != 0 THEN
RAISE EXCEPTION 'Sum of transaction amounts must be 0';
END IF;
RETURN NEW;
END;
$$
LANGUAGE plpgsql
""",
"DROP FUNCTION check_leg()",
),
migrations.RunSQL(
"""
CREATE CONSTRAINT TRIGGER check_leg_trigger
AFTER INSERT OR UPDATE OR DELETE ON hordak_leg
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW EXECUTE PROCEDURE check_leg();
""",
"DROP TRIGGER IF EXISTS check_leg_trigger ON hordak_leg",
),
]
| {
"content_hash": "6d9d23858c53581d0ed797b74ead5177",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 122,
"avg_line_length": 33.17777777777778,
"alnum_prop": 0.48894842598794375,
"repo_name": "waldocollective/django-hordak",
"id": "edd42620fa3f6d3fb811c8b357f23e63fc5d6888",
"size": "1566",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "hordak/migrations/0002_check_leg_trigger_20160903_1149.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "62305"
}
],
"symlink_target": ""
} |
from share.provider import ProviderAppConfig
from .harvester import DailySSRNHarvester
class AppConfig(ProviderAppConfig):
name = 'providers.com.dailyssrn'
version = '0.0.1'
title = 'dailyssrn'
long_title = 'Social Science Research Network'
home_page = 'http://papers.ssrn.com/'
harvester = DailySSRNHarvester
disabled = True # Disabled as no articles have been release in a while
| {
"content_hash": "6d639a10fea14493e76c37f92e78bda7",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 75,
"avg_line_length": 34.333333333333336,
"alnum_prop": 0.7305825242718447,
"repo_name": "zamattiac/SHARE",
"id": "a9a038756a7bf7ccda63844c8de740f292ffb36c",
"size": "412",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "providers/com/dailyssrn/apps.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3690"
},
{
"name": "HTML",
"bytes": "1582"
},
{
"name": "Python",
"bytes": "1517988"
},
{
"name": "Shell",
"bytes": "633"
}
],
"symlink_target": ""
} |
"""
This module contains translators for both Cinder and EBS volumes.
"""
from heat2arm.translators.storage.volumes.cinder_volume import (
CinderVolumeARMTranslator,
)
from heat2arm.translators.storage.volumes.ebs_volume import (
EBSVolumeARMTranslator,
)
from heat2arm.translators.storage.volumes.volume_attachments import (
CinderVolumeAttachmentARMTranslator,
EBSVolumeAttachmentARMTranslator,
)
| {
"content_hash": "bfe0bbe61cfe7ea31489fa924f75dfe4",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 69,
"avg_line_length": 30,
"alnum_prop": 0.8,
"repo_name": "aznashwan/heat2arm",
"id": "371c68e1634949c3e337dedee0e7e51f3b51a064",
"size": "1059",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "heat2arm/translators/storage/volumes/__init__.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "95403"
}
],
"symlink_target": ""
} |
import kfp.deprecated as kfp
from kfp.samples.test.utils import TestCase, relative_path, run_pipeline_func
run_pipeline_func([
TestCase(
pipeline_file=relative_path(__file__, 'pipeline_transformers.py'),
mode=kfp.dsl.PipelineExecutionMode.V1_LEGACY,
),
])
| {
"content_hash": "0f8815743bacb8249afdf5f95cfa3964",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 77,
"avg_line_length": 31.22222222222222,
"alnum_prop": 0.7117437722419929,
"repo_name": "kubeflow/pipelines",
"id": "2fd190338446c02024068d002c2aab2bbc2befd5",
"size": "867",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/core/pipeline_transformers/pipeline_transformers_test.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "799"
},
{
"name": "CSS",
"bytes": "2171"
},
{
"name": "Dockerfile",
"bytes": "49331"
},
{
"name": "Go",
"bytes": "1903937"
},
{
"name": "HTML",
"bytes": "3656"
},
{
"name": "JavaScript",
"bytes": "544297"
},
{
"name": "Jinja",
"bytes": "938"
},
{
"name": "Jupyter Notebook",
"bytes": "359548"
},
{
"name": "Makefile",
"bytes": "22164"
},
{
"name": "Mustache",
"bytes": "23652"
},
{
"name": "PowerShell",
"bytes": "3194"
},
{
"name": "Python",
"bytes": "5684887"
},
{
"name": "Shell",
"bytes": "264595"
},
{
"name": "Smarty",
"bytes": "8295"
},
{
"name": "Starlark",
"bytes": "553"
},
{
"name": "TypeScript",
"bytes": "4294958"
}
],
"symlink_target": ""
} |
'''
Creates keyspace, column family, and performs basic
bootstraping for the examples to run.
This file MUST be executed before running any example
'''
from pycassa.pool import ConnectionPool
from pycassa.system_manager import *
from pycassa.types import *
keyspace = 'mastering_cassandra'
#Open connection
sys = SystemManager('localhost:9160') #assume default installation
print 'dropping and recreating {} keyspace.'.format(keyspace)
try:
sys.drop_keyspace(keyspace)
except Exception as e:
#ignore, the keyspace does not exist
pass
sys.create_keyspace( keyspace, SIMPLE_STRATEGY, {'replication_factor': '1'})
#Create CFs
print 'creating videos CF'
sys.create_column_family(keyspace, 'videos', super=False, comparator_type=UTF8_TYPE)
sys.alter_column(keyspace, 'videos', 'title', UTF8_TYPE)
sys.alter_column(keyspace, 'videos', 'user_name', UTF8_TYPE)
sys.alter_column(keyspace, 'videos', 'runtime_in_sec', INT_TYPE)
sys.alter_column(keyspace, 'videos', 'tags_csv', UTF8_TYPE)
print 'creating tag_videos CF'
sys.create_column_family(keyspace, 'tag_videos', super=False, comparator_type=UTF8_TYPE)
print 'creating tag_videos_sup super-CF'
sys.create_column_family(keyspace, 'tag_videos_sup', super=True, comparator_type=UTF8_TYPE)
print 'creating tag_videos_composite composite column CF'
colNameType = CompositeType(UTF8Type(), UTF8Type()) # (username, videoId)
sys.create_column_family(keyspace, 'tag_videos_composite', super=False, comparator_type=colNameType)
#Add Index
print 'Adding indexes to videos CF'
sys.create_index(keyspace, 'videos', 'user_name', UTF8_TYPE)
sys.create_index(keyspace, 'videos', 'runtime_in_sec', INT_TYPE)
#Create CFs
print 'creating videos_denorm CF'
sys.create_column_family(keyspace, 'videos_denorm', super=False, comparator_type=UTF8_TYPE)
sys.alter_column(keyspace, 'videos_denorm', 'title', UTF8_TYPE)
sys.alter_column(keyspace, 'videos_denorm', 'user_name', UTF8_TYPE)
sys.alter_column(keyspace, 'videos_denorm', 'runtime_in_sec', INT_TYPE)
#Create CFs
print 'creating reverse chronologically sorted event_log CF'
event_log_comp = TimeUUIDType(reversed=True)
sys.create_column_family(keyspace, 'event_log', super=False, comparator_type=event_log_comp)
print 'creating reverse chronologically sorted event_log_mux CF'
event_log_mux_comp = TimeUUIDType(reversed=True)
sys.create_column_family(keyspace, 'event_log_mux', super=False, comparator_type=event_log_mux_comp)
#Close connection
sys.close()
print 'Bootstrapping finished!'
| {
"content_hash": "79972a0f0f7229973ed877ff9cb94042",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 100,
"avg_line_length": 37.134328358208954,
"alnum_prop": 0.7688906752411575,
"repo_name": "naishe/mastering_cassandra",
"id": "0402ca7cec189646962888b6c079c3cba9640431",
"size": "2511",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chapter_3/base_script.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "13608"
},
{
"name": "Python",
"bytes": "30249"
},
{
"name": "Shell",
"bytes": "4391"
}
],
"symlink_target": ""
} |
_DEBUG = True
def set_debug(enabled):
"""
Enable or disable the debug mode. In debug mode, a bunch of extra checks in claripy will be executed. You'll want to
disable debug mode if you are running performance critical code.
"""
global _DEBUG
_DEBUG = enabled
| {
"content_hash": "c13f5c421c7da2e3074c835f5150b53d",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 120,
"avg_line_length": 26,
"alnum_prop": 0.6818181818181818,
"repo_name": "angr/claripy",
"id": "e7578ebe4627c8782de656f93027621589e10c13",
"size": "363",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "claripy/debug.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Python",
"bytes": "821129"
}
],
"symlink_target": ""
} |
import argparse
import shutil
import subprocess
import re
import subprocess
import os
import zipfile
import io
import codecs
from subprocess import PIPE, STDOUT, Popen
from os import listdir
from os.path import isfile, join
def ParseArguments():
argMap = {}
parser = argparse.ArgumentParser(description="Generates an SDK given an sdk name and version")
parser.add_argument("--outputLocation", action="store")
parser.add_argument("--serviceName", action="store")
parser.add_argument("--apiVersion", action="store")
parser.add_argument("--pathToApiDefinitions", action="store")
parser.add_argument("--pathToGenerator", action="store")
parser.add_argument("--prepareTools", help="Makes sure generation environment is setup.", action="store_true")
parser.add_argument("--listAll", help="Lists all available SDKs for generation.", action="store_true")
args = vars( parser.parse_args() )
argMap[ "outputLocation" ] = args[ "outputLocation" ] or "./"
argMap[ "serviceName" ] = args[ "serviceName" ] or None
argMap[ "apiVersion" ] = args[ "apiVersion" ] or ""
argMap[ "pathToApiDefinitions" ] = args["pathToApiDefinitions"] or "./code-generation/api-descriptions"
argMap[ "pathToGenerator" ] = args["pathToGenerator"] or "./code-generation/generator"
argMap[ "prepareTools" ] = args["prepareTools"]
argMap[ "listAll" ] = args["listAll"]
return argMap
def DiscoverAllAvailableSDKs(discoveryPath):
sdks = {}
filesInDir = [f for f in listdir(discoveryPath) if isfile(join(discoveryPath, f))]
for file in filesInDir:
match = re.search('([\w\d-]+)-(\d{4}-\d{2}-\d{2}).normal.json', file)
if match:
sdk = {}
sdk['serviceName'] = match.group(1)
sdk['apiVersion'] = match.group(2)
sdk['filePath'] = join(discoveryPath, file)
sdks['{}-{}'.format(sdk['serviceName'], sdk['apiVersion'])] = sdk
return sdks
def PrepareGenerator(generatorPath):
currentDir = os.getcwd()
os.chdir(generatorPath)
process = subprocess.call('mvn package', shell=True)
os.chdir(currentDir)
def GenerateSdk(generatorPath, sdk, outputDir):
try:
with codecs.open(sdk['filePath'], 'rb', 'utf-8') as api_definition:
api_content = api_definition.read()
jar_path = join(generatorPath, 'target/aws-client-generator-1.0-SNAPSHOT-jar-with-dependencies.jar')
process = Popen(['java', '-jar', jar_path, '--service', sdk['serviceName'], '--version', sdk['apiVersion'], '--language-binding', 'cpp', '--arbitrary'],stdout=PIPE, stdin=PIPE, stderr=STDOUT )
writer = codecs.getwriter('utf-8')
stdInWriter = writer(process.stdin)
stdInWriter.write(api_content)
process.stdin.close()
output = process.stdout.read()
if output:
with zipfile.ZipFile(output.strip().decode('utf-8'), 'r') as zip:
zip.extractall(outputDir)
except EnvironmentError as ex:
print('Error generating sdk {} with error {}'.format(sdk, ex))
def Main():
arguments = ParseArguments()
if arguments['prepareTools']:
PrepareGenerator(arguments['pathToGenerator'])
sdks = DiscoverAllAvailableSDKs(arguments['pathToApiDefinitions'])
if arguments['listAll']:
for key, value in sdks.iteritems():
print(value)
if arguments['serviceName']:
print('Generating {} api version {}.'.format(arguments['serviceName'], arguments['apiVersion']))
key = '{}-{}'.format(arguments['serviceName'], arguments['apiVersion'])
GenerateSdk(arguments['pathToGenerator'], sdks[key], arguments['outputLocation'])
Main()
| {
"content_hash": "87ed543b45a930830e9cdb895f4d4bf8",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 205,
"avg_line_length": 40.204301075268816,
"alnum_prop": 0.6509761968440759,
"repo_name": "ambasta/aws-sdk-cpp",
"id": "7d6b5dc599752bc14ced0f4d6853495add2d1690",
"size": "4332",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/generate_sdks.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2305"
},
{
"name": "C++",
"bytes": "74273816"
},
{
"name": "CMake",
"bytes": "412257"
},
{
"name": "Java",
"bytes": "229873"
},
{
"name": "Python",
"bytes": "62933"
}
],
"symlink_target": ""
} |
import errno
import socket
import unittest
dummy_app = object()
class TestWSGIServer(unittest.TestCase):
def _makeOne(self, application=dummy_app, host='127.0.0.1', port=0,
_dispatcher=None, adj=None, map=None, _start=True,
_sock=None, _server=None):
from waitress.server import create_server
return create_server(
application,
host=host,
port=port,
map=map,
_dispatcher=_dispatcher,
_start=_start,
_sock=_sock)
def _makeOneWithMap(self, adj=None, _start=True, host='127.0.0.1',
port=0, app=dummy_app):
sock = DummySock()
task_dispatcher = DummyTaskDispatcher()
map = {}
return self._makeOne(
app,
host=host,
port=port,
map=map,
_sock=sock,
_dispatcher=task_dispatcher,
_start=_start,
)
def test_ctor_app_is_None(self):
self.assertRaises(ValueError, self._makeOneWithMap, app=None)
def test_ctor_start_true(self):
inst = self._makeOneWithMap(_start=True)
self.assertEqual(inst.accepting, True)
self.assertEqual(inst.socket.listened, 1024)
def test_ctor_makes_dispatcher(self):
inst = self._makeOne(_start=False, map={})
self.assertEqual(inst.task_dispatcher.__class__.__name__,
'ThreadedTaskDispatcher')
def test_ctor_start_false(self):
inst = self._makeOneWithMap(_start=False)
self.assertEqual(inst.accepting, False)
def test_get_server_name_empty(self):
inst = self._makeOneWithMap(_start=False)
result = inst.get_server_name('')
self.assertTrue(result)
def test_get_server_name_with_ip(self):
inst = self._makeOneWithMap(_start=False)
result = inst.get_server_name('127.0.0.1')
self.assertTrue(result)
def test_get_server_name_with_hostname(self):
inst = self._makeOneWithMap(_start=False)
result = inst.get_server_name('fred.flintstone.com')
self.assertEqual(result, 'fred.flintstone.com')
def test_get_server_name_0000(self):
inst = self._makeOneWithMap(_start=False)
result = inst.get_server_name('0.0.0.0')
self.assertEqual(result, 'localhost')
def test_run(self):
inst = self._makeOneWithMap(_start=False)
inst.asyncore = DummyAsyncore()
inst.task_dispatcher = DummyTaskDispatcher()
inst.run()
self.assertTrue(inst.task_dispatcher.was_shutdown)
def test_pull_trigger(self):
inst = self._makeOneWithMap(_start=False)
inst.trigger = DummyTrigger()
inst.pull_trigger()
self.assertEqual(inst.trigger.pulled, True)
def test_add_task(self):
task = DummyTask()
inst = self._makeOneWithMap()
inst.add_task(task)
self.assertEqual(inst.task_dispatcher.tasks, [task])
self.assertFalse(task.serviced)
def test_readable_not_accepting(self):
inst = self._makeOneWithMap()
inst.accepting = False
self.assertFalse(inst.readable())
def test_readable_maplen_gt_connection_limit(self):
inst = self._makeOneWithMap()
inst.accepting = True
inst.adj = DummyAdj
inst._map = {'a': 1, 'b': 2}
self.assertFalse(inst.readable())
def test_readable_maplen_lt_connection_limit(self):
inst = self._makeOneWithMap()
inst.accepting = True
inst.adj = DummyAdj
inst._map = {}
self.assertTrue(inst.readable())
def test_readable_maintenance_false(self):
import time
inst = self._makeOneWithMap()
then = time.time() + 1000
inst.next_channel_cleanup = then
L = []
inst.maintenance = lambda t: L.append(t)
inst.readable()
self.assertEqual(L, [])
self.assertEqual(inst.next_channel_cleanup, then)
def test_readable_maintenance_true(self):
inst = self._makeOneWithMap()
inst.next_channel_cleanup = 0
L = []
inst.maintenance = lambda t: L.append(t)
inst.readable()
self.assertEqual(len(L), 1)
self.assertNotEqual(inst.next_channel_cleanup, 0)
def test_writable(self):
inst = self._makeOneWithMap()
self.assertFalse(inst.writable())
def test_handle_read(self):
inst = self._makeOneWithMap()
self.assertEqual(inst.handle_read(), None)
def test_handle_connect(self):
inst = self._makeOneWithMap()
self.assertEqual(inst.handle_connect(), None)
def test_handle_accept_wouldblock_socket_error(self):
inst = self._makeOneWithMap()
ewouldblock = socket.error(errno.EWOULDBLOCK)
inst.socket = DummySock(toraise=ewouldblock)
inst.handle_accept()
self.assertEqual(inst.socket.accepted, False)
def test_handle_accept_other_socket_error(self):
inst = self._makeOneWithMap()
eaborted = socket.error(errno.ECONNABORTED)
inst.socket = DummySock(toraise=eaborted)
inst.adj = DummyAdj
def foo():
raise socket.error
inst.accept = foo
inst.logger = DummyLogger()
inst.handle_accept()
self.assertEqual(inst.socket.accepted, False)
self.assertEqual(len(inst.logger.logged), 1)
def test_handle_accept_noerror(self):
inst = self._makeOneWithMap()
innersock = DummySock()
inst.socket = DummySock(acceptresult=(innersock, None))
inst.adj = DummyAdj
L = []
inst.channel_class = lambda *arg, **kw: L.append(arg)
inst.handle_accept()
self.assertEqual(inst.socket.accepted, True)
self.assertEqual(innersock.opts, [('level', 'optname', 'value')])
self.assertEqual(L, [(inst, innersock, None, inst.adj)])
def test_maintenance(self):
inst = self._makeOneWithMap()
class DummyChannel(object):
requests = []
zombie = DummyChannel()
zombie.last_activity = 0
zombie.running_tasks = False
inst.active_channels[100] = zombie
inst.maintenance(10000)
self.assertEqual(zombie.will_close, True)
def test_backward_compatibility(self):
from waitress.server import WSGIServer, TcpWSGIServer
from waitress.adjustments import Adjustments
self.assertTrue(WSGIServer is TcpWSGIServer)
inst = WSGIServer(None, _start=False, port=1234)
# Ensure the adjustment was actually applied.
self.assertNotEqual(Adjustments.port, 1234)
self.assertEqual(inst.adj.port, 1234)
if hasattr(socket, 'AF_UNIX'):
class TestUnixWSGIServer(unittest.TestCase):
unix_socket = '/tmp/waitress.test.sock'
def _makeOne(self, _start=True, _sock=None):
from waitress.server import create_server
return create_server(
dummy_app,
map={},
_start=_start,
_sock=_sock,
_dispatcher=DummyTaskDispatcher(),
unix_socket=self.unix_socket,
unix_socket_perms='600'
)
def _makeDummy(self, *args, **kwargs):
sock = DummySock(*args, **kwargs)
sock.family = socket.AF_UNIX
return sock
def test_unix(self):
inst = self._makeOne(_start=False)
self.assertEqual(inst.socket.family, socket.AF_UNIX)
self.assertEqual(inst.socket.getsockname(), self.unix_socket)
def test_handle_accept(self):
# Working on the assumption that we only have to test the happy path
# for Unix domain sockets as the other paths should've been covered
# by inet sockets.
client = self._makeDummy()
listen = self._makeDummy(acceptresult=(client, None))
inst = self._makeOne(_sock=listen)
self.assertEqual(inst.accepting, True)
self.assertEqual(inst.socket.listened, 1024)
L = []
inst.channel_class = lambda *arg, **kw: L.append(arg)
inst.handle_accept()
self.assertEqual(inst.socket.accepted, True)
self.assertEqual(client.opts, [])
self.assertEqual(
L,
[(inst, client, ('localhost', None), inst.adj)]
)
class DummySock(object):
accepted = False
blocking = False
family = socket.AF_INET
def __init__(self, toraise=None, acceptresult=(None, None)):
self.toraise = toraise
self.acceptresult = acceptresult
self.bound = None
self.opts = []
def bind(self, addr):
self.bound = addr
def accept(self):
if self.toraise:
raise self.toraise
self.accepted = True
return self.acceptresult
def setblocking(self, x):
self.blocking = True
def fileno(self):
return 10
def getpeername(self):
return '127.0.0.1'
def setsockopt(self, *arg):
self.opts.append(arg)
def getsockopt(self, *arg):
return 1
def listen(self, num):
self.listened = num
def getsockname(self):
return self.bound
class DummyTaskDispatcher(object):
def __init__(self):
self.tasks = []
def add_task(self, task):
self.tasks.append(task)
def shutdown(self):
self.was_shutdown = True
class DummyTask(object):
serviced = False
start_response_called = False
wrote_header = False
status = '200 OK'
def __init__(self):
self.response_headers = {}
self.written = ''
def service(self): # pragma: no cover
self.serviced = True
class DummyAdj:
connection_limit = 1
log_socket_errors = True
socket_options = [('level', 'optname', 'value')]
cleanup_interval = 900
channel_timeout = 300
class DummyAsyncore(object):
def loop(self, timeout=30.0, use_poll=False, map=None, count=None):
raise SystemExit
class DummyTrigger(object):
def pull_trigger(self):
self.pulled = True
class DummyLogger(object):
def __init__(self):
self.logged = []
def warning(self, msg, **kw):
self.logged.append(msg)
| {
"content_hash": "792874631d0a83f3ec5b62e01c85981a",
"timestamp": "",
"source": "github",
"line_count": 333,
"max_line_length": 80,
"avg_line_length": 31.06906906906907,
"alnum_prop": 0.5968490237773052,
"repo_name": "WillisXChen/django-oscar",
"id": "0ff887175bd4689c8807c092c6c0f6d565a856f9",
"size": "10346",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "oscar/lib/python2.7/site-packages/waitress/tests/test_server.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "78"
},
{
"name": "C",
"bytes": "5979"
},
{
"name": "C++",
"bytes": "572"
},
{
"name": "CSS",
"bytes": "694578"
},
{
"name": "CoffeeScript",
"bytes": "21"
},
{
"name": "Groff",
"bytes": "21346"
},
{
"name": "HTML",
"bytes": "708061"
},
{
"name": "JavaScript",
"bytes": "1433937"
},
{
"name": "Jupyter Notebook",
"bytes": "189877"
},
{
"name": "Makefile",
"bytes": "6656"
},
{
"name": "Python",
"bytes": "47548581"
},
{
"name": "Shell",
"bytes": "6790"
},
{
"name": "Smarty",
"bytes": "21023"
},
{
"name": "TeX",
"bytes": "56837"
},
{
"name": "XSLT",
"bytes": "24882"
}
],
"symlink_target": ""
} |
from __future__ import division, print_function
import time
import numpy as np
import pyqtgraph as pg
import pyqtgraph.console
from ..fitting.psp import StackedPsp
from .user_test import UserTestUi
class PspFitUI(object):
"""Used to display details of PSP/PSC fitting analysis.
"""
def __init__(self, title=None):
self.pw = pg.GraphicsLayoutWidget()
self.plt1 = self.pw.addPlot(title=title)
self.console = pg.console.ConsoleWidget()
self.widget = pg.QtGui.QSplitter(pg.QtCore.Qt.Vertical)
self.widget.addWidget(self.pw)
self.widget.addWidget(self.console)
self.widget.resize(1000, 600)
self.widget.setSizes([400, 200])
self.widget.show()
def clear(self):
self.plt1.clear()
def show_result(self, fit):
if fit is None:
return
if not isinstance(fit, dict):
fit = fit.best_values
psp = StackedPsp()
x = np.linspace(fit['xoffset']-10e-3, fit['xoffset']+30e-3, 5000)
y = psp.eval(x=x, **fit)
self.plt1.plot(x, y, pen='g')
class PspFitTestUi(UserTestUi):
"""UI for manually pass/failing PSP fitting unit tests.
"""
def __init__(self):
expected_display = PspFitUI('expected result')
current_display = PspFitUI('current result')
UserTestUi.__init__(self, expected_display, current_display)
expected_display.plt1.setXLink(current_display.plt1)
expected_display.plt1.setYLink(current_display.plt1)
| {
"content_hash": "26c68d62fa0fcb7069992b406e0751d3",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 73,
"avg_line_length": 31.14,
"alnum_prop": 0.6242774566473989,
"repo_name": "campagnola/neuroanalysis",
"id": "755160e12e166e1302c68b1eeb799a4fd818e8e5",
"size": "1557",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "neuroanalysis/ui/psp_fitting.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "335791"
}
],
"symlink_target": ""
} |
__author__ = 'Simone Campagna'
import re
import string
import collections
from .debug import PRINT
class _FormatSpecData(object):
KEYS = ('fill', 'align', 'sign', 'alternate', 'zero', 'width', 'comma', 'precision', 'type')
#RE_FORMAT_SPEC = re.compile(r"(?P<fill>[^\{\}])?(?P<align>[\<\>\=\^])?(?P<sign>[\+\- ])?(?P<alternate>\#)?(?P<zero>0)?(?P<width>[1-9]+\d*)?(?P<comma>,)?(?P<precision>.\d+)?(?P<type>[sbcdoxXneEfFgG\%])?")
RE_FORMAT_SPEC = re.compile(r"(?P<align>[\<\>\=\^])?(?P<sign>[\+\- ])?(?P<alternate>\#)?(?P<zero>0)?(?P<width>[1-9]+\d*)?(?P<comma>,)?(?P<precision>.\d+)?(?P<type>[sbcdoxXneEfFgG\%])?")
def __init__(self, fspec):
if fspec is None:
fspec = ''
if isinstance(fspec, _FormatSpecData):
for key in self.KEYS:
setattr(self, key, getattr(fspec, key))
elif isinstance(fspec, str):
m = self.RE_FORMAT_SPEC.search(fspec)
if not m:
raise ValueError("invalid format spec {0!r}".format(fspec))
b, e = m.span()
if b == 0:
fill = None
else:
fill = fspec[:b]
self.fill = fill
for key, val in m.groupdict().items():
#print("... {}={!r}".format(key, val))
setattr(self, key, val)
else:
raise TypeError("unsupported type {0}".format(type(fspec).__name__))
def __str__(self):
l = []
for key in self.KEYS:
val = getattr(self, key)
#print("KEY {0}={1!r}".format(key, val))
if val is not None:
l.append(str(val))
return ''.join(l)
def copy(self):
return self.__class__(str(self))
class Table(object):
_FormatItem = collections.namedtuple('_FormatItem', ('pre', 'name', 'format_spec', 'conversion', 'format_spec_data'))
def __init__(self,
row_format,
title=None,
separator='',
min_ordinal_length=3,
max_row_length=70,
show_header=True,
show_header_if_empty=True):
self.max_row_length = max_row_length
self.min_ordinal_length = min_ordinal_length
self.show_header = show_header
self.show_header_if_empty = show_header_if_empty
self.separator = separator
self._columns = collections.OrderedDict()
self._set_format(row_format)
self.set_title(title)
self._rows = []
def columns(self):
return iter(self._columns)
def _set_format(self, row_format):
formatter = string.Formatter()
next_positional = 0
self._format_items = []
self._body_formats = []
self._header_formats = []
self._num_cols = 0
for pre, name, format_spec, conversion in formatter.parse(row_format):
self._num_cols += 1
is_format = True
fill = None
width = None
align = None
if name is None:
is_format = False
else:
is_format = True
self._num_cols += 1
if name:
try:
iname = int(name)
name = iname
next_positional = name
except ValueError as e:
pass
else:
name = next_positional
next_positional += 1
format_spec_data = _FormatSpecData(format_spec)
format_item = self._FormatItem(
pre=pre,
name=name,
format_spec=format_spec,
conversion=conversion,
format_spec_data=format_spec_data)
self._format_items.append(format_item)
if name is not None:
self._columns[name] = str(name).upper()
if is_format:
align = format_spec_data.align
header_format_spec_data = format_spec_data.copy()
header_format_spec_data.precision = None
header_format_spec_data.type = 's'
header_format_spec_data.sign = None
header_format_spec_data.alternate = None
header_format_spec_data.fill = None
header_format_spec_data.zero = None
if header_format_spec_data.align == '=':
header_format_spec_data.align = '<'
header_format_spec = str(header_format_spec_data)
if conversion is None:
conversion = ''
if conversion:
conversion = '!' + conversion
if format_spec:
format_spec = ':' + format_spec
if header_format_spec:
header_format_spec = ':' + header_format_spec
body_fmt = '{{{0}{1}{2}}}'.format(name, conversion, format_spec)
header_fmt = '{{{0}{1}}}'.format(name, header_format_spec)
self._body_formats.append(body_fmt)
self._header_formats.append(header_fmt)
else:
self._body_formats.append("")
self._header_formats.append("")
self._columns['__ordinal__'] = '#'
@classmethod
def format_title(self, title, max_row_length=70):
if title is not None:
title = "== {0} ".format(title)
title += "=" * (max_row_length - len(title))
return title
def set_title(self, title=None):
self._title = self.format_title(title, self.max_row_length)
def set_column_title(self, *p_args, **n_args):
for column, title in enumerate(p_args):
self._columns[column] = title
for column, title in n_args.items():
#if not column in self._columns:
# raise KeyError("no such column {0!r}".format(column))
self._columns[column] = title
def _make_row(self, is_header, row_index, *p_args, **n_args):
row = []
for format_index, format_item in enumerate(self._format_items):
row.append(format_item.pre)
name = format_item.name
if name is None:
col = ''
else:
if is_header:
fmt = self._header_formats[format_index]
else:
fmt = self._body_formats[format_index]
if not '__ordinal__' in n_args:
n_args['__ordinal__'] = row_index
col = fmt.format(*p_args, **n_args)
#print(is_header, repr(fmt), p_args, n_args, '---> {0!r}'.format(col))
row.append(col)
return row
def _make_body_row(self, row_index, *p_args, **n_args):
return self._make_row(False, row_index, *p_args, **n_args)
def _make_header_row(self, row_index, *p_args, **n_args):
#print(row_index, p_args, n_args)
return self._make_row(True, row_index, *p_args, **n_args)
def _make_header(self):
p_args = []
n_args = {}
for key, val in self._columns.items():
if isinstance(key, str):
n_args[key] = val
else:
p_args.append(val)
return self._make_header_row('', *p_args, **n_args)
def add_row(self, *p_args, **n_args):
self._rows.append(self._make_body_row(len(self._rows), *p_args, **n_args))
def add_header_row(self, *p_args, **n_args):
self._rows.append(self._make_header_row(len(self._rows), *p_args, **n_args))
def __iter__(self):
if self._title:
yield self._title
table = []
if self.show_header_if_empty or (self.show_header and self._rows):
table.append(self._make_header())
for row in self._rows:
table.append(row)
if len(table) == 0:
return
num_cols = self._num_cols
max_lengths = [max(len(row[col]) for row in table) for col in range(num_cols)]
#print(max_lengths)
aligns = []
for format_item in self._format_items:
aligns.append('<') # for pre
format_spec_data = format_item.format_spec_data
align = format_spec_data.align
if align == '=':
align = '<'
aligns.append(align)
#print(aligns)
mods = []
for max_length, align in zip(max_lengths[:-1], aligns[:-1]):
if align is None:
align = '<'
if max_length:
mods.append(":{0}{1}s".format(align, max_length))
else:
mods.append("")
if max_lengths:
align, max_length = aligns[-1], max_lengths[-1]
if (align is None or align == '<') or max_length == 0:
mods.append("")
else:
mods.append(":{0}{1}s".format(align, max_length))
fmts = ["{{{i}{m}}}".format(i=i, m=m) for i, m in enumerate(mods)]
fmt = self.separator.join(fmts)
#print(mods)
#print(fmt)
#l = max(len(str(len(table) - 1)), self.min_ordinal_length)
#r_fmt = '{{0:{l}s}}) '.format(l=l) + fmt
for row in table:
#print(repr(fmt))
#print(repr(row))
yield fmt.format(*row)
def render(self, printer_function=None):
if printer_function is None:
printer_function = PRINT
for line in self:
printer_function(line)
def show_table(title, lst, printer_function=None):
if printer_function is None:
printer_function = PRINT
lst = tuple(lst)
if lst:
if isinstance(lst[0], (tuple, list)):
lst = tuple(tuple(str(e) for e in row) for row in lst)
else:
lst = tuple((str(e), ) for e in lst)
l = len(lst[0])
fmt = "{__ordinal__:>3d}) " + ' '.join("{}" for i in range(l))
t = Table(fmt, title=title, show_header=False)
for row in lst:
t.add_row(*row)
t.render(printer_function)
def show_title(title, printer_function=None):
if printer_function is None:
printer_function = PRINT
printer_function(Table.format_title(title))
def validate_format(fmt, *p_args, **n_args):
t = Table(fmt)
for column in t.columns():
if isinstance(column, int):
if column >= len(p_args):
raise KeyError("format {0!r}: no such column {1!r}".format(fmt, column))
else:
if not column in n_args:
raise KeyError("format {0!r}: no such column {1!r}".format(fmt, column))
if __name__ == "__main__":
lt = [
('intel', 'foo/0.3', 'library', ''),
('gnu', 'foo/0.3', 'library', 'experimental very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very long'),
('intel', 'foo/0.5', 'library', 'good'),
('intel', 'foo/0.56', 'library', 'good'),
('intel', 'foo/0.57', 'library', 'good'),
('intel', 'foo/0.58', 'library', 'good_but_not_perfect'),
('intel', 'foo/0.15', 'library', 'good'),
('intel', 'foo/0.34j5', 'library', 'good'),
('intel/12.1', 'foo/0.35', 'library', 'good'),
('intel', 'foo/0.0.05', 'library', 'good'),
('intel', 'foo/0', 'library', 'good'),
('intel', 'foofoo/0.5', 'library', 'good'),
('intel', 'foo/10.00.5', 'library', 'good'),
]
keys = ['suite', 'package', 'category', 'tags']
ld = [dict(zip(keys, t)) for t in lt]
# {'suite': 'intel', 'package': 'foo/0.3', 'category': 'library', 'tags': ''},
# {'suite': 'gnu', 'package': 'foo/0.3', 'category': 'library', 'tags': 'experimental very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very long'},
# {'suite': 'intel', 'package': 'foo/0.5', 'category': 'library', 'tags': 'good'},
# {'suite': 'intel', 'package': 'foo/0.56', 'category': 'library', 'tags': 'good'},
# {'suite': 'intel', 'package': 'foo/0.57', 'category': 'library', 'tags': 'good'},
# {'suite': 'intel', 'package': 'foo/0.58', 'category': 'library', 'tags': 'good_but_not_perfect'},
# {'suite': 'intel', 'package': 'foo/0.15', 'category': 'library', 'tags': 'good'},
# {'suite': 'intel', 'package': 'foo/0.34j5', 'category': 'library', 'tags': 'good'},
# {'suite': 'intel/12.1', 'package': 'foo/0.35', 'category': 'library', 'tags': 'good'},
# {'suite': 'intel', 'package': 'foo/0.0.05', 'category': 'library', 'tags': 'good'},
# {'suite': 'intel', 'package': 'foo/0', 'category': 'library', 'tags': 'good'},
# {'suite': 'intel', 'package': 'foofoo/0.5', 'category': 'library', 'tags': 'good'},
# {'suite': 'intel', 'package': 'foo/10.00.5', 'category': 'library', 'tags': 'good'},
# ]
t1 = Table('{__ordinal__:>+#3d}) {suite!r:^20s}:{package:>s} {category} {tags:<}')
t1.set_column_title(suite='XUITE')
t2 = Table('{__ordinal__:>+#3d}) {!r:^20s}:{:>s} {} {:<}')
t2.set_column_title(*[k.upper() for k in keys])
for i, (l, t) in enumerate(((ld, t1), (lt, t2))):
for row in l:
if isinstance(row, collections.Mapping):
t.add_row(**row)
else:
t.add_row(*row)
print("-" * 70)
t.render(print)
print("-" * 70)
input("t{0} done...".format(i))
| {
"content_hash": "e4c9e5582611941d965b5a9450d82281",
"timestamp": "",
"source": "github",
"line_count": 343,
"max_line_length": 282,
"avg_line_length": 40.011661807580175,
"alnum_prop": 0.5041533080734479,
"repo_name": "simone-campagna/zapper",
"id": "222c4986ad95cd8aad9effc192c140cf78daf085",
"size": "14332",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/python/zapper/utils/table.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "291487"
},
{
"name": "Shell",
"bytes": "10602"
}
],
"symlink_target": ""
} |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'recipes.apps.RecipesConfig',
'jquery'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'leavenproject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': os.environ.get("LEAVEN_DB_NAME"),
'USER': os.environ.get("DB_USER"),
'PASSWORD': os.environ.get("DB_PASSWORD"),
'HOST': os.environ.get("DB_HOST"),
'PORT': os.environ.get("DB_PORT"),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
| {
"content_hash": "9649a47db247d8c2aae10a422c4a0989",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 91,
"avg_line_length": 26.70909090909091,
"alnum_prop": 0.6684819605173588,
"repo_name": "nowackie/leaven",
"id": "254603e76d1086e9f40ce9a8e123a84a4784105b",
"size": "2938",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "leavenproject/leavenproject/settings.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "11162"
},
{
"name": "Python",
"bytes": "9524"
}
],
"symlink_target": ""
} |
"""Keystone Client functionality for use by resources."""
import collections
import uuid
import weakref
from keystoneauth1 import exceptions as ks_exception
from keystoneauth1.identity import generic as ks_auth
from keystoneclient.v3 import client as kc_v3
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import importutils
from heat.common import context
from heat.common import exception
from heat.common.i18n import _
from heat.common import password_gen
LOG = logging.getLogger('heat.engine.clients.keystoneclient')
AccessKey = collections.namedtuple('AccessKey', ['id', 'access', 'secret'])
_default_keystone_backend = (
'heat.engine.clients.os.keystone.heat_keystoneclient.KsClientWrapper')
keystone_opts = [
cfg.StrOpt('keystone_backend',
default=_default_keystone_backend,
help=_("Fully qualified class name to use as a "
"keystone backend."))
]
cfg.CONF.register_opts(keystone_opts)
class KsClientWrapper(object):
"""Wrap keystone client so we can encapsulate logic used in resources.
Note this is intended to be initialized from a resource on a per-session
basis, so the session context is passed in on initialization
Also note that an instance of this is created in each request context as
part of a lazy-loaded cloud backend and it can be easily referenced in
each resource as ``self.keystone()``, so there should not be any need to
directly instantiate instances of this class inside resources themselves.
"""
def __init__(self, context):
# If a trust_id is specified in the context, we immediately
# authenticate so we can populate the context with a trust token
# otherwise, we delay client authentication until needed to avoid
# unnecessary calls to keystone.
#
# Note that when you obtain a token using a trust, it cannot be
# used to reauthenticate and get another token, so we have to
# get a new trust-token even if context.auth_token is set.
#
# - context.auth_url is expected to contain a versioned keystone
# path, we will work with either a v2.0 or v3 path
self._context = weakref.ref(context)
self._client = None
self._admin_auth = None
self._domain_admin_auth = None
self._domain_admin_client = None
self.session = self.context.keystone_session
self.v3_endpoint = self.context.keystone_v3_endpoint
if self.context.trust_id:
# Create a client with the specified trust_id, this
# populates self.context.auth_token with a trust-scoped token
self._client = self._v3_client_init()
# The stack domain user ID should be set in heat.conf
# It can be created via python-openstackclient
# openstack --os-identity-api-version=3 domain create heat
# If the domain is specified, then you must specify a domain
# admin user. If no domain is specified, we fall back to
# legacy behavior with warnings.
self._stack_domain_id = cfg.CONF.stack_user_domain_id
self.stack_domain_name = cfg.CONF.stack_user_domain_name
self.domain_admin_user = cfg.CONF.stack_domain_admin
self.domain_admin_password = cfg.CONF.stack_domain_admin_password
LOG.debug('Using stack domain %s', self.stack_domain)
@property
def context(self):
ctxt = self._context()
assert ctxt is not None, "Need a reference to the context"
return ctxt
@property
def stack_domain(self):
"""Domain scope data.
This is only used for checking for scoping data, not using the value.
"""
return self._stack_domain_id or self.stack_domain_name
@property
def client(self):
if not self._client:
# Create connection to v3 API
self._client = self._v3_client_init()
return self._client
@property
def auth_region_name(self):
importutils.import_module('keystonemiddleware.auth_token')
auth_region = cfg.CONF.keystone_authtoken.region_name
if not auth_region:
auth_region = (self.context.region_name or
cfg.CONF.region_name_for_services)
return auth_region
@property
def domain_admin_auth(self):
if not self._domain_admin_auth:
# Note we must specify the domain when getting the token
# as only a domain scoped token can create projects in the domain
auth = ks_auth.Password(username=self.domain_admin_user,
password=self.domain_admin_password,
auth_url=self.v3_endpoint,
domain_id=self._stack_domain_id,
domain_name=self.stack_domain_name,
user_domain_id=self._stack_domain_id,
user_domain_name=self.stack_domain_name)
# NOTE(jamielennox): just do something to ensure a valid token
try:
auth.get_token(self.session)
except ks_exception.Unauthorized:
LOG.error("Domain admin client authentication failed")
raise exception.AuthorizationFailure()
self._domain_admin_auth = auth
return self._domain_admin_auth
@property
def domain_admin_client(self):
if not self._domain_admin_client:
self._domain_admin_client = kc_v3.Client(
session=self.session,
auth=self.domain_admin_auth,
region_name=self.auth_region_name)
return self._domain_admin_client
def _v3_client_init(self):
client = kc_v3.Client(session=self.session,
region_name=self.auth_region_name)
if hasattr(self.context.auth_plugin, 'get_access'):
# NOTE(jamielennox): get_access returns the current token without
# reauthenticating if it's present and valid.
try:
auth_ref = self.context.auth_plugin.get_access(self.session)
except ks_exception.Unauthorized:
LOG.error("Keystone client authentication failed")
raise exception.AuthorizationFailure()
if self.context.trust_id:
# Sanity check
if not auth_ref.trust_scoped:
LOG.error("trust token re-scoping failed!")
raise exception.AuthorizationFailure()
# Sanity check that impersonation is effective
if self.context.trustor_user_id != auth_ref.user_id:
LOG.error("Trust impersonation failed")
raise exception.AuthorizationFailure()
return client
def create_trust_context(self):
"""Create a trust using the trustor identity in the current context.
The trust is created with the trustee as the heat service user.
If the current context already contains a trust_id, we do nothing
and return the current context.
Returns a context containing the new trust_id.
"""
if self.context.trust_id:
return self.context
# We need the service admin user ID (not name), as the trustor user
# can't lookup the ID in keystoneclient unless they're admin
# workaround this by getting the user_id from admin_client
try:
trustee_user_id = self.context.trusts_auth_plugin.get_user_id(
self.session)
except ks_exception.Unauthorized:
LOG.error("Domain admin client authentication failed")
raise exception.AuthorizationFailure()
trustor_user_id = self.context.auth_plugin.get_user_id(self.session)
trustor_proj_id = self.context.auth_plugin.get_project_id(self.session)
role_kw = {}
# inherit the roles of the trustor, unless set trusts_delegated_roles
if cfg.CONF.trusts_delegated_roles:
role_kw['role_names'] = cfg.CONF.trusts_delegated_roles
else:
token_info = self.context.auth_token_info
if token_info and token_info.get('token', {}).get('roles'):
role_kw['role_ids'] = [r['id'] for r in
token_info['token']['roles']]
else:
role_kw['role_names'] = self.context.roles
try:
trust = self.client.trusts.create(trustor_user=trustor_user_id,
trustee_user=trustee_user_id,
project=trustor_proj_id,
impersonation=True,
**role_kw)
except ks_exception.NotFound:
LOG.debug("Failed to find roles %s for user %s"
% (role_kw, trustor_user_id))
raise exception.MissingCredentialError(
required=_("roles %s") % role_kw)
context_data = self.context.to_dict()
context_data['overwrite'] = False
trust_context = context.RequestContext.from_dict(context_data)
trust_context.trust_id = trust.id
trust_context.trustor_user_id = trustor_user_id
return trust_context
def delete_trust(self, trust_id):
"""Delete the specified trust."""
try:
self.client.trusts.delete(trust_id)
except (ks_exception.NotFound, ks_exception.Unauthorized):
pass
def _get_username(self, username):
if(len(username) > 255):
LOG.warning("Truncating the username %s to the last 255 "
"characters.", username)
# get the last 255 characters of the username
return username[-255:]
def create_stack_user(self, username, password=''):
"""Create a user defined as part of a stack.
The user is defined either via template or created internally by a
resource. This user will be added to the heat_stack_user_role as
defined in the config.
Returns the keystone ID of the resulting user.
"""
# FIXME(shardy): There's duplicated logic between here and
# create_stack_domain user, but this function is expected to
# be removed after the transition of all resources to domain
# users has been completed
stack_user_role = self.client.roles.list(
name=cfg.CONF.heat_stack_user_role)
if len(stack_user_role) == 1:
role_id = stack_user_role[0].id
# Create the user
user = self.client.users.create(
name=self._get_username(username), password=password,
default_project=self.context.tenant_id)
# Add user to heat_stack_user_role
LOG.debug("Adding user %(user)s to role %(role)s",
{'user': user.id, 'role': role_id})
self.client.roles.grant(role=role_id, user=user.id,
project=self.context.tenant_id)
else:
LOG.error("Failed to add user %(user)s to role %(role)s, "
"check role exists!",
{'user': username,
'role': cfg.CONF.heat_stack_user_role})
raise exception.Error(_("Can't find role %s")
% cfg.CONF.heat_stack_user_role)
return user.id
def stack_domain_user_token(self, user_id, project_id, password):
"""Get a token for a stack domain user."""
if not self.stack_domain:
# Note, no legacy fallback path as we don't want to deploy
# tokens for non stack-domain users inside instances
msg = _('Cannot get stack domain user token, no stack domain id '
'configured, please fix your heat.conf')
raise exception.Error(msg)
# Create a keystone session, then request a token with no
# catalog (the token is expected to be used inside an instance
# where a specific endpoint will be specified, and user-data
# space is limited..)
# TODO(rabi): generic auth plugins don't support `include_catalog'
# flag yet. We'll add it once it's supported..
auth = ks_auth.Password(auth_url=self.v3_endpoint,
user_id=user_id,
password=password,
project_id=project_id)
return auth.get_token(self.session)
def create_stack_domain_user(self, username, project_id, password=None):
"""Create a domain user defined as part of a stack.
The user is defined either via template or created internally by a
resource. This user will be added to the heat_stack_user_role as
defined in the config, and created in the specified project (which is
expected to be in the stack_domain).
Returns the keystone ID of the resulting user.
"""
if not self.stack_domain:
# FIXME(shardy): Legacy fallback for folks using old heat.conf
# files which lack domain configuration
return self.create_stack_user(username=username, password=password)
# We add the new user to a special keystone role
# This role is designed to allow easier differentiation of the
# heat-generated "stack users" which will generally have credentials
# deployed on an instance (hence are implicitly untrusted)
stack_user_role = self.domain_admin_client.roles.list(
name=cfg.CONF.heat_stack_user_role)
if len(stack_user_role) == 1:
role_id = stack_user_role[0].id
# Create user
user = self.domain_admin_client.users.create(
name=self._get_username(username), password=password,
default_project=project_id, domain=self.stack_domain_id)
# Add to stack user role
LOG.debug("Adding user %(user)s to role %(role)s",
{'user': user.id, 'role': role_id})
self.domain_admin_client.roles.grant(role=role_id, user=user.id,
project=project_id)
else:
LOG.error("Failed to add user %(user)s to role %(role)s, "
"check role exists!",
{'user': username,
'role': cfg.CONF.heat_stack_user_role})
raise exception.Error(_("Can't find role %s")
% cfg.CONF.heat_stack_user_role)
return user.id
@property
def stack_domain_id(self):
if not self._stack_domain_id:
try:
access = self.domain_admin_auth.get_access(self.session)
except ks_exception.Unauthorized:
LOG.error("Keystone client authentication failed")
raise exception.AuthorizationFailure()
self._stack_domain_id = access.domain_id
return self._stack_domain_id
def _check_stack_domain_user(self, user_id, project_id, action):
"""Sanity check that domain/project is correct."""
user = self.domain_admin_client.users.get(user_id)
if user.domain_id != self.stack_domain_id:
raise ValueError(_('User %s in invalid domain') % action)
if user.default_project_id != project_id:
raise ValueError(_('User %s in invalid project') % action)
def delete_stack_domain_user(self, user_id, project_id):
if not self.stack_domain:
# FIXME(shardy): Legacy fallback for folks using old heat.conf
# files which lack domain configuration
return self.delete_stack_user(user_id)
try:
self._check_stack_domain_user(user_id, project_id, 'delete')
self.domain_admin_client.users.delete(user_id)
except ks_exception.NotFound:
pass
def delete_stack_user(self, user_id):
try:
self.client.users.delete(user=user_id)
except ks_exception.NotFound:
pass
def create_stack_domain_project(self, stack_id):
"""Create a project in the heat stack-user domain."""
if not self.stack_domain:
# FIXME(shardy): Legacy fallback for folks using old heat.conf
# files which lack domain configuration
return self.context.tenant_id
# Note we use the tenant ID not name to ensure uniqueness in a multi-
# domain environment (where the tenant name may not be globally unique)
project_name = ('%s-%s' % (self.context.tenant_id, stack_id))[:64]
desc = "Heat stack user project"
domain_project = self.domain_admin_client.projects.create(
name=project_name,
domain=self.stack_domain_id,
description=desc)
return domain_project.id
def delete_stack_domain_project(self, project_id):
if not self.stack_domain:
# FIXME(shardy): Legacy fallback for folks using old heat.conf
# files which lack domain configuration
return
# If stacks are created before configuring the heat domain, they
# exist in the default domain, in the user's project, which we
# do *not* want to delete! However, if the keystone v3cloudsample
# policy is used, it's possible that we'll get Forbidden when trying
# to get the project, so again we should do nothing
try:
project = self.domain_admin_client.projects.get(project=project_id)
except ks_exception.NotFound:
return
except ks_exception.Forbidden:
LOG.warning('Unable to get details for project %s, '
'not deleting', project_id)
return
if project.domain_id != self.stack_domain_id:
LOG.warning('Not deleting non heat-domain project')
return
try:
project.delete()
except ks_exception.NotFound:
pass
def _find_ec2_keypair(self, access, user_id=None):
"""Lookup an ec2 keypair by access ID."""
# FIXME(shardy): add filtering for user_id when keystoneclient
# extensible-crud-manager-operations bp lands
credentials = self.client.credentials.list()
for cr in credentials:
ec2_creds = jsonutils.loads(cr.blob)
if ec2_creds.get('access') == access:
return AccessKey(id=cr.id,
access=ec2_creds['access'],
secret=ec2_creds['secret'])
def delete_ec2_keypair(self, credential_id=None, access=None,
user_id=None):
"""Delete credential containing ec2 keypair."""
if credential_id:
try:
self.client.credentials.delete(credential_id)
except ks_exception.NotFound:
pass
elif access:
cred = self._find_ec2_keypair(access=access, user_id=user_id)
if cred:
self.client.credentials.delete(cred.id)
else:
raise ValueError("Must specify either credential_id or access")
def get_ec2_keypair(self, credential_id=None, access=None, user_id=None):
"""Get an ec2 keypair via v3/credentials, by id or access."""
# Note v3/credentials does not support filtering by access
# because it's stored in the credential blob, so we expect
# all resources to pass credential_id except where backwards
# compatibility is required (resource only has access stored)
# then we'll have to do a brute-force lookup locally
if credential_id:
cred = self.client.credentials.get(credential_id)
ec2_creds = jsonutils.loads(cred.blob)
return AccessKey(id=cred.id,
access=ec2_creds['access'],
secret=ec2_creds['secret'])
elif access:
return self._find_ec2_keypair(access=access, user_id=user_id)
else:
raise ValueError("Must specify either credential_id or access")
def create_ec2_keypair(self, user_id=None):
user_id = user_id or self.context.get_access(self.session).user_id
project_id = self.context.tenant_id
data_blob = {'access': uuid.uuid4().hex,
'secret': password_gen.generate_openstack_password()}
ec2_creds = self.client.credentials.create(
user=user_id, type='ec2', blob=jsonutils.dumps(data_blob),
project=project_id)
# Return a AccessKey namedtuple for easier access to the blob contents
# We return the id as the v3 api provides no way to filter by
# access in the blob contents, so it will be much more efficient
# if we manage credentials by ID instead
return AccessKey(id=ec2_creds.id,
access=data_blob['access'],
secret=data_blob['secret'])
def create_stack_domain_user_keypair(self, user_id, project_id):
if not self.stack_domain:
# FIXME(shardy): Legacy fallback for folks using old heat.conf
# files which lack domain configuration
return self.create_ec2_keypair(user_id)
data_blob = {'access': uuid.uuid4().hex,
'secret': password_gen.generate_openstack_password()}
creds = self.domain_admin_client.credentials.create(
user=user_id, type='ec2', blob=jsonutils.dumps(data_blob),
project=project_id)
return AccessKey(id=creds.id,
access=data_blob['access'],
secret=data_blob['secret'])
def delete_stack_domain_user_keypair(self, user_id, project_id,
credential_id):
if not self.stack_domain:
# FIXME(shardy): Legacy fallback for folks using old heat.conf
# files which lack domain configuration
return self.delete_ec2_keypair(credential_id=credential_id)
self._check_stack_domain_user(user_id, project_id, 'delete_keypair')
try:
self.domain_admin_client.credentials.delete(credential_id)
except ks_exception.NotFound:
pass
def disable_stack_user(self, user_id):
self.client.users.update(user=user_id, enabled=False)
def enable_stack_user(self, user_id):
self.client.users.update(user=user_id, enabled=True)
def disable_stack_domain_user(self, user_id, project_id):
if not self.stack_domain:
# FIXME(shardy): Legacy fallback for folks using old heat.conf
# files which lack domain configuration
return self.disable_stack_user(user_id)
self._check_stack_domain_user(user_id, project_id, 'disable')
self.domain_admin_client.users.update(user=user_id, enabled=False)
def enable_stack_domain_user(self, user_id, project_id):
if not self.stack_domain:
# FIXME(shardy): Legacy fallback for folks using old heat.conf
# files which lack domain configuration
return self.enable_stack_user(user_id)
self._check_stack_domain_user(user_id, project_id, 'enable')
self.domain_admin_client.users.update(user=user_id, enabled=True)
class KeystoneClient(object):
"""Keystone Auth Client.
Delay choosing the backend client module until the client's class
needs to be initialized.
"""
def __new__(cls, context):
if cfg.CONF.keystone_backend == _default_keystone_backend:
return KsClientWrapper(context)
else:
return importutils.import_object(
cfg.CONF.keystone_backend,
context
)
def list_opts():
yield None, keystone_opts
| {
"content_hash": "0864d2e97ccb2f6880f10a5303e29606",
"timestamp": "",
"source": "github",
"line_count": 559,
"max_line_length": 79,
"avg_line_length": 43.1788908765653,
"alnum_prop": 0.6018146414218835,
"repo_name": "noironetworks/heat",
"id": "f91c2c134e97dda70b98436c25fb80cb8f10dc23",
"size": "24712",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "heat/engine/clients/os/keystone/heat_keystoneclient.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "8804896"
},
{
"name": "Shell",
"bytes": "64533"
}
],
"symlink_target": ""
} |
from __future__ import annotations
import unittest
from unittest import mock
from urllib.parse import quote_plus
from parameterized import parameterized
from airflow.models import Connection
from airflow.providers.microsoft.mssql.hooks.mssql import MsSqlHook
PYMSSQL_CONN = Connection(
conn_type="mssql", host="ip", schema="share", login="username", password="password", port=8081
)
PYMSSQL_CONN_ALT = Connection(
conn_type="mssql", host="ip", schema="", login="username", password="password", port=8081
)
PYMSSQL_CONN_ALT_1 = Connection(
conn_type="mssql",
host="ip",
schema="",
login="username",
password="password",
port=8081,
extra={"SQlalchemy_Scheme": "mssql+testdriver"},
)
PYMSSQL_CONN_ALT_2 = Connection(
conn_type="mssql",
host="ip",
schema="",
login="username",
password="password",
port=8081,
extra={"SQlalchemy_Scheme": "mssql+testdriver", "myparam": "5@-//*"},
)
class TestMsSqlHook(unittest.TestCase):
@mock.patch("airflow.providers.microsoft.mssql.hooks.mssql.MsSqlHook.get_conn")
@mock.patch("airflow.providers.common.sql.hooks.sql.DbApiHook.get_connection")
def test_get_conn_should_return_connection(self, get_connection, mssql_get_conn):
get_connection.return_value = PYMSSQL_CONN
mssql_get_conn.return_value = mock.Mock()
hook = MsSqlHook()
conn = hook.get_conn()
assert mssql_get_conn.return_value == conn
mssql_get_conn.assert_called_once()
@mock.patch("airflow.providers.microsoft.mssql.hooks.mssql.MsSqlHook.get_conn")
@mock.patch("airflow.providers.common.sql.hooks.sql.DbApiHook.get_connection")
def test_set_autocommit_should_invoke_autocommit(self, get_connection, mssql_get_conn):
get_connection.return_value = PYMSSQL_CONN
mssql_get_conn.return_value = mock.Mock()
autocommit_value = mock.Mock()
hook = MsSqlHook()
conn = hook.get_conn()
hook.set_autocommit(conn, autocommit_value)
mssql_get_conn.assert_called_once()
mssql_get_conn.return_value.autocommit.assert_called_once_with(autocommit_value)
@mock.patch("airflow.providers.microsoft.mssql.hooks.mssql.MsSqlHook.get_conn")
@mock.patch("airflow.providers.common.sql.hooks.sql.DbApiHook.get_connection")
def test_get_autocommit_should_return_autocommit_state(self, get_connection, mssql_get_conn):
get_connection.return_value = PYMSSQL_CONN
mssql_get_conn.return_value = mock.Mock()
mssql_get_conn.return_value.autocommit_state = "autocommit_state"
hook = MsSqlHook()
conn = hook.get_conn()
mssql_get_conn.assert_called_once()
assert hook.get_autocommit(conn) == "autocommit_state"
@parameterized.expand(
[
(
PYMSSQL_CONN,
(
"mssql+pymssql://"
f"{quote_plus(PYMSSQL_CONN.login)}:{quote_plus(PYMSSQL_CONN.password)}"
f"@{PYMSSQL_CONN.host}:{PYMSSQL_CONN.port}/{PYMSSQL_CONN.schema}"
),
),
(
PYMSSQL_CONN_ALT,
(
"mssql+pymssql://"
f"{quote_plus(PYMSSQL_CONN_ALT.login)}:{quote_plus(PYMSSQL_CONN_ALT.password)}"
f"@{PYMSSQL_CONN_ALT.host}:{PYMSSQL_CONN_ALT.port}"
),
),
(
PYMSSQL_CONN_ALT_1,
(
f"{PYMSSQL_CONN_ALT_1.extra_dejson['SQlalchemy_Scheme']}://"
f"{quote_plus(PYMSSQL_CONN_ALT.login)}:{quote_plus(PYMSSQL_CONN_ALT.password)}"
f"@{PYMSSQL_CONN_ALT.host}:{PYMSSQL_CONN_ALT.port}/"
),
),
(
PYMSSQL_CONN_ALT_2,
(
f"{PYMSSQL_CONN_ALT_2.extra_dejson['SQlalchemy_Scheme']}://"
f"{quote_plus(PYMSSQL_CONN_ALT_2.login)}:{quote_plus(PYMSSQL_CONN_ALT_2.password)}"
f"@{PYMSSQL_CONN_ALT_2.host}:{PYMSSQL_CONN_ALT_2.port}/"
f"?myparam={quote_plus(PYMSSQL_CONN_ALT_2.extra_dejson['myparam'])}"
),
),
],
)
@mock.patch("airflow.providers.microsoft.mssql.hooks.mssql.MsSqlHook.get_connection")
def test_get_uri_driver_rewrite(self, conn, exp_uri, get_connection):
get_connection.return_value = conn
hook = MsSqlHook()
res_uri = hook.get_uri()
get_connection.assert_called()
assert res_uri == exp_uri
@mock.patch("airflow.providers.microsoft.mssql.hooks.mssql.MsSqlHook.get_connection")
def test_sqlalchemy_scheme_is_default(self, get_connection):
get_connection.return_value = PYMSSQL_CONN
hook = MsSqlHook()
assert hook.sqlalchemy_scheme == hook.DEFAULT_SQLALCHEMY_SCHEME
def test_sqlalchemy_scheme_is_from_hook(self):
hook = MsSqlHook(sqlalchemy_scheme="mssql+mytestdriver")
assert hook.sqlalchemy_scheme == "mssql+mytestdriver"
@mock.patch("airflow.providers.microsoft.mssql.hooks.mssql.MsSqlHook.get_connection")
def test_sqlalchemy_scheme_is_from_conn_extra(self, get_connection):
get_connection.return_value = PYMSSQL_CONN_ALT_1
hook = MsSqlHook()
scheme = hook.sqlalchemy_scheme
get_connection.assert_called()
assert scheme == PYMSSQL_CONN_ALT_1.extra_dejson["SQlalchemy_Scheme"]
@mock.patch("airflow.providers.microsoft.mssql.hooks.mssql.MsSqlHook.get_connection")
def test_get_sqlalchemy_engine(self, get_connection):
get_connection.return_value = PYMSSQL_CONN
hook = MsSqlHook()
hook.get_sqlalchemy_engine()
| {
"content_hash": "c9eefd94e962470b4bed2ebe39b54d1e",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 103,
"avg_line_length": 38.24,
"alnum_prop": 0.622907949790795,
"repo_name": "nathanielvarona/airflow",
"id": "832fb49754d42795e24442706be419da0fb4f722",
"size": "6523",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/providers/microsoft/mssql/hooks/test_mssql.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "25980"
},
{
"name": "Dockerfile",
"bytes": "70681"
},
{
"name": "HCL",
"bytes": "3786"
},
{
"name": "HTML",
"bytes": "173025"
},
{
"name": "JavaScript",
"bytes": "142848"
},
{
"name": "Jinja",
"bytes": "38895"
},
{
"name": "Jupyter Notebook",
"bytes": "5482"
},
{
"name": "Mako",
"bytes": "1339"
},
{
"name": "Python",
"bytes": "23169682"
},
{
"name": "R",
"bytes": "313"
},
{
"name": "Shell",
"bytes": "211967"
},
{
"name": "TypeScript",
"bytes": "484556"
}
],
"symlink_target": ""
} |
from pyfbsdk import *
##################################################################################
# Script for selecting effecting character and control rig from model selection
# Author Sergey Solohin (Neill3d) 2014
# e-mail to: s@neill3d.com
# www.neill3d.com
#
# Github repo - https://github.com/Neill3d/MoPlugs
# Licensed under BSD 3-clause
# https://github.com/Neill3d/MoPlugs/blob/master/LICENSE
#
##################################################################################
lSystem = FBSystem()
lScene = lSystem.Scene
lCharToSelect = None
for lChar in lScene.Characters:
lSkinModelList = FBModelList()
lChar.GetSkinModelList(lSkinModelList)
for lModel in lSkinModelList:
if lModel.Selected == True:
lCharToSelect = lChar
break
if lCharToSelect != None:
lCharToSelect.Selected = True
lControlSet = lCharToSelect.GetCurrentControlSet()
if lControlSet != None:
lControlSet.Selected = True
# select ref
lRefModel = lCharToSelect.GetCtrlRigModel(FBBodyNodeId.kFBReferenceNodeId)
if lRefModel:
lRefModel.Selected = True
#lCharToSelect.SelectModels(True, True, True, True) | {
"content_hash": "83b8ad3b234eb92afc94738360631cb4",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 82,
"avg_line_length": 30.162790697674417,
"alnum_prop": 0.5643793369313801,
"repo_name": "Neill3d/MoPlugs",
"id": "f3161839cadbd4423ef0e04d8cac5adfeac1e23a",
"size": "1298",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PythonScripts/Actions/SelCharAndCR_ByModelSelection.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "93535"
},
{
"name": "C#",
"bytes": "388924"
},
{
"name": "C++",
"bytes": "5588932"
},
{
"name": "GLSL",
"bytes": "395995"
},
{
"name": "Inno Setup",
"bytes": "12223"
},
{
"name": "Python",
"bytes": "514876"
}
],
"symlink_target": ""
} |
"""Model classes for datastore objects and properties for models."""
import datetime
import inspect
import json
import pickle
import zlib
from google.cloud.datastore import helpers
from google.cloud.ndb import _datastore_types
from google.cloud.ndb import exceptions
from google.cloud.ndb import key as key_module
__all__ = [
"Key",
"BlobKey",
"GeoPt",
"Rollback",
"KindError",
"InvalidPropertyError",
"BadProjectionError",
"UnprojectedPropertyError",
"ReadonlyPropertyError",
"ComputedPropertyError",
"IndexProperty",
"Index",
"IndexState",
"ModelAdapter",
"make_connection",
"ModelAttribute",
"Property",
"ModelKey",
"BooleanProperty",
"IntegerProperty",
"FloatProperty",
"BlobProperty",
"TextProperty",
"StringProperty",
"GeoPtProperty",
"PickleProperty",
"JsonProperty",
"UserProperty",
"KeyProperty",
"BlobKeyProperty",
"DateTimeProperty",
"DateProperty",
"TimeProperty",
"StructuredProperty",
"LocalStructuredProperty",
"GenericProperty",
"ComputedProperty",
"MetaModel",
"Model",
"Expando",
"transaction",
"transaction_async",
"in_transaction",
"transactional",
"transactional_async",
"transactional_tasklet",
"non_transactional",
"get_multi_async",
"get_multi",
"put_multi_async",
"put_multi",
"delete_multi_async",
"delete_multi",
"get_indexes_async",
"get_indexes",
]
_MAX_STRING_LENGTH = 1500
Key = key_module.Key
BlobKey = _datastore_types.BlobKey
GeoPt = helpers.GeoPoint
Rollback = exceptions.Rollback
class KindError(exceptions.BadValueError):
"""Raised when an implementation for a kind can't be found.
May also be raised when the kind is not a byte string.
"""
class InvalidPropertyError(exceptions.Error):
"""Raised when a property is not applicable to a given use.
For example, a property must exist and be indexed to be used in a query's
projection or group by clause.
"""
BadProjectionError = InvalidPropertyError
"""This alias for :class:`InvalidPropertyError` is for legacy support."""
class UnprojectedPropertyError(exceptions.Error):
"""Raised when getting a property value that's not in the projection."""
class ReadonlyPropertyError(exceptions.Error):
"""Raised when attempting to set a property value that is read-only."""
class ComputedPropertyError(ReadonlyPropertyError):
"""Raised when attempting to set or delete a computed property."""
class IndexProperty:
"""Immutable object representing a single property in an index."""
__slots__ = ("_name", "_direction")
def __new__(cls, *, name, direction):
instance = super(IndexProperty, cls).__new__(cls)
instance._name = name
instance._direction = direction
return instance
@property
def name(self):
"""str: The property name being indexed."""
return self._name
@property
def direction(self):
"""str: The direction in the index, ``asc`` or ``desc``."""
return self._direction
def __repr__(self):
"""Return a string representation."""
return "{}(name={!r}, direction={!r})".format(
type(self).__name__, self.name, self.direction
)
def __eq__(self, other):
"""Compare two index properties for equality."""
if not isinstance(other, IndexProperty):
return NotImplemented
return self.name == other.name and self.direction == other.direction
def __ne__(self, other):
"""Inequality comparison operation."""
return not self == other
def __hash__(self):
return hash((self.name, self.direction))
class Index:
"""Immutable object representing an index."""
__slots__ = ("_kind", "_properties", "_ancestor")
def __new__(cls, *, kind, properties, ancestor):
instance = super(Index, cls).__new__(cls)
instance._kind = kind
instance._properties = properties
instance._ancestor = ancestor
return instance
@property
def kind(self):
"""str: The kind being indexed."""
return self._kind
@property
def properties(self):
"""List[IndexProperty]: The properties being indexed."""
return self._properties
@property
def ancestor(self):
"""bool: Indicates if this is an ancestor index."""
return self._ancestor
def __repr__(self):
"""Return a string representation."""
return "{}(kind={!r}, properties={!r}, ancestor={})".format(
type(self).__name__, self.kind, self.properties, self.ancestor
)
def __eq__(self, other):
"""Compare two indexes."""
if not isinstance(other, Index):
return NotImplemented
return (
self.kind == other.kind
and self.properties == other.properties
and self.ancestor == other.ancestor
)
def __ne__(self, other):
"""Inequality comparison operation."""
return not self == other
def __hash__(self):
return hash((self.kind, self.properties, self.ancestor))
class IndexState:
"""Immutable object representing an index and its state."""
__slots__ = ("_definition", "_state", "_id")
def __new__(cls, *, definition, state, id):
instance = super(IndexState, cls).__new__(cls)
instance._definition = definition
instance._state = state
instance._id = id
return instance
@property
def definition(self):
"""Index: The index corresponding to the tracked state."""
return self._definition
@property
def state(self):
"""str: The index state.
Possible values are ``error``, ``deleting``, ``serving`` or
``building``.
"""
return self._state
@property
def id(self):
"""int: The index ID."""
return self._id
def __repr__(self):
"""Return a string representation."""
return "{}(definition={!r}, state={!r}, id={:d})".format(
type(self).__name__, self.definition, self.state, self.id
)
def __eq__(self, other):
"""Compare two index states."""
if not isinstance(other, IndexState):
return NotImplemented
return (
self.definition == other.definition
and self.state == other.state
and self.id == other.id
)
def __ne__(self, other):
"""Inequality comparison operation."""
return not self == other
def __hash__(self):
return hash((self.definition, self.state, self.id))
class ModelAdapter:
__slots__ = ()
def __init__(self, *args, **kwargs):
raise NotImplementedError
def make_connection(*args, **kwargs):
raise NotImplementedError
class ModelAttribute:
"""Base for classes that implement a ``_fix_up()`` method."""
__slots__ = ()
def _fix_up(self, cls, code_name):
"""Fix-up property name. To be implemented by subclasses.
Args:
cls (type): The model class that owns the property.
code_name (str): The name of the :class:`Property` being fixed up.
"""
class _BaseValue:
"""A marker object wrapping a "base type" value.
This is used to be able to tell whether ``entity._values[name]`` is a
user value (i.e. of a type that the Python code understands) or a
base value (i.e of a type that serialization understands).
User values are unwrapped; base values are wrapped in a
:class:`_BaseValue` instance.
Args:
b_val (Any): The base value to be wrapped.
Raises:
TypeError: If ``b_val`` is :data:`None`.
TypeError: If ``b_val`` is a list.
"""
__slots__ = ("b_val",)
def __init__(self, b_val):
if b_val is None:
raise TypeError("Cannot wrap None")
if isinstance(b_val, list):
raise TypeError("Lists cannot be wrapped. Received", b_val)
self.b_val = b_val
def __repr__(self):
return "_BaseValue({!r})".format(self.b_val)
def __eq__(self, other):
"""Compare two :class:`_BaseValue` instances."""
if not isinstance(other, _BaseValue):
return NotImplemented
return self.b_val == other.b_val
def __ne__(self, other):
"""Inequality comparison operation."""
return not self == other
def __hash__(self):
raise TypeError("_BaseValue is not immutable")
class Property(ModelAttribute):
"""A class describing a typed, persisted attribute of an entity.
.. warning::
This is not to be confused with Python's ``@property`` built-in.
.. note::
This is just a base class; there are specific subclasses that
describe properties of various types (and :class:`GenericProperty`
which describes a dynamically typed property).
The :class:`Property` does not reserve any "public" names (i.e. names
that don't start with an underscore). This is intentional; the subclass
:class:`StructuredProperty` uses the public attribute namespace to refer to
nested property names (this is essential for specifying queries on
subproperties).
The :meth:`IN` attribute is provided as an alias for ``_IN``, but ``IN``
can be overridden if a subproperty has the same name.
The :class:`Property` class and its predefined subclasses allow easy
subclassing using composable (or stackable) validation and
conversion APIs. These require some terminology definitions:
* A **user value** is a value such as would be set and accessed by the
application code using standard attributes on the entity.
* A **base value** is a value such as would be serialized to
and deserialized from Cloud Datastore.
A property will be a member of a :class:`Model` and will be used to help
store values in an ``entity`` (i.e. instance of a model subclass). The
underlying stored values can be either user values or base values.
To interact with the composable conversion and validation API, a
:class:`Property` subclass can define
* ``_to_base_type()``
* ``_from_base_type()``
* ``_validate()``
These should **not** call their ``super()`` method, since the methods
are meant to be composed. For example with composable validation:
.. code-block:: python
class Positive(ndb.IntegerProperty):
def _validate(self, value):
if value < 1:
raise ndb.exceptions.BadValueError("Non-positive", value)
class SingleDigit(Positive):
def _validate(self, value):
if value > 9:
raise ndb.exceptions.BadValueError("Multi-digit", value)
neither ``_validate()`` method calls ``super()``. Instead, when a
``SingleDigit`` property validates a value, it composes all validation
calls in order:
* ``SingleDigit._validate``
* ``Positive._validate``
* ``IntegerProperty._validate``
The API supports "stacking" classes with ever more sophisticated
user / base conversions:
* the user to base conversion goes from more sophisticated to less
sophisticated
* the base to user conversion goes from less sophisticated to more
sophisticated
For example, see the relationship between :class:`BlobProperty`,
:class:`TextProperty` and :class:`StringProperty`.
The validation API distinguishes between "lax" and "strict" user values.
The set of lax values is a superset of the set of strict values. The
``_validate()`` method takes a lax value and if necessary converts it to
a strict value. For example, an integer (lax) can be converted to a
floating point (strict) value. This means that when setting the property
value, lax values are accepted, while when getting the property value, only
strict values will be returned. If no conversion is needed, ``_validate()``
may return :data:`None`. If the argument is outside the set of accepted lax
values, ``_validate()`` should raise an exception, preferably
:exc:`TypeError` or :exc:`.BadValueError`.
A class utilizing all three may resemble:
.. code-block:: python
class WidgetProperty(ndb.Property):
def _validate(self, value):
# Lax user value to strict user value.
if not isinstance(value, Widget):
raise nbd.exceptions.BadValueError(value)
def _to_base_type(self, value):
# (Strict) user value to base value.
if isinstance(value, Widget):
return value.to_internal()
def _from_base_type(self, value):
# Base value to (strict) user value.'
if not isinstance(value, _WidgetInternal):
return Widget(value)
There are some things that ``_validate()``, ``_to_base_type()`` and
``_from_base_type()`` do **not** need to handle:
* :data:`None`: They will not be called with :data:`None` (and if they
return :data:`None`, this means that the value does not need conversion).
* Repeated values: The infrastructure takes care of calling
``_from_base_type()`` or ``_to_base_type()`` for each list item in a
repeated value.
* Wrapping "base" values: The wrapping and unwrapping is taken care of by
the infrastructure that calls the composable APIs.
* Comparisons: The comparison operations call ``_to_base_type()`` on
their operand.
* Distinguishing between user and base values: the infrastructure
guarantees that ``_from_base_type()`` will be called with an
(unwrapped) base value, and that ``_to_base_type()`` will be called
with a user value.
* Returning the original value: if any of these return :data:`None`, the
original value is kept. (Returning a different value not equal to
:data:`None` will substitute the different value.)
Additionally, :meth:`_prepare_for_put` can be used to integrate with
datastore save hooks used by :class:`Model` instances.
.. automethod:: _prepare_for_put
Args:
name (str): The name of the property.
indexed (bool): Indicates if the value should be indexed.
repeated (bool): Indicates if this property is repeated, i.e. contains
multiple values.
required (bool): Indicates if this property is required on the given
model type.
default (Any): The default value for this property.
choices (Iterable[Any]): A container of allowed values for this
property.
validator (Callable[[~google.cloud.ndb.model.Property, Any], bool]): A
validator to be used to check values.
verbose_name (str): A longer, user-friendly name for this property.
write_empty_list (bool): Indicates if an empty list should be written
to the datastore.
"""
# Instance default fallbacks provided by class.
_code_name = None
_name = None
_indexed = True
_repeated = False
_required = False
_default = None
_choices = None
_validator = None
_verbose_name = None
_write_empty_list = False
# Non-public class attributes.
_FIND_METHODS_CACHE = {}
def __init__(
self,
name=None,
*,
indexed=None,
repeated=None,
required=None,
default=None,
choices=None,
validator=None,
verbose_name=None,
write_empty_list=None
):
# NOTE: These explicitly avoid setting the values so that the
# instances will fall back to the class on lookup.
if name is not None:
self._name = self._verify_name(name)
if indexed is not None:
self._indexed = indexed
if repeated is not None:
self._repeated = repeated
if required is not None:
self._required = required
if default is not None:
self._default = default
self._verify_repeated()
if choices is not None:
self._choices = self._verify_choices(choices)
if validator is not None:
self._validator = self._verify_validator(validator)
if verbose_name is not None:
self._verbose_name = verbose_name
if write_empty_list is not None:
self._write_empty_list = write_empty_list
@staticmethod
def _verify_name(name):
"""Verify the name of the property.
Args:
name (str): The name of the property.
Returns:
str: The ``name`` passed in.
Raises:
TypeError: If the ``name`` is not a string.
ValueError: If the name contains a ``.``.
"""
if not isinstance(name, str):
raise TypeError("Name {!r} is not a string".format(name))
if "." in name:
raise ValueError(
"Name {!r} cannot contain period characters".format(name)
)
return name
def _verify_repeated(self):
"""Checks if the repeated / required / default values are compatible.
Raises:
ValueError: If ``repeated`` is :data:`True` but one of
``required`` or ``default`` is set.
"""
if self._repeated and (self._required or self._default is not None):
raise ValueError(
"repeated is incompatible with required or default"
)
@staticmethod
def _verify_choices(choices):
"""Verify the choices for a property with a limited set of values.
Args:
choices (Union[list, tuple, set, frozenset]): An iterable of
allowed values for the property.
Returns:
frozenset: The ``choices`` cast to a frozen set.
Raises:
TypeError: If ``choices`` is not one of the expected container
types.
"""
if not isinstance(choices, (list, tuple, set, frozenset)):
raise TypeError(
"choices must be a list, tuple or set; received {!r}".format(
choices
)
)
return frozenset(choices)
@staticmethod
def _verify_validator(validator):
"""Verify the validator for a property.
The validator will be called as follows:
.. code-block:: python
value = validator(prop, value)
The ``validator`` should be idempotent, i.e. calling it a second time
should not further modify the value. So a validator that returns e.g.
``value.lower()`` or ``value.strip()`` is fine, but one that returns
``value + "$"`` is not.
Args:
validator (Callable[[Property, Any], bool]): A callable that can
validate a property value.
Returns:
Callable[[Property, Any], bool]: The ``validator``.
Raises:
TypeError: If ``validator`` is not callable. This is determined by
checking is the attribute ``__call__`` is defined.
"""
# NOTE: Checking for ``_call__`` is done to match the original
# implementation. It's not clear why ``callable()`` was not used.
if getattr(validator, "__call__", None) is None:
raise TypeError(
"validator must be callable or None; received {!r}".format(
validator
)
)
return validator
def _constructor_info(self):
"""Helper for :meth:`__repr__`.
Yields:
Tuple[str, bool]: Pairs of argument name and a boolean indicating
if that argument is a keyword.
"""
signature = inspect.signature(self.__init__)
for name, parameter in signature.parameters.items():
is_keyword = parameter.kind == inspect.Parameter.KEYWORD_ONLY
yield name, is_keyword
def __repr__(self):
"""Return a compact unambiguous string representation of a property.
This cycles through all stored attributes and displays the ones that
differ from the default values.
"""
args = []
cls = type(self)
for name, is_keyword in self._constructor_info():
attr = "_{}".format(name)
instance_val = getattr(self, attr)
default_val = getattr(cls, attr)
if instance_val is not default_val:
if isinstance(instance_val, type):
as_str = instance_val.__qualname__
else:
as_str = repr(instance_val)
if is_keyword:
as_str = "{}={}".format(name, as_str)
args.append(as_str)
return "{}({})".format(cls.__name__, ", ".join(args))
def _datastore_type(self, value):
"""Internal hook used by property filters.
Sometimes the low-level query interface needs a specific data type
in order for the right filter to be constructed. See
:meth:`_comparison`.
Args:
value (Any): The value to be converted to a low-level type.
Returns:
Any: The passed-in ``value``, always. Subclasses may alter this
behavior.
"""
return value
def _comparison(self, op, value):
"""Internal helper for comparison operators.
Args:
op (str): The comparison operator. One of ``=``, ``!=``, ``<``,
``<=``, ``>``, ``>=`` or ``in``.
value (Any): The value to compare against.
Returns:
FilterNode: A FilterNode instance representing the requested
comparison.
Raises:
BadFilterError: If the current property is not indexed.
"""
# Import late to avoid circular imports.
from google.cloud.ndb import query
if not self._indexed:
raise exceptions.BadFilterError(
"Cannot query for unindexed property {}".format(self._name)
)
if value is not None:
value = self._do_validate(value)
value = self._call_to_base_type(value)
value = self._datastore_type(value)
return query.FilterNode(self._name, op, value)
# Comparison operators on Property instances don't compare the
# properties; instead they return ``FilterNode``` instances that can be
# used in queries.
def __eq__(self, value):
"""FilterNode: Represents the ``=`` comparison."""
return self._comparison("=", value)
def __ne__(self, value):
"""FilterNode: Represents the ``!=`` comparison."""
return self._comparison("!=", value)
def __lt__(self, value):
"""FilterNode: Represents the ``<`` comparison."""
return self._comparison("<", value)
def __le__(self, value):
"""FilterNode: Represents the ``<=`` comparison."""
return self._comparison("<=", value)
def __gt__(self, value):
"""FilterNode: Represents the ``>`` comparison."""
return self._comparison(">", value)
def __ge__(self, value):
"""FilterNode: Represents the ``>=`` comparison."""
return self._comparison(">=", value)
def _IN(self, value):
"""For the ``in`` comparison operator.
The ``in`` operator cannot be overloaded in the way we want
to, so we define a method. For example:
.. code-block:: python
Employee.query(Employee.rank.IN([4, 5, 6]))
Note that the method is called ``_IN()`` but may normally be invoked
as ``IN()``; ``_IN()`` is provided for the case that a
:class:`.StructuredProperty` refers to a model that has a property
named ``IN``.
Args:
value (Iterable[Any]): The set of values that the property value
must be contained in.
Returns:
Union[~google.cloud.ndb.query.DisjunctionNode, \
~google.cloud.ndb.query.FilterNode, \
~google.cloud.ndb.query.FalseNode]: A node corresponding
to the desired in filter.
* If ``value`` is empty, this will return a :class:`.FalseNode`
* If ``len(value) == 1``, this will return a :class:`.FilterNode`
* Otherwise, this will return a :class:`.DisjunctionNode`
Raises:
~google.cloud.ndb.exceptions.BadFilterError: If the current
property is not indexed.
~google.cloud.ndb.exceptions.BadArgumentError: If ``value`` is not
a basic container (:class:`list`, :class:`tuple`, :class:`set`
or :class:`frozenset`).
"""
# Import late to avoid circular imports.
from google.cloud.ndb import query
if not self._indexed:
raise exceptions.BadFilterError(
"Cannot query for unindexed property {}".format(self._name)
)
if not isinstance(value, (list, tuple, set, frozenset)):
raise exceptions.BadArgumentError(
"Expected list, tuple or set, got {!r}".format(value)
)
values = []
for sub_value in value:
if sub_value is not None:
sub_value = self._do_validate(sub_value)
sub_value = self._call_to_base_type(sub_value)
sub_value = self._datastore_type(sub_value)
values.append(sub_value)
return query.FilterNode(self._name, "in", values)
IN = _IN
"""Used to check if a property value is contained in a set of values.
For example:
.. code-block:: python
Employee.query(Employee.rank.IN([4, 5, 6]))
"""
def __neg__(self):
"""Return a descending sort order on this property.
For example:
.. code-block:: python
Employee.query().order(-Employee.rank)
Raises:
NotImplementedError: Always, the original implementation relied on
a low-level datastore query module.
"""
raise NotImplementedError("Missing datastore_query.PropertyOrder")
def __pos__(self):
"""Return an ascending sort order on this property.
Note that this is redundant but provided for consistency with
:meth:`__neg__`. For example, the following two are equivalent:
.. code-block:: python
Employee.query().order(+Employee.rank)
Employee.query().order(Employee.rank)
Raises:
NotImplementedError: Always, the original implementation relied on
a low-level datastore query module.
"""
raise NotImplementedError("Missing datastore_query.PropertyOrder")
def _do_validate(self, value):
"""Call all validations on the value.
This transforms the ``value`` via:
* Calling the derived ``_validate()`` method(s) (on subclasses that
don't define ``_to_base_type()``),
* Calling the custom validator function
After transforming, it checks if the transformed value is in
``choices`` (if defined).
It's possible that one of the ``_validate()`` methods will raise
an exception.
If ``value`` is a base-value, this will do nothing and return it.
.. note::
This does not call all composable ``_validate()`` methods.
It only calls ``_validate()`` methods up to the
first class in the hierarchy that defines a ``_to_base_type()``
method, when the MRO is traversed looking for ``_validate()`` and
``_to_base_type()`` methods.
.. note::
For a repeated property this method should be called
for each value in the list, not for the list as a whole.
Args:
value (Any): The value to be converted / validated.
Returns:
Any: The transformed ``value``, possibly modified in an idempotent
way.
"""
if isinstance(value, _BaseValue):
return value
value = self._call_shallow_validation(value)
if self._validator is not None:
new_value = self._validator(self, value)
if new_value is not None:
value = new_value
if self._choices is not None:
if value not in self._choices:
raise exceptions.BadValueError(
"Value {!r} for property {} is not an allowed "
"choice".format(value, self._name)
)
return value
def _fix_up(self, cls, code_name):
"""Internal helper called to tell the property its name.
This is called by :meth:`_fix_up_properties`, which is called by
:class:`MetaModel` when finishing the construction of a :class:`Model`
subclass. The name passed in is the name of the class attribute to
which the current property is assigned (a.k.a. the code name). Note
that this means that each property instance must be assigned to (at
most) one class attribute. E.g. to declare three strings, you must
call create three :class:`StringProperty` instances:
.. code-block:: python
class MyModel(ndb.Model):
foo = ndb.StringProperty()
bar = ndb.StringProperty()
baz = ndb.StringProperty()
you cannot write:
.. code-block:: python
class MyModel(ndb.Model):
foo = bar = baz = ndb.StringProperty()
Args:
cls (type): The class that the property is stored on. This argument
is unused by this method, but may be used by subclasses.
code_name (str): The name (on the class) that refers to this
property.
"""
self._code_name = code_name
if self._name is None:
self._name = code_name
def _store_value(self, entity, value):
"""Store a value in an entity for this property.
This assumes validation has already taken place. For a repeated
property the value should be a list.
Args:
entity (Model): An entity to set a value on.
value (Any): The value to be stored for this property.
"""
entity._values[self._name] = value
def _set_value(self, entity, value):
"""Set a value in an entity for a property.
This performs validation first. For a repeated property the value
should be a list (or similar container).
Args:
entity (Model): An entity to set a value on.
value (Any): The value to be stored for this property.
Raises:
ReadonlyPropertyError: If the ``entity`` is the result of a
projection query.
.BadValueError: If the current property is repeated but the
``value`` is not a basic container (:class:`list`,
:class:`tuple`, :class:`set` or :class:`frozenset`).
"""
if entity._projection:
raise ReadonlyPropertyError(
"You cannot set property values of a projection entity"
)
if self._repeated:
if not isinstance(value, (list, tuple, set, frozenset)):
raise exceptions.BadValueError(
"Expected list or tuple, got {!r}".format(value)
)
value = [self._do_validate(v) for v in value]
else:
if value is not None:
value = self._do_validate(value)
self._store_value(entity, value)
def _has_value(self, entity, unused_rest=None):
"""Determine if the entity has a value for this property.
Args:
entity (Model): An entity to check if the current property has
a value set.
unused_rest (None): An always unused keyword.
"""
return self._name in entity._values
def _retrieve_value(self, entity, default=None):
"""Retrieve the value for this property from an entity.
This returns :data:`None` if no value is set, or the ``default``
argument if given. For a repeated property this returns a list if a
value is set, otherwise :data:`None`. No additional transformations
are applied.
Args:
entity (Model): An entity to get a value from.
default (Optional[Any]): The default value to use as fallback.
"""
return entity._values.get(self._name, default)
def _get_user_value(self, entity):
"""Return the user value for this property of the given entity.
This implies removing the :class:`_BaseValue` wrapper if present, and
if it is, calling all ``_from_base_type()`` methods, in the reverse
method resolution order of the property's class. It also handles
default values and repeated properties.
Args:
entity (Model): An entity to get a value from.
Returns:
Any: The original value (if not :class:`_BaseValue`) or the wrapped
value converted from the base type.
"""
return self._apply_to_values(entity, self._opt_call_from_base_type)
def _get_base_value(self, entity):
"""Return the base value for this property of the given entity.
This implies calling all ``_to_base_type()`` methods, in the method
resolution order of the property's class, and adding a
:class:`_BaseValue` wrapper, if one is not already present. (If one
is present, no work is done.) It also handles default values and
repeated properties.
Args:
entity (Model): An entity to get a value from.
Returns:
Union[_BaseValue, List[_BaseValue]]: The original value
(if :class:`_BaseValue`) or the value converted to the base type
and wrapped.
"""
return self._apply_to_values(entity, self._opt_call_to_base_type)
def _get_base_value_unwrapped_as_list(self, entity):
"""Like _get_base_value(), but always returns a list.
Args:
entity (Model): An entity to get a value from.
Returns:
List[Any]: The unwrapped base values. For an unrepeated
property, if the value is missing or :data:`None`, returns
``[None]``; for a repeated property, if the original value is
missing or :data:`None` or empty, returns ``[]``.
"""
wrapped = self._get_base_value(entity)
if self._repeated:
return [w.b_val for w in wrapped]
else:
if wrapped is None:
return [None]
return [wrapped.b_val]
def _opt_call_from_base_type(self, value):
"""Call ``_from_base_type()`` if necessary.
If ``value`` is a :class:`_BaseValue`, unwrap it and call all
:math:`_from_base_type` methods. Otherwise, return the value
unchanged.
Args:
value (Any): The value to invoke :meth:`_call_from_base_type`
for.
Returns:
Any: The original value (if not :class:`_BaseValue`) or the value
converted from the base type.
"""
if isinstance(value, _BaseValue):
value = self._call_from_base_type(value.b_val)
return value
def _value_to_repr(self, value):
"""Turn a value (base or not) into its repr().
This exists so that property classes can override it separately.
This manually applies ``_from_base_type()`` so as not to have a side
effect on what's contained in the entity. Printing a value should not
change it.
Args:
value (Any): The value to convert to a pretty-print ``repr``.
Returns:
str: The ``repr`` of the "true" value.
"""
val = self._opt_call_from_base_type(value)
return repr(val)
def _opt_call_to_base_type(self, value):
"""Call ``_to_base_type()`` if necessary.
If ``value`` is a :class:`_BaseValue`, return it unchanged.
Otherwise, call all ``_validate()`` and ``_to_base_type()`` methods
and wrap it in a :class:`_BaseValue`.
Args:
value (Any): The value to invoke :meth:`_call_to_base_type`
for.
Returns:
_BaseValue: The original value (if :class:`_BaseValue`) or the
value converted to the base type and wrapped.
"""
if not isinstance(value, _BaseValue):
value = _BaseValue(self._call_to_base_type(value))
return value
def _call_from_base_type(self, value):
"""Call all ``_from_base_type()`` methods on the value.
This calls the methods in the reverse method resolution order of
the property's class.
Args:
value (Any): The value to be converted.
Returns:
Any: The transformed ``value``.
"""
methods = self._find_methods("_from_base_type", reverse=True)
call = self._apply_list(methods)
return call(value)
def _call_to_base_type(self, value):
"""Call all ``_validate()`` and ``_to_base_type()`` methods on value.
This calls the methods in the method resolution order of the
property's class. For example, given the hierarchy
.. code-block:: python
class A(Property):
def _validate(self, value):
...
def _to_base_type(self, value):
...
class B(A):
def _validate(self, value):
...
def _to_base_type(self, value):
...
class C(B):
def _validate(self, value):
...
the full list of methods (in order) is:
* ``C._validate()``
* ``B._validate()``
* ``B._to_base_type()``
* ``A._validate()``
* ``A._to_base_type()``
Args:
value (Any): The value to be converted / validated.
Returns:
Any: The transformed ``value``.
"""
methods = self._find_methods("_validate", "_to_base_type")
call = self._apply_list(methods)
return call(value)
def _call_shallow_validation(self, value):
"""Call the "initial" set of ``_validate()`` methods.
This is similar to :meth:`_call_to_base_type` except it only calls
those ``_validate()`` methods that can be called without needing to
call ``_to_base_type()``.
An example: suppose the class hierarchy is
.. code-block:: python
class A(Property):
def _validate(self, value):
...
def _to_base_type(self, value):
...
class B(A):
def _validate(self, value):
...
def _to_base_type(self, value):
...
class C(B):
def _validate(self, value):
...
The full list of methods (in order) called by
:meth:`_call_to_base_type` is:
* ``C._validate()``
* ``B._validate()``
* ``B._to_base_type()``
* ``A._validate()``
* ``A._to_base_type()``
whereas the full list of methods (in order) called here stops once
a ``_to_base_type()`` method is encountered:
* ``C._validate()``
* ``B._validate()``
Args:
value (Any): The value to be converted / validated.
Returns:
Any: The transformed ``value``.
"""
methods = []
for method in self._find_methods("_validate", "_to_base_type"):
# Stop if ``_to_base_type()`` is encountered.
if method.__name__ != "_validate":
break
methods.append(method)
call = self._apply_list(methods)
return call(value)
@classmethod
def _find_methods(cls, *names, reverse=False):
"""Compute a list of composable methods.
Because this is a common operation and the class hierarchy is
static, the outcome is cached (assuming that for a particular list
of names the reversed flag is either always on, or always off).
Args:
names (Tuple[str, ...]): One or more method names to look up on
the current class or base classes.
reverse (bool): Optional flag, default False; if True, the list is
reversed.
Returns:
List[Callable]: Class method objects.
"""
# Get cache on current class / set cache if it doesn't exist.
key = "{}.{}".format(cls.__module__, cls.__qualname__)
cache = cls._FIND_METHODS_CACHE.setdefault(key, {})
hit = cache.get(names)
if hit is not None:
if reverse:
return list(reversed(hit))
else:
return hit
methods = []
for klass in cls.__mro__:
for name in names:
method = klass.__dict__.get(name)
if method is not None:
methods.append(method)
cache[names] = methods
if reverse:
return list(reversed(methods))
else:
return methods
def _apply_list(self, methods):
"""Chain together a list of callables for transforming a value.
.. note::
Each callable in ``methods`` is an unbound instance method, e.g.
accessed via ``Property.foo`` rather than ``instance.foo``.
Therefore, calling these methods will require ``self`` as the
first argument.
If one of the method returns :data:`None`, the previous value is kept;
otherwise the last value is replace.
Exceptions thrown by a method in ``methods`` are not caught, so it
is up to the caller to catch them.
Args:
methods (Iterable[Callable[[Any], Any]]): An iterable of methods
to apply to a value.
Returns:
Callable[[Any], Any]: A callable that takes a single value and
applies each method in ``methods`` to it.
"""
def call(value):
for method in methods:
new_value = method(self, value)
if new_value is not None:
value = new_value
return value
return call
def _apply_to_values(self, entity, function):
"""Apply a function to the property value / values of a given entity.
This retrieves the property value, applies the function, and then
stores the value back. For a repeated property, the function is
applied separately to each of the values in the list. The
resulting value or list of values is both stored back in the
entity and returned from this method.
Args:
entity (Model): An entity to get a value from.
function (Callable[[Any], Any]): A transformation to apply to
the value.
Returns:
Any: The transformed value store on the entity for this property.
"""
value = self._retrieve_value(entity, self._default)
if self._repeated:
if value is None:
value = []
self._store_value(entity, value)
else:
# NOTE: This assumes, but does not check, that ``value`` is
# iterable. This relies on ``_set_value`` having checked
# and converted to a ``list`` for a repeated property.
value[:] = map(function, value)
else:
if value is not None:
new_value = function(value)
if new_value is not None and new_value is not value:
self._store_value(entity, new_value)
value = new_value
return value
def _get_value(self, entity):
"""Get the value for this property from an entity.
For a repeated property this initializes the value to an empty
list if it is not set.
Args:
entity (Model): An entity to get a value from.
Returns:
Any: The user value stored for the current property.
Raises:
UnprojectedPropertyError: If the ``entity`` is the result of a
projection query and the current property is not one of the
projected properties.
"""
if entity._projection:
if self._name not in entity._projection:
raise UnprojectedPropertyError(
"Property {} is not in the projection".format(self._name)
)
return self._get_user_value(entity)
def _delete_value(self, entity):
"""Delete the value for this property from an entity.
.. note::
If no value exists this is a no-op; deleted values will not be
serialized but requesting their value will return :data:`None` (or
an empty list in the case of a repeated property).
Args:
entity (Model): An entity to get a value from.
"""
if self._name in entity._values:
del entity._values[self._name]
def _is_initialized(self, entity):
"""Ask if the entity has a value for this property.
This returns :data:`False` if a value is stored but the stored value
is :data:`None`.
Args:
entity (Model): An entity to get a value from.
"""
return not self._required or (
(self._has_value(entity) or self._default is not None)
and self._get_value(entity) is not None
)
def __get__(self, entity, unused_cls=None):
"""Descriptor protocol: get the value from the entity.
Args:
entity (Model): An entity to get a value from.
unused_cls (type): The class that owns this instance.
"""
if entity is None:
# Handle the case where ``__get__`` is called on the class
# rather than an instance.
return self
return self._get_value(entity)
def __set__(self, entity, value):
"""Descriptor protocol: set the value on the entity.
Args:
entity (Model): An entity to set a value on.
value (Any): The value to set.
"""
self._set_value(entity, value)
def __delete__(self, entity):
"""Descriptor protocol: delete the value from the entity.
Args:
entity (Model): An entity to delete a value from.
"""
self._delete_value(entity)
def _serialize(
self, entity, pb, prefix="", parent_repeated=False, projection=None
):
"""Serialize this property to a protocol buffer.
Some subclasses may override this method.
Args:
entity (Model): The entity that owns this property.
pb (google.cloud.datastore_v1.proto.entity_pb2.Entity): An existing
entity protobuf instance that we'll add a value to.
prefix (Optional[str]): Name prefix used for
:class:`StructuredProperty` (if present, must end in ``.``).
parent_repeated (Optional[bool]): Indicates if the parent (or an
earlier ancestor) is a repeated property.
projection (Optional[Union[list, tuple]]): An iterable of strings
representing the projection for the model instance, or
:data:`None` if the instance is not a projection.
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
def _deserialize(self, entity, p, unused_depth=1):
"""Deserialize this property to a protocol buffer.
Some subclasses may override this method.
Args:
entity (Model): The entity that owns this property.
p (google.cloud.datastore_v1.proto.entity_pb2.Value): A property
value protobuf to be deserialized.
depth (int): Optional nesting depth, default 1 (unused here, but
used by some subclasses that override this method).
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
def _prepare_for_put(self, entity):
"""Allow this property to define a pre-put hook.
This base class implementation does nothing, but subclasses may
provide hooks.
Args:
entity (Model): An entity with values.
"""
pass
def _check_property(self, rest=None, require_indexed=True):
"""Check this property for specific requirements.
Called by ``Model._check_properties()``.
Args:
rest: Optional subproperty to check, of the form
``name1.name2...nameN``.
required_indexed (bool): Indicates if the current property must
be indexed.
Raises:
InvalidPropertyError: If ``require_indexed`` is :data:`True`
but the current property is not indexed.
InvalidPropertyError: If a subproperty is specified via ``rest``
(:class:`StructuredProperty` overrides this method to handle
subproperties).
"""
if require_indexed and not self._indexed:
raise InvalidPropertyError(
"Property is unindexed {}".format(self._name)
)
if rest:
raise InvalidPropertyError(
"Referencing subproperty {}.{} but {} is not a structured "
"property".format(self._name, rest, self._name)
)
def _get_for_dict(self, entity):
"""Retrieve the value like ``_get_value()``.
This is intended to be processed for ``_to_dict()``.
Property subclasses can override this if they want the dictionary
returned by ``entity._to_dict()`` to contain a different value. The
main use case is allowing :class:`StructuredProperty` and
:class:`LocalStructuredProperty` to allow the default ``_get_value()``
behavior.
* If you override ``_get_for_dict()`` to return a different type, you
must override ``_validate()`` to accept values of that type and
convert them back to the original type.
* If you override ``_get_for_dict()``, you must handle repeated values
and :data:`None` correctly. However, ``_validate()`` does not need to
handle these.
Args:
entity (Model): An entity to get a value from.
Returns:
Any: The user value stored for the current property.
"""
return self._get_value(entity)
def _validate_key(value, entity=None):
"""Validate a key.
Args:
value (.Key): The key to be validated.
entity (Optional[Model]): The entity that the key is being validated
for.
Returns:
.Key: The passed in ``value``.
Raises:
.BadValueError: If ``value`` is not a :class:`.Key`.
KindError: If ``entity`` is specified, but the kind of the entity
doesn't match the kind of ``value``.
"""
if not isinstance(value, Key):
raise exceptions.BadValueError("Expected Key, got {!r}".format(value))
if entity and type(entity) not in (Model, Expando):
if value.kind() != entity._get_kind():
raise KindError(
"Expected Key kind to be {}; received "
"{}".format(entity._get_kind(), value.kind())
)
return value
class ModelKey(Property):
"""Special property to store a special "key" for a :class:`Model`.
This is intended to be used as a psuedo-:class:`Property` on each
:class:`Model` subclass. It is **not** intended for other usage in
application code.
It allows key-only queries to be done for a given kind.
.. automethod:: _validate
"""
__slots__ = ()
def __init__(self):
super(ModelKey, self).__init__()
self._name = "__key__"
def _comparison(self, op, value):
"""Internal helper for comparison operators.
This uses the base implementation in :class:`Property`, but doesn't
allow comparison to :data:`None`.
Args:
op (str): The comparison operator. One of ``=``, ``!=``, ``<``,
``<=``, ``>``, ``>=`` or ``in``.
value (Any): The value to compare against.
Returns:
FilterNode: A FilterNode instance representing the requested
comparison.
Raises:
.BadValueError: If ``value`` is :data:`None`.
"""
if value is not None:
return super(ModelKey, self)._comparison(op, value)
raise exceptions.BadValueError(
"__key__ filter query can't be compared to None"
)
def _validate(self, value):
"""Validate a ``value`` before setting it.
Args:
value (.Key): The value to check.
Returns:
.Key: The passed-in ``value``.
"""
return _validate_key(value)
@staticmethod
def _set_value(entity, value):
"""Set the entity key on an entity.
Args:
entity (Model): An entity to set the entity key on.
value (.Key): The key to be set on the entity.
"""
if value is not None:
value = _validate_key(value, entity=entity)
value = entity._validate_key(value)
entity._entity_key = value
@staticmethod
def _get_value(entity):
"""Get the entity key from an entity.
Args:
entity (Model): An entity to get the entity key from.
Returns:
.Key: The entity key stored on ``entity``.
"""
return entity._entity_key
@staticmethod
def _delete_value(entity):
"""Remove / disassociate the entity key from an entity.
Args:
entity (Model): An entity to remove the entity key from.
"""
entity._entity_key = None
class BooleanProperty(Property):
"""A property that contains values of type bool.
.. automethod:: _validate
"""
__slots__ = ()
def _validate(self, value):
"""Validate a ``value`` before setting it.
Args:
value (bool): The value to check.
Returns:
bool: The passed-in ``value``.
Raises:
.BadValueError: If ``value`` is not a :class:`bool`.
"""
if not isinstance(value, bool):
raise exceptions.BadValueError(
"Expected bool, got {!r}".format(value)
)
return value
def _db_set_value(self, v, unused_p, value):
"""Helper for :meth:`_serialize`.
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
def _db_get_value(self, v, unused_p):
"""Helper for :meth:`_deserialize`.
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
class IntegerProperty(Property):
"""A property that contains values of type integer.
.. note::
If a value is a :class:`bool`, it will be coerced to ``0`` (for
:data:`False`) or ``1`` (for :data:`True`).
.. automethod:: _validate
"""
__slots__ = ()
def _validate(self, value):
"""Validate a ``value`` before setting it.
Args:
value (Union[int, bool]): The value to check.
Returns:
int: The passed-in ``value``.
Raises:
.BadValueError: If ``value`` is not an :class:`int` or convertible
to one.
"""
if not isinstance(value, int):
raise exceptions.BadValueError(
"Expected integer, got {!r}".format(value)
)
return int(value)
def _db_set_value(self, v, unused_p, value):
"""Helper for :meth:`_serialize`.
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
def _db_get_value(self, v, unused_p):
"""Helper for :meth:`_deserialize`.
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
class FloatProperty(Property):
"""A property that contains values of type float.
.. note::
If a value is a :class:`bool` or :class:`int`, it will be
coerced to a floating point value.
.. automethod:: _validate
"""
__slots__ = ()
def _validate(self, value):
"""Validate a ``value`` before setting it.
Args:
value (Union[float, int, bool]): The value to check.
Returns:
float: The passed-in ``value``, possibly converted to a
:class:`float`.
Raises:
.BadValueError: If ``value`` is not a :class:`float` or convertible
to one.
"""
if not isinstance(value, (float, int)):
raise exceptions.BadValueError(
"Expected float, got {!r}".format(value)
)
return float(value)
def _db_set_value(self, v, unused_p, value):
"""Helper for :meth:`_serialize`.
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
def _db_get_value(self, v, unused_p):
"""Helper for :meth:`_deserialize`.
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
class _CompressedValue:
"""A marker object wrapping compressed values.
Args:
z_val (bytes): A return value of ``zlib.compress``.
"""
__slots__ = ("z_val",)
def __init__(self, z_val):
self.z_val = z_val
def __repr__(self):
return "_CompressedValue({!r})".format(self.z_val)
def __eq__(self, other):
"""Compare two compressed values."""
if not isinstance(other, _CompressedValue):
return NotImplemented
return self.z_val == other.z_val
def __ne__(self, other):
"""Inequality comparison operation."""
return not self == other
def __hash__(self):
raise TypeError("_CompressedValue is not immutable")
class BlobProperty(Property):
"""A property that contains values that are byte strings.
.. note::
Unlike most property types, a :class:`BlobProperty` is **not**
indexed by default.
.. automethod:: _to_base_type
.. automethod:: _from_base_type
.. automethod:: _validate
Args:
name (str): The name of the property.
compressed (bool): Indicates if the value should be compressed (via
``zlib``).
indexed (bool): Indicates if the value should be indexed.
repeated (bool): Indicates if this property is repeated, i.e. contains
multiple values.
required (bool): Indicates if this property is required on the given
model type.
default (bytes): The default value for this property.
choices (Iterable[bytes]): A container of allowed values for this
property.
validator (Callable[[~google.cloud.ndb.model.Property, Any], bool]): A
validator to be used to check values.
verbose_name (str): A longer, user-friendly name for this property.
write_empty_list (bool): Indicates if an empty list should be written
to the datastore.
Raises:
NotImplementedError: If the property is both compressed and indexed.
"""
_indexed = False
_compressed = False
def __init__(
self,
name=None,
*,
compressed=None,
indexed=None,
repeated=None,
required=None,
default=None,
choices=None,
validator=None,
verbose_name=None,
write_empty_list=None
):
super(BlobProperty, self).__init__(
name=name,
indexed=indexed,
repeated=repeated,
required=required,
default=default,
choices=choices,
validator=validator,
verbose_name=verbose_name,
write_empty_list=write_empty_list,
)
if compressed is not None:
self._compressed = compressed
if self._compressed and self._indexed:
raise NotImplementedError(
"BlobProperty {} cannot be compressed and "
"indexed at the same time.".format(self._name)
)
def _value_to_repr(self, value):
"""Turn the value into a user friendly representation.
.. note::
This will truncate the value based on the "visual" length, e.g.
if it contains many ``\\xXX`` or ``\\uUUUU`` sequences, those
will count against the length as more than one character.
Args:
value (Any): The value to convert to a pretty-print ``repr``.
Returns:
str: The ``repr`` of the "true" value.
"""
long_repr = super(BlobProperty, self)._value_to_repr(value)
if len(long_repr) > _MAX_STRING_LENGTH + 4:
# Truncate, assuming the final character is the closing quote.
long_repr = long_repr[:_MAX_STRING_LENGTH] + "..." + long_repr[-1]
return long_repr
def _validate(self, value):
"""Validate a ``value`` before setting it.
Args:
value (bytes): The value to check.
Raises:
.BadValueError: If ``value`` is not a :class:`bytes`.
.BadValueError: If the current property is indexed but the value
exceeds the maximum length (1500 bytes).
"""
if not isinstance(value, bytes):
raise exceptions.BadValueError(
"Expected bytes, got {!r}".format(value)
)
if self._indexed and len(value) > _MAX_STRING_LENGTH:
raise exceptions.BadValueError(
"Indexed value {} must be at most {:d} "
"bytes".format(self._name, _MAX_STRING_LENGTH)
)
def _to_base_type(self, value):
"""Convert a value to the "base" value type for this property.
Args:
value (bytes): The value to be converted.
Returns:
Optional[bytes]: The converted value. If the current property is
compressed, this will return a wrapped version of the compressed
value. Otherwise, it will return :data:`None` to indicate that
the value didn't need to be converted.
"""
if self._compressed:
return _CompressedValue(zlib.compress(value))
def _from_base_type(self, value):
"""Convert a value from the "base" value type for this property.
Args:
value (bytes): The value to be converted.
Returns:
Optional[bytes]: The converted value. If the current property is
a (wrapped) compressed value, this will unwrap the value and return
the decompressed form. Otherwise, it will return :data:`None` to
indicate that the value didn't need to be unwrapped and
decompressed.
"""
if isinstance(value, _CompressedValue):
return zlib.decompress(value.z_val)
def _db_set_value(self, v, unused_p, value):
"""Helper for :meth:`_serialize`.
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
def _db_set_compressed_meaning(self, p):
"""Helper for :meth:`_db_set_value`.
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
def _db_set_uncompressed_meaning(self, p):
"""Helper for :meth:`_db_set_value`.
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
def _db_get_value(self, v, unused_p):
"""Helper for :meth:`_deserialize`.
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
class TextProperty(BlobProperty):
"""An unindexed property that contains UTF-8 encoded text values.
A :class:`TextProperty` is intended for values of unlimited length, hence
is **not** indexed. Previously, a :class:`TextProperty` could be indexed
via:
.. code-block:: python
class Item(ndb.Model):
description = ndb.TextProperty(indexed=True)
...
but this usage is no longer supported. If indexed text is desired, a
:class:`StringProperty` should be used instead.
.. automethod:: _to_base_type
.. automethod:: _from_base_type
.. automethod:: _validate
Raises:
NotImplementedError: If ``indexed=True`` is provided.
"""
__slots__ = ()
def __init__(self, *args, **kwargs):
indexed = kwargs.pop("indexed", False)
if indexed:
raise NotImplementedError(
"A TextProperty cannot be indexed. Previously this was "
"allowed, but this usage is no longer supported."
)
super(TextProperty, self).__init__(*args, **kwargs)
@property
def _indexed(self):
"""bool: Indicates that the property is not indexed."""
return False
def _validate(self, value):
"""Validate a ``value`` before setting it.
Args:
value (Union[bytes, str]): The value to check.
Raises:
.BadValueError: If ``value`` is :class:`bytes`, but is not a valid
UTF-8 encoded string.
.BadValueError: If ``value`` is neither :class:`bytes` nor
:class:`str`.
.BadValueError: If the current property is indexed but the UTF-8
encoded value exceeds the maximum length (1500 bytes).
"""
if isinstance(value, bytes):
try:
encoded_length = len(value)
value = value.decode("utf-8")
except UnicodeError:
raise exceptions.BadValueError(
"Expected valid UTF-8, got {!r}".format(value)
)
elif isinstance(value, str):
encoded_length = len(value.encode("utf-8"))
else:
raise exceptions.BadValueError(
"Expected string, got {!r}".format(value)
)
if self._indexed and encoded_length > _MAX_STRING_LENGTH:
raise exceptions.BadValueError(
"Indexed value {} must be at most {:d} "
"bytes".format(self._name, _MAX_STRING_LENGTH)
)
def _to_base_type(self, value):
"""Convert a value to the "base" value type for this property.
Args:
value (Union[bytes, str]): The value to be converted.
Returns:
Optional[bytes]: The converted value. If ``value`` is a
:class:`str`, this will return the UTF-8 encoded bytes for it.
Otherwise, it will return :data:`None`.
"""
if isinstance(value, str):
return value.encode("utf-8")
def _from_base_type(self, value):
"""Convert a value from the "base" value type for this property.
.. note::
Older versions of ``ndb`` could write non-UTF-8 ``TEXT``
properties. This means that if ``value`` is :class:`bytes`, but is
not a valid UTF-8 encoded string, it can't (necessarily) be
rejected. But, :meth:`_validate` now rejects such values, so it's
not possible to write new non-UTF-8 ``TEXT`` properties.
Args:
value (Union[bytes, str]): The value to be converted.
Returns:
Optional[str]: The converted value. If ``value`` is a a valid UTF-8
encoded :class:`bytes` string, this will return the decoded
:class:`str` corresponding to it. Otherwise, it will return
:data:`None`.
"""
if isinstance(value, bytes):
try:
return value.decode("utf-8")
except UnicodeError:
pass
def _db_set_uncompressed_meaning(self, p):
"""Helper for :meth:`_db_set_value`.
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
class StringProperty(TextProperty):
"""An indexed property that contains UTF-8 encoded text values.
This is nearly identical to :class:`TextProperty`, but is indexed. Values
must be at most 1500 bytes (when UTF-8 encoded from :class:`str` to bytes).
Raises:
NotImplementedError: If ``indexed=False`` is provided.
"""
__slots__ = ()
def __init__(self, *args, **kwargs):
indexed = kwargs.pop("indexed", True)
if not indexed:
raise NotImplementedError(
"A StringProperty must be indexed. Previously setting "
"``indexed=False`` was allowed, but this usage is no longer "
"supported."
)
super(StringProperty, self).__init__(*args, **kwargs)
@property
def _indexed(self):
"""bool: Indicates that the property is indexed."""
return True
class GeoPtProperty(Property):
"""A property that contains :attr:`.GeoPt` values.
.. automethod:: _validate
"""
__slots__ = ()
def _validate(self, value):
"""Validate a ``value`` before setting it.
Args:
value (~google.cloud.datastore.helpers.GeoPoint): The value to
check.
Raises:
.BadValueError: If ``value`` is not a :attr:`.GeoPt`.
"""
if not isinstance(value, GeoPt):
raise exceptions.BadValueError(
"Expected GeoPt, got {!r}".format(value)
)
def _db_set_value(self, v, p, value):
"""Helper for :meth:`_serialize`.
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
def _db_get_value(self, v, unused_p):
"""Helper for :meth:`_deserialize`.
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
class PickleProperty(BlobProperty):
"""A property that contains values that are pickle-able.
.. note::
Unlike most property types, a :class:`PickleProperty` is **not**
indexed by default.
This will use :func:`pickle.dumps` with the highest available pickle
protocol to convert to bytes and :func:`pickle.loads` to convert **from**
bytes. The base value stored in the datastore will be the pickled bytes.
.. automethod:: _to_base_type
.. automethod:: _from_base_type
"""
__slots__ = ()
def _to_base_type(self, value):
"""Convert a value to the "base" value type for this property.
Args:
value (Any): The value to be converted.
Returns:
bytes: The pickled ``value``.
"""
return pickle.dumps(value, pickle.HIGHEST_PROTOCOL)
def _from_base_type(self, value):
"""Convert a value from the "base" value type for this property.
Args:
value (bytes): The value to be converted.
Returns:
Any: The unpickled ``value``.
"""
return pickle.loads(value)
class JsonProperty(BlobProperty):
"""A property that contains JSON-encodable values.
.. note::
Unlike most property types, a :class:`JsonProperty` is **not**
indexed by default.
.. automethod:: _to_base_type
.. automethod:: _from_base_type
.. automethod:: _validate
Args:
name (str): The name of the property.
compressed (bool): Indicates if the value should be compressed (via
``zlib``).
json_type (type): The expected type of values that this property can
hold. If :data:`None`, any type is allowed.
indexed (bool): Indicates if the value should be indexed.
repeated (bool): Indicates if this property is repeated, i.e. contains
multiple values.
required (bool): Indicates if this property is required on the given
model type.
default (Any): The default value for this property.
choices (Iterable[Any]): A container of allowed values for this
property.
validator (Callable[[~google.cloud.ndb.model.Property, Any], bool]): A
validator to be used to check values.
verbose_name (str): A longer, user-friendly name for this property.
write_empty_list (bool): Indicates if an empty list should be written
to the datastore.
"""
_json_type = None
def __init__(
self,
name=None,
*,
compressed=None,
json_type=None,
indexed=None,
repeated=None,
required=None,
default=None,
choices=None,
validator=None,
verbose_name=None,
write_empty_list=None
):
super(JsonProperty, self).__init__(
name=name,
compressed=compressed,
indexed=indexed,
repeated=repeated,
required=required,
default=default,
choices=choices,
validator=validator,
verbose_name=verbose_name,
write_empty_list=write_empty_list,
)
if json_type is not None:
self._json_type = json_type
def _validate(self, value):
"""Validate a ``value`` before setting it.
Args:
value (Any): The value to check.
Raises:
TypeError: If the current property has a JSON type set and
``value`` is not an instance of that type.
"""
if self._json_type is None:
return
if not isinstance(value, self._json_type):
raise TypeError(
"JSON property must be a {}".format(self._json_type)
)
def _to_base_type(self, value):
"""Convert a value to the "base" value type for this property.
Args:
value (Any): The value to be converted.
Returns:
bytes: The ``value``, JSON encoded as an ASCII byte string.
"""
as_str = json.dumps(value, separators=(",", ":"), ensure_ascii=True)
return as_str.encode("ascii")
def _from_base_type(self, value):
"""Convert a value from the "base" value type for this property.
Args:
value (bytes): The value to be converted.
Returns:
Any: The ``value`` (ASCII bytes or string) loaded as JSON.
"""
return json.loads(value.decode("ascii"))
class UserProperty(Property):
__slots__ = ()
def __init__(self, *args, **kwargs):
raise NotImplementedError
class KeyProperty(Property):
"""A property that contains :class:`.Key` values.
The constructor for :class:`KeyProperty` allows at most two positional
arguments. Any usage of :data:`None` as a positional argument will
be ignored. Any of the following signatures are allowed:
.. testsetup:: key-property-constructor
from google.cloud import ndb
class SimpleModel(ndb.Model):
pass
.. doctest:: key-property-constructor
>>> name = "my_value"
>>> ndb.KeyProperty(name)
KeyProperty('my_value')
>>> ndb.KeyProperty(SimpleModel)
KeyProperty(kind='SimpleModel')
>>> ndb.KeyProperty(name, SimpleModel)
KeyProperty('my_value', kind='SimpleModel')
>>> ndb.KeyProperty(SimpleModel, name)
KeyProperty('my_value', kind='SimpleModel')
The type of the positional arguments will be used to determine their
purpose: a string argument is assumed to be the ``name`` and a
:class:`type` argument is assumed to be the ``kind`` (and checked that
the type is a subclass of :class:`Model`).
.. automethod:: _validate
Args:
name (str): The name of the property.
kind (Union[type, str]): The (optional) kind to be stored. If provided
as a positional argument, this must be a subclass of :class:`Model`
otherwise the kind name is sufficient.
indexed (bool): Indicates if the value should be indexed.
repeated (bool): Indicates if this property is repeated, i.e. contains
multiple values.
required (bool): Indicates if this property is required on the given
model type.
default (.Key): The default value for this property.
choices (Iterable[.Key]): A container of allowed values for this
property.
validator (Callable[[~google.cloud.ndb.model.Property, .Key], bool]): A
validator to be used to check values.
verbose_name (str): A longer, user-friendly name for this property.
write_empty_list (bool): Indicates if an empty list should be written
to the datastore.
"""
_kind = None
def __init__(
self,
*args,
name=None,
kind=None,
indexed=None,
repeated=None,
required=None,
default=None,
choices=None,
validator=None,
verbose_name=None,
write_empty_list=None
):
name, kind = self._handle_positional(args, name, kind)
super(KeyProperty, self).__init__(
name=name,
indexed=indexed,
repeated=repeated,
required=required,
default=default,
choices=choices,
validator=validator,
verbose_name=verbose_name,
write_empty_list=write_empty_list,
)
if kind is not None:
self._kind = kind
@staticmethod
def _handle_positional(args, name, kind):
"""Handle positional arguments.
In particular, assign them to the "correct" values and make sure
they don't collide with the relevant keyword arguments.
Args:
args (tuple): The positional arguments provided to the
constructor.
name (Optional[str]): The name that was provided as a keyword
argument to the constructor.
kind (Optional[Union[type, str]]): The kind that was provided as a
keyword argument to the constructor.
Returns:
Tuple[Optional[str], Optional[str]]: The ``name`` and ``kind``
inferred from the arguments. Either may be :data:`None`.
Raises:
TypeError: If ``args`` has more than 2 elements.
TypeError: If a valid ``name`` type (i.e. a string) is specified
twice in ``args``.
TypeError: If a valid ``kind`` type (i.e. a subclass of
:class:`Model`) is specified twice in ``args``.
TypeError: If an element in ``args`` is not a :class:`str` or a
subclass of :class:`Model`.
TypeError: If a ``name`` is specified both in ``args`` and via
the ``name`` keyword.
TypeError: If a ``kind`` is specified both in ``args`` and via
the ``kind`` keyword.
TypeError: If a ``kind`` was provided via ``keyword`` and is
not a :class:`str` or a subclass of :class:`Model`.
"""
# Limit positional arguments.
if len(args) > 2:
raise TypeError(
"The KeyProperty constructor accepts at most two "
"positional arguments."
)
# Filter out None
args = [value for value in args if value is not None]
# Determine the name / kind inferred from the positional arguments.
name_via_positional = None
kind_via_positional = None
for value in args:
if isinstance(value, str):
if name_via_positional is None:
name_via_positional = value
else:
raise TypeError("You can only specify one name")
elif isinstance(value, type) and issubclass(value, Model):
if kind_via_positional is None:
kind_via_positional = value
else:
raise TypeError("You can only specify one kind")
else:
raise TypeError(
"Unexpected positional argument: {!r}".format(value)
)
# Reconcile the two possible ``name``` values.
if name_via_positional is not None:
if name is None:
name = name_via_positional
else:
raise TypeError("You can only specify name once")
# Reconcile the two possible ``kind``` values.
if kind_via_positional is None:
if isinstance(kind, type) and issubclass(kind, Model):
kind = kind._get_kind()
else:
if kind is None:
kind = kind_via_positional._get_kind()
else:
raise TypeError("You can only specify kind once")
# Make sure the ``kind`` is a ``str``.
if kind is not None and not isinstance(kind, str):
raise TypeError("kind must be a Model class or a string")
return name, kind
def _constructor_info(self):
"""Helper for :meth:`__repr__`.
Yields:
Tuple[str, bool]: Pairs of argument name and a boolean indicating
if that argument is a keyword.
"""
yield "name", False
yield "kind", True
from_inspect = super(KeyProperty, self)._constructor_info()
for name, is_keyword in from_inspect:
if name in ("args", "name", "kind"):
continue
yield name, is_keyword
def _validate(self, value):
"""Validate a ``value`` before setting it.
Args:
value (.Key): The value to check.
Raises:
.BadValueError: If ``value`` is not a :class:`.Key`.
.BadValueError: If ``value`` is a partial :class:`.Key` (i.e. it
has no name or ID set).
.BadValueError: If the current property has an associated ``kind``
and ``value`` does not match that kind.
"""
if not isinstance(value, Key):
raise exceptions.BadValueError(
"Expected Key, got {!r}".format(value)
)
# Reject incomplete keys.
if not value.id():
raise exceptions.BadValueError(
"Expected complete Key, got {!r}".format(value)
)
# Verify kind if provided.
if self._kind is not None:
if value.kind() != self._kind:
raise exceptions.BadValueError(
"Expected Key with kind={!r}, got "
"{!r}".format(self._kind, value)
)
def _db_set_value(self, v, unused_p, value):
"""Helper for :meth:`_serialize`.
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
def _db_get_value(self, v, unused_p):
"""Helper for :meth:`_deserialize`.
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
class BlobKeyProperty(Property):
"""A property containing :class:`~google.cloud.ndb.model.BlobKey` values.
.. automethod:: _validate
"""
__slots__ = ()
def _validate(self, value):
"""Validate a ``value`` before setting it.
Args:
value (~google.cloud.ndb.model.BlobKey): The value to check.
Raises:
.BadValueError: If ``value`` is not a
:class:`~google.cloud.ndb.model.BlobKey`.
"""
if not isinstance(value, BlobKey):
raise exceptions.BadValueError(
"Expected BlobKey, got {!r}".format(value)
)
def _db_set_value(self, v, p, value):
"""Helper for :meth:`_serialize`.
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
def _db_get_value(self, v, unused_p):
"""Helper for :meth:`_deserialize`.
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
class DateTimeProperty(Property):
"""A property that contains :class:`~datetime.datetime` values.
This property expects "naive" datetime stamps, i.e. no timezone can
be set. Furthermore, the assumption is that naive datetime stamps
represent UTC.
.. note::
Unlike Django, ``auto_now_add`` can be overridden by setting the
value before writing the entity. And unlike the legacy
``google.appengine.ext.db``, ``auto_now`` does not supply a default
value. Also unlike legacy ``db``, when the entity is written, the
property values are updated to match what was written. Finally, beware
that this also updates the value in the in-process cache, **and** that
``auto_now_add`` may interact weirdly with transaction retries (a retry
of a property with ``auto_now_add`` set will reuse the value that was
set on the first try).
.. automethod:: _validate
.. automethod:: _prepare_for_put
Args:
name (str): The name of the property.
auto_now (bool): Indicates that the property should be set to the
current datetime when an entity is created and whenever it is
updated.
auto_now_add (bool): Indicates that the property should be set to the
current datetime when an entity is created.
indexed (bool): Indicates if the value should be indexed.
repeated (bool): Indicates if this property is repeated, i.e. contains
multiple values.
required (bool): Indicates if this property is required on the given
model type.
default (~datetime.datetime): The default value for this property.
choices (Iterable[~datetime.datetime]): A container of allowed values
for this property.
validator (Callable[[~google.cloud.ndb.model.Property, Any], bool]): A
validator to be used to check values.
verbose_name (str): A longer, user-friendly name for this property.
write_empty_list (bool): Indicates if an empty list should be written
to the datastore.
Raises:
ValueError: If ``repeated=True`` and ``auto_now=True``.
ValueError: If ``repeated=True`` and ``auto_now_add=True``.
"""
_auto_now = False
_auto_now_add = False
def __init__(
self,
name=None,
*,
auto_now=None,
auto_now_add=None,
indexed=None,
repeated=None,
required=None,
default=None,
choices=None,
validator=None,
verbose_name=None,
write_empty_list=None
):
super(DateTimeProperty, self).__init__(
name=name,
indexed=indexed,
repeated=repeated,
required=required,
default=default,
choices=choices,
validator=validator,
verbose_name=verbose_name,
write_empty_list=write_empty_list,
)
if self._repeated:
if auto_now:
raise ValueError(
"DateTimeProperty {} could use auto_now and be "
"repeated, but there would be no point.".format(self._name)
)
elif auto_now_add:
raise ValueError(
"DateTimeProperty {} could use auto_now_add and be "
"repeated, but there would be no point.".format(self._name)
)
if auto_now is not None:
self._auto_now = auto_now
if auto_now_add is not None:
self._auto_now_add = auto_now_add
def _validate(self, value):
"""Validate a ``value`` before setting it.
Args:
value (~datetime.datetime): The value to check.
Raises:
.BadValueError: If ``value`` is not a :class:`~datetime.datetime`.
"""
if not isinstance(value, datetime.datetime):
raise exceptions.BadValueError(
"Expected datetime, got {!r}".format(value)
)
@staticmethod
def _now():
"""datetime.datetime: Return current datetime.
Subclasses will override this to return different forms of "now".
"""
return datetime.datetime.utcnow()
def _prepare_for_put(self, entity):
"""Sets the current timestamp when "auto" is set.
If one of the following scenarios occur
* ``auto_now=True``
* ``auto_now_add=True`` and the ``entity`` doesn't have a value set
then this hook will run before the ``entity`` is ``put()`` into
the datastore.
Args:
entity (Model): An entity with values.
"""
if self._auto_now or (
self._auto_now_add and not self._has_value(entity)
):
value = self._now()
self._store_value(entity, value)
def _db_set_value(self, v, p, value):
"""Helper for :meth:`_serialize`.
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
def _db_get_value(self, v, unused_p):
"""Helper for :meth:`_deserialize`.
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
class DateProperty(DateTimeProperty):
"""A property that contains :class:`~datetime.date` values.
.. automethod:: _to_base_type
.. automethod:: _from_base_type
.. automethod:: _validate
"""
__slots__ = ()
def _validate(self, value):
"""Validate a ``value`` before setting it.
Args:
value (~datetime.date): The value to check.
Raises:
.BadValueError: If ``value`` is not a :class:`~datetime.date`.
"""
if not isinstance(value, datetime.date):
raise exceptions.BadValueError(
"Expected date, got {!r}".format(value)
)
def _to_base_type(self, value):
"""Convert a value to the "base" value type for this property.
Args:
value (~datetime.date): The value to be converted.
Returns:
~datetime.datetime: The converted value: a datetime object with the
time set to ``00:00``.
Raises:
TypeError: If ``value`` is not a :class:`~datetime.date`.
"""
if not isinstance(value, datetime.date):
raise TypeError(
"Cannot convert to datetime expected date value; "
"received {}".format(value)
)
return datetime.datetime(value.year, value.month, value.day)
def _from_base_type(self, value):
"""Convert a value from the "base" value type for this property.
Args:
value (~datetime.datetime): The value to be converted.
Returns:
~datetime.date: The converted value: the date that ``value``
occurs on.
"""
return value.date()
@staticmethod
def _now():
"""datetime.datetime: Return current date."""
return datetime.datetime.utcnow().date()
class TimeProperty(DateTimeProperty):
"""A property that contains :class:`~datetime.time` values.
.. automethod:: _to_base_type
.. automethod:: _from_base_type
.. automethod:: _validate
"""
__slots__ = ()
def _validate(self, value):
"""Validate a ``value`` before setting it.
Args:
value (~datetime.time): The value to check.
Raises:
.BadValueError: If ``value`` is not a :class:`~datetime.time`.
"""
if not isinstance(value, datetime.time):
raise exceptions.BadValueError(
"Expected time, got {!r}".format(value)
)
def _to_base_type(self, value):
"""Convert a value to the "base" value type for this property.
Args:
value (~datetime.time): The value to be converted.
Returns:
~datetime.datetime: The converted value: a datetime object with the
date set to ``1970-01-01``.
Raises:
TypeError: If ``value`` is not a :class:`~datetime.time`.
"""
if not isinstance(value, datetime.time):
raise TypeError(
"Cannot convert to datetime expected time value; "
"received {}".format(value)
)
return datetime.datetime(
1970,
1,
1,
value.hour,
value.minute,
value.second,
value.microsecond,
)
def _from_base_type(self, value):
"""Convert a value from the "base" value type for this property.
Args:
value (~datetime.datetime): The value to be converted.
Returns:
~datetime.time: The converted value: the time that ``value``
occurs at.
"""
return value.time()
@staticmethod
def _now():
"""datetime.datetime: Return current time."""
return datetime.datetime.utcnow().time()
class StructuredProperty(Property):
__slots__ = ()
def __init__(self, *args, **kwargs):
raise NotImplementedError
class LocalStructuredProperty(BlobProperty):
__slots__ = ()
def __init__(self, *args, **kwargs):
raise NotImplementedError
class GenericProperty(Property):
__slots__ = ()
def __init__(self, *args, **kwargs):
raise NotImplementedError
class ComputedProperty(GenericProperty):
__slots__ = ()
def __init__(self, *args, **kwargs):
raise NotImplementedError
class MetaModel(type):
__slots__ = ()
def __new__(self, *args, **kwargs):
raise NotImplementedError
class Model:
__slots__ = ("_entity_key",)
def __init__(self, *args, **kwargs):
raise NotImplementedError
@classmethod
def _get_kind(cls):
"""Return the kind name for this class.
This defaults to ``cls.__name__``; users may override this to give a
class a different name when stored in Google Cloud Datastore than the
name of the class.
"""
return cls.__name__
@staticmethod
def _validate_key(key):
"""Validation for ``_key`` attribute (designed to be overridden).
Args:
key (.Key): Proposed key to use for this entity.
Returns:
.Key: The validated ``key``.
"""
return key
class Expando(Model):
__slots__ = ()
def __init__(self, *args, **kwargs):
raise NotImplementedError
def transaction(*args, **kwargs):
raise NotImplementedError
def transaction_async(*args, **kwargs):
raise NotImplementedError
def in_transaction(*args, **kwargs):
raise NotImplementedError
def transactional(*args, **kwargs):
raise NotImplementedError
def transactional_async(*args, **kwargs):
raise NotImplementedError
def transactional_tasklet(*args, **kwargs):
raise NotImplementedError
def non_transactional(*args, **kwargs):
raise NotImplementedError
def get_multi_async(*args, **kwargs):
raise NotImplementedError
def get_multi(*args, **kwargs):
raise NotImplementedError
def put_multi_async(*args, **kwargs):
raise NotImplementedError
def put_multi(*args, **kwargs):
raise NotImplementedError
def delete_multi_async(*args, **kwargs):
raise NotImplementedError
def delete_multi(*args, **kwargs):
raise NotImplementedError
def get_indexes_async(*args, **kwargs):
raise NotImplementedError
def get_indexes(*args, **kwargs):
raise NotImplementedError
| {
"content_hash": "a6a8bd482cb3a524e881971437680288",
"timestamp": "",
"source": "github",
"line_count": 3035,
"max_line_length": 79,
"avg_line_length": 31.97825370675453,
"alnum_prop": 0.5746079502132834,
"repo_name": "jonparrott/google-cloud-python",
"id": "a45135173c03b6082a4e98b84d4d00a395e44e14",
"size": "97630",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ndb/src/google/cloud/ndb/model.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3366"
},
{
"name": "PowerShell",
"bytes": "7195"
},
{
"name": "Protocol Buffer",
"bytes": "62009"
},
{
"name": "Python",
"bytes": "3459300"
},
{
"name": "Shell",
"bytes": "7548"
}
],
"symlink_target": ""
} |
from muntjac.ui.text_field import TextField
from muntjac.demo.sampler.APIResource import APIResource
from muntjac.demo.sampler.Feature import Feature, Version
class TextFieldSingle(Feature):
def getSinceVersion(self):
return Version.OLD
def getName(self):
return 'Text field'
def getDescription(self):
return ('A single-line TextField is a fundamental UI building blocks'
' with numerous uses.<br/>'
'If the input would benefit from remembering previous values,'
' you might want to consider using a ComboBox it it\'s '
' \'suggesting mode\' instead.')
def getRelatedAPI(self):
return [APIResource(TextField)]
def getRelatedFeatures(self):
from muntjac.demo.sampler.FeatureSet import Texts
from muntjac.demo.sampler.features.text.TextFieldSecret import TextFieldSecret
from muntjac.demo.sampler.features.selects.ComboBoxNewItems import ComboBoxNewItems
# TODO update CB -ref to 'suggest' pattern, when available
return [TextFieldSecret, ComboBoxNewItems, Texts]
def getRelatedResources(self):
# TODO Auto-generated method stub
return None
| {
"content_hash": "e6ae3090657845c84c308dae3082923c",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 91,
"avg_line_length": 29.634146341463413,
"alnum_prop": 0.6962962962962963,
"repo_name": "rwl/muntjac",
"id": "ddc043472af8ce5294c50f05b9a3724907b7e609",
"size": "1216",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "muntjac/demo/sampler/features/text/TextFieldSingle.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "8602"
},
{
"name": "Java",
"bytes": "2243"
},
{
"name": "JavaScript",
"bytes": "32438"
},
{
"name": "Python",
"bytes": "3212361"
}
],
"symlink_target": ""
} |
__author__ = 'mpetyx'
from django.db import models
import tweepy
class TwitterInteraction(models.Model):
user_name = models.TextField()
post_id = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
screen_name = models.TextField()
text = models.TextField()
#profile_url = models.StringProperty()
#access_token = models.StringProperty()
def add_interaction(user_name, screen_name, text, post_id):
interaction = TwitterInteraction(user_name= user_name, screen_name = screen_name, text = text, post_id = post_id)
interaction.save()
return 1
class retrieve:
def __init__(self, auth=None):
"""
I suppose i have a connection, otherwise i open one
"""
if auth is None:
self.auth = "initialize connection"
else:
self.auth = auth
self.count = 5
def RoundRobin(self):
"""
Here we are going to decide about the statuses
that we are going to track
"""
return 1
def statistics(self):
#https://dev.twitter.com/doc/get/statuses/mentions
auth = self.auth
api = tweepy.API(auth)
#lolen = api.retweets( id, count=self.count)# ,since_id= self.last_twitter_id)
lolen = api.retweets_of_me()
statuses = []
lolen = lolen + api.retweeted_to_me()
for status in lolen:
user = status.user
name = user.screen_name
text = status.text
id = status.id
full_name = user.name
#http://apiwiki.twitter.com/w/page/22554664/Return-Values
created_at = status.created_at
statuses.append(self.myStatus(name,text,id,full_name))
for mention in api.mentions(count=self.count):# ,since_id= self.last_twitter_id)
user = mention.user
name = user.screen_name
text = mention.text
id = mention.id
full_name = user.name
#http://apiwiki.twitter.com/w/page/22554664/Return-Values
created_at = mention.created_at
myMention = self.myStatus(name,text,id,full_name)
if myMention in statuses:
continue
else:
statuses.append(myMention)
for status in statuses:
add_interaction(user_name = status['full_name'], screen_name = status['name'], text = status['text'], post_id = status['id'])
def create_friendship(self, friend):
return self.auth.create_friendship(friend)
def myStatus(self, name, text,id, full_name):
id = str(id)
return {'name':name, 'text':text, 'id':id,"full_name":full_name}
| {
"content_hash": "050fe1d20c5425f9176d32629f523a39",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 137,
"avg_line_length": 28.12121212121212,
"alnum_prop": 0.5858477011494253,
"repo_name": "mpetyx/pychatbot",
"id": "03e88eed36f2324f0dc31c341cbb6b230a81c6eb",
"size": "2784",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AIML/AliceTwitter/AliceOnHeroku/AliceOnHeroku/models.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "99757"
},
{
"name": "C++",
"bytes": "1736027"
},
{
"name": "CSS",
"bytes": "287248"
},
{
"name": "D",
"bytes": "5487330"
},
{
"name": "Java",
"bytes": "4140"
},
{
"name": "JavaScript",
"bytes": "8460"
},
{
"name": "Objective-C",
"bytes": "39"
},
{
"name": "PHP",
"bytes": "4179"
},
{
"name": "Perl",
"bytes": "40530"
},
{
"name": "Python",
"bytes": "943590"
},
{
"name": "Shell",
"bytes": "175258"
},
{
"name": "TeX",
"bytes": "234627"
},
{
"name": "XSLT",
"bytes": "4027675"
}
],
"symlink_target": ""
} |
import unittest
import mock
class DynamicFieldsMixinTestCase(unittest.TestCase):
"""Test functionality of the DynamicFieldsMixin class."""
def test_restrict_dynamic_fields(self):
| {
"content_hash": "35e69858f9b44390d8d46cb96183de64",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 61,
"avg_line_length": 17.545454545454547,
"alnum_prop": 0.7668393782383419,
"repo_name": "chewse/djangorestframework-dynamic-fields",
"id": "ca9198c77845cbc0a2b089f49a673c1229f12c1b",
"size": "218",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test_dynamicfields.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "4100"
}
],
"symlink_target": ""
} |
"""Settings reused by other settings."""
import os
DEBUG = False
SANDBOX = False
PROJECT_ROOT = os.path.realpath(
os.path.join(os.path.dirname(__file__), "../.."))
| {
"content_hash": "067e8a77518b6f2282830bf7b6688682",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 53,
"avg_line_length": 21.25,
"alnum_prop": 0.6529411764705882,
"repo_name": "bitmazk/webfaction-django1.4-boilerplate",
"id": "2306cc9aba1f5fd27c57864be05af5b1e53831b4",
"size": "170",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "website/webapps/django/myproject/myproject/settings/base_settings.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "64"
},
{
"name": "Python",
"bytes": "32979"
},
{
"name": "Shell",
"bytes": "3664"
}
],
"symlink_target": ""
} |
def extractChococatshomeWpcomstagingCom(item):
'''
Parser for 'chococatshome.wpcomstaging.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
| {
"content_hash": "3089e6fe435db9d94de8f2914fafe619",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 104,
"avg_line_length": 27.19047619047619,
"alnum_prop": 0.6427320490367776,
"repo_name": "fake-name/ReadableWebProxy",
"id": "be57c5eca9c77641626fb65512596a353c174c7b",
"size": "572",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WebMirror/management/rss_parser_funcs/feed_parse_extractChococatshomeWpcomstagingCom.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "105811"
},
{
"name": "Dockerfile",
"bytes": "1178"
},
{
"name": "HTML",
"bytes": "119737"
},
{
"name": "JavaScript",
"bytes": "3006524"
},
{
"name": "Jupyter Notebook",
"bytes": "148075"
},
{
"name": "Mako",
"bytes": "1454"
},
{
"name": "Python",
"bytes": "5264346"
},
{
"name": "Shell",
"bytes": "1059"
}
],
"symlink_target": ""
} |
import os
import logging
import uuid
import urlparse
from google.appengine.api import users
from google.appengine.api import urlfetch
from google.appengine.api import taskqueue
from google.appengine.ext import db
import webapp2
from webapp2_extras import jinja2
from webapp2_extras import sessions
import datetime
from cardchecker import CardChecker
import errors
import data
from app_engine_util import send_email
import utils
import utils.times
import utils.filters
from gael.urlfetch import Transcriber, PayloadEncoder, RedirectFollower, CookieHandler, Securer
from authomatic import Authomatic
from authomatic.adapters import Webapp2Adapter
import config
authomatic = Authomatic(
config=config.authomatic_config,
secret='secret',
report_errors=True,
logging_level=logging.DEBUG)
clock = utils.times.Clock()
class MyHandler(webapp2.RequestHandler):
@webapp2.cached_property
def jinja(self):
jinja2.default_config['environment_args']['autoescape'] = False
j = jinja2.get_jinja2(app=self.app)
utils.filters.register_all(j.environment)
return j
def handle_exception(self, exception, debug_mode):
error_uid = uuid.uuid4()
logging.critical('Error ' + str(error_uid) + ' caught. Unable to proceed.', exc_info=True)
message_body = str(self.request)
for attr in ('user', 'family'):
if hasattr(self.request, attr):
message_body += '\n' + attr + ': ' + str(getattr(self.request, attr))
send_email(['librarianhippo@gmail.com'],
'LibraryHippo Error ' + str(error_uid),
body=message_body)
self.template_values['error_uid'] = error_uid
self.render('error.html')
self.response.set_status(500)
def render(self, template_file):
self.response.out.write(self.jinja.render_template(template_file, **self.template_values))
def dispatch(self):
self.template_values = {}
# Get a session store for this request.
self.session_store = sessions.get_store(request=self.request)
try:
self.assert_is_allowed()
webapp2.RequestHandler.dispatch(self)
finally:
# Save all sessions.
self.session_store.save_sessions(self.response)
@webapp2.cached_property
def session(self):
# Returns a session using the default cookie key.
return self.session_store.get_session()
def get_family(self):
user_email = self.session.get('user_email')
impersonating_user_email = self.session.get('impersonating_user_email')
logging.debug('user_email = %s', user_email)
logging.debug('impersonating_user_email = %s', impersonating_user_email)
if not user_email:
self.session['next_url'] = self.request.url
self.redirect('/oauth2/google')
return (None, None)
if impersonating_user_email is not None:
self.template_values['stop_impersonating_url'] = '/admin/stopimpersonating'
user_email = impersonating_user_email
user = users.User(user_email)
family = None
for f in data.Family.all():
for p in f.principals:
principal_email = p.email()
if principal_email == user.email():
user = p
family = f
break
self.template_values['logout_url'] = '/logout'
if self.is_current_user_admin():
self.template_values['control_panel_url'] = '/admin/controlpanel'
logging.info('user = [%s] and family = [%s]', user, family)
return (user, family)
def is_allowed(self):
if self.is_current_user_admin():
logging.debug('is_allowed: returning true because [%s] is an admin', self.session.get('user_email'))
return True
path = urlparse.urlsplit(self.request.url).path
if path.startswith('/admin/'):
logging.debug('is_allowed: returning false because [%s] is not an admin', self.session.get('user_email'))
return False
else:
logging.debug('is_allowed: assuming true because [%s] is not an admin-only URL', self.request.url)
return True
def is_current_user_admin(self):
return self.session.get('user_email') == 'blair.conrad@gmail.com'
def assert_is_allowed(self):
if not self.is_allowed():
self.abort(403)
class OAuth2(MyHandler):
def get(self, provider_name):
result = authomatic.login(Webapp2Adapter(self), provider_name)
if result:
if result.error:
error_message = result.error.message
raise(Exception('Login failed to [%s]. Error was [%s].' % (provider_name, error_message)))
elif result.user:
if not (result.user.name and result.user.id):
logging.debug('No name or id. Getting.')
result.user.update()
logging.info('user = [%s, %s, %s]', result.user.name, result.user.id, result.user.email)
self.session['user_email'] = result.user.email
next_url = self.session.get('next_url') or '/'
logging.debug('redirecting to %s', next_url)
return self.redirect(str(next_url))
else:
raise(Exception('Login to [%(provider_name)s] succeeded, but no user was returned.' % vars()))
class Account(MyHandler):
def get(self):
(user, family) = self.get_family()
if user is None:
return
libraries = data.Library.all()
self.template_values.update({
'family': family,
'libraries': libraries,
'cards': family and list(family.card_set) or [],
'principals': family and family.principals or [],
})
self.render('account.html')
class SaveCard(MyHandler):
def post(self):
(user, family) = self.get_family()
if not family:
self.redirect('/account')
return
card = data.Card(parent=family,
family=family,
number=self.request.get('number'),
name=self.request.get('name'),
pin=self.request.get('pin'),
library=data.Library.get(self.request.get('library_id'))
)
card.put()
self.redirect('/account')
class RemoveCard(MyHandler):
def get(self, card_key):
(user, family) = self.get_family()
card = data.Card.get(card_key)
if card.family.key() == family.key():
logging.info('removing card %s', card.to_xml())
card.delete()
family.put()
logging.info('saved family %s', family.to_xml())
else:
logging.error('request to remove card %s from family %s failed', card.to_xml(), family.to_xml())
self.redirect('/account')
class ChangePin(MyHandler):
def get(self, card_key, new_pin):
(user, family) = self.get_family()
card = data.Card.get(card_key)
if card.family.key() == family.key():
logging.info('updating pin for card %s', card.to_xml())
card.pin = new_pin
card.put()
logging.info('saved card')
else:
logging.error('request to update pin for card %s that belongs to family %s failed',
card.to_xml(), family.to_xml())
self.redirect('/account')
class RemoveResponsible(MyHandler):
def post(self):
(user, family) = self.get_family()
removed_a_principal = False
for principal_email in self.request.arguments():
principal = users.User(principal_email)
if principal in family.principals:
send_email([principal_email],
'LibraryHippo: you are no longer a responsible person for the ' + family.name + ' family',
body=user.email() + ' has removed you from being a responsible person for the ' +
family.name + 'family at LibraryHippo (http://libraryhippo.com)')
logging.info('removing principal %s ', principal)
family.principals.remove(principal)
removed_a_principal = True
else:
logging.error('request to remove principal %s from family %s failed', principal, family.to_xml())
if len(family.principals) == 0:
logging.info('no more principals - removing family %s', family.to_xml())
cards = [c for c in family.card_set]
db.delete(cards + [family])
else:
if removed_a_principal:
family.put()
logging.info('saved family %s', family.to_xml())
self.redirect('/account')
class SaveFamily(MyHandler):
def post(self):
(user, family) = self.get_family()
if not family:
family = data.Family()
send_email(['librarianhippo@gmail.com'],
'New family ' + self.request.get('name') + ' registered',
body=('registered to ' + str(user)))
family.name = self.request.get('name')
if not family.principals:
family.principals = [user]
family.put()
self.redirect('/account')
class AddResponsible(MyHandler):
def post(self):
(user, family) = self.get_family()
if not family:
self.redirect('/account')
new_principal = users.User(self.request.get('email'))
if new_principal not in family.principals:
if data.Family.all().filter('principals = ', new_principal).count():
logging.info('%s is a member of a different family', new_principal.email())
self.template_values.update({
'title': 'User Belongs to Another Family',
'message': new_principal.email() + ' is already responsible for another family',
})
self.render('info.html')
return
else:
send_email([new_principal.email()],
'LibraryHippo: you are now a responsible person for the ' + family.name + ' family',
body=user.email() + ' has made you a responsible person for the ' + family.name +
' family.\nLearn more by visiting LibraryHippo at http://libraryhippo.com')
family.principals.append(new_principal)
family.put()
else:
logging.debug(new_principal.email() + ' is already in ' + family.name)
self.redirect('/account')
def make_test_summary(family):
card = family.card_set[0]
h = data.Hold(card.library, card)
h.title = 'A Book'
h.author = 'Some Author'
h.url = 'http://books.wpl.ca/record=2017161~S3'
h.status = data.Hold.READY
h.pickup = 'The Book Source'
h.add_status_note('note 1')
h.add_status_note('note 2')
holds_ready = [h]
template_values = {}
template_values['holds_ready'] = holds_ready
template_values['items_due'] = []
template_values['info'] = []
template_values['family'] = family
return template_values
def build_template(statuses, family):
holds = sum((status.holds for status in statuses), [])
items = sum((status.items for status in statuses), [])
info = sum((status.info for status in statuses), [])
holds.sort()
items.sort()
today = clock.today()
item_due_cutoff = today + datetime.timedelta(days=3)
items_due_soon = []
items_due_later = []
for item in items:
if item.status <= item_due_cutoff:
items_due_soon.append(item)
else:
items_due_later.append(item)
hold_expires_cutoff = today + datetime.timedelta(days=30)
holds_ready = []
holds_not_ready = []
for hold in holds:
if hold.status == data.Hold.READY:
holds_ready.append(hold)
else:
holds_not_ready.append(hold)
if hold.expires <= hold_expires_cutoff:
hold.add_status_note('expires on ' + utils.filters.duedate(hold.expires))
template_values = {}
template_values['family'] = family
template_values['should_notify'] = False
template_values['holds_ready'] = holds_ready
template_values['holds_not_ready'] = holds_not_ready
template_values['items_due'] = items_due_soon
template_values['items_not_due'] = items_due_later
template_values['info'] = []
template_values['info'] += info
template_values['error'] = bool(template_values['info'])
if template_values['info'] or template_values['holds_ready'] or template_values['items_due']:
template_values['should_notify'] = True
expiry_first_warning_date = today + datetime.timedelta(days=7)
for status in statuses:
if status.expires <= expiry_first_warning_date:
logging.debug('card expires within a week')
if status.expires == today or status.expires == expiry_first_warning_date:
template_values['should_notify'] = True
if status.expires < today:
message = 'card expired on ' + str(status.expires)
elif status.expires == today:
message = 'card expires today'
else:
message = 'card expires on ' + utils.filters.duedate(status.expires)
template_values['info'] += [data.CardInfo(status.library_name, status.patron_name, message)]
return template_values
class Summary(MyHandler):
def get(self):
(user, family) = self.get_family()
if not user:
return
if not family:
self.redirect('/account')
return
self.template_values['cards'] = [card for card in family.card_set]
self.template_values['family'] = family
self.render('summary.html')
class CheckCardBase(MyHandler):
def check_card(self, user, card):
fetcher = PayloadEncoder(RedirectFollower(CookieHandler(Securer(Transcriber(urlfetch.fetch)))))
checker = CardChecker()
try:
card_status = checker.check(user, card, fetcher)
except errors.TransientError as e:
self.response.set_status(504)
card_status = e.card_status
return card_status
class CheckCard(CheckCardBase):
def get(self, card_key):
(user, family) = self.get_family()
logging.info('CheckCard called ' + card_key)
card = data.Card.get(card_key)
if family.key() != card.family.key():
logging.error('access denied: card family = ' + str(card.family) + ' family = ' + str(family))
card_status = data.CardStatus(card)
card_status.add_failure()
else:
card_status = self.check_card(user=user, card=card)
self.template_values.update(build_template([card_status], family))
self.render('ajax_content.html')
class Welcome(MyHandler):
def get(self):
self.render('welcome.html')
class About(MyHandler):
def get(self):
self.render('about.html')
class AdminNotify(MyHandler):
def load_summary(self, family, checked_cards):
logging.info('getting summary for family = ' + str(family.name))
statuses = [c.payload for c in checked_cards]
template = build_template(statuses, family)
for c in checked_cards:
elapsed = clock.utcnow() - c.datetime
if elapsed > datetime.timedelta(hours=20):
time_since_check = utils.filters.elapsed(elapsed)
logging.error('unable to check card for ' + time_since_check)
template['should_notify'] = True
why_link = '<a href="http://libraryhippo.com/about#check_failed">Why?</a>'
template['info'].append(data.CardInfo(c.payload.library_name, c.payload.patron_name,
'Unable to check card for ' + time_since_check + '. ' +
why_link))
return template
def get(self, family_key):
family = data.Family.get(family_key)
if not family:
raise Exception('no family')
# what happens if there are cards that have never been checked? Don't worry for now.
checked_cards = data.CheckedCard.all().filter('card IN ', list(family.card_set))
template_values = self.load_summary(family, checked_cards)
if not template_values['should_notify']:
logging.debug('no reason to notify')
return
subject = utils.build_notification_subject(template_values['info'],
template_values['items_due'],
template_values['holds_ready'])
if subject:
bccs = []
if template_values['error']:
bccs = ['librarianhippo@gmail.com']
send_email([a.email() for a in family.principals],
subject,
bccs=bccs,
html=self.jinja.render_template('email.html', **template_values))
class AdminNotifyTest(MyHandler):
def get(self, family_key):
for_family = data.Family.get(family_key)
if not for_family:
raise Exception('no family')
template_values = make_test_summary(for_family)
send_email([a.email() for a in for_family.principals],
'LibraryHippo status for ' + for_family.name + ' Family',
html=self.jinja.render_template('email.html', **template_values))
class CheckAllCards(MyHandler):
def get(self):
cards = data.Card.all().fetch(1000)
tasks = [taskqueue.Task(url='/system/checkcard/' + str(card.key()), method='GET') for card in cards]
q = taskqueue.Queue()
q.add(tasks)
message = 'finished queuing tasks to check %d cards' % (len(tasks),)
logging.info(message)
self.response.out.write(message)
class AdminCheckCard(CheckCardBase):
def get(self, card_key):
card = data.Card.get(card_key)
self.check_card(user=users.get_current_user(), card=card)
class ListFamilies(MyHandler):
def get(self):
families = data.Family.all().fetch(1000)
logging.debug(families)
self.template_values.update({'families': families})
self.render('families.html')
class ControlPanel(MyHandler):
def get(self):
if os.environ['SERVER_SOFTWARE'].startswith('Development'):
dashboard = 'http://localhost:8000/datastore'
else:
dashboard = 'https://console.cloud.google.com/home/dashboard?project=libraryhippo27'
self.template_values = {'dashboard': dashboard}
self.render('controlpanel.html')
class Impersonate(MyHandler):
def get(self, username):
self.session['impersonating_user_email'] = username
self.template_values.update({'user': username})
self.render('impersonate.html')
return
class ViewCheckedCards(MyHandler):
def get(self, family_key):
family = data.Family.get(family_key)
if not family:
raise Exception('no family')
checked_cards = data.CheckedCard.all().filter('card IN ', list(family.card_set)).fetch(1000)
statuses = [cc.payload for cc in checked_cards]
logging.debug('found ' + str(len(statuses)) + ' statuses')
self.template_values = build_template(statuses, family)
self.render('static_summary.html')
class AuditLog(MyHandler):
def get(self, page='1'):
page = int(page, 10)
now = clock.utcnow()
events = []
for e in data.Event.all() \
.filter('date_time_saved >', now - datetime.timedelta(days=page)) \
.filter('date_time_saved <', now - datetime.timedelta(days=page - 1)) \
.order('-date_time_saved'):
logging.debug('Event user = ' + str(e.user))
events.append(e)
self.template_values = {'events': events, 'previouspage': page - 1, 'nextpage': page + 1}
self.render('auditlog.html')
class StopImpersonating(MyHandler):
def get(self):
self.session['impersonating_user_email'] = None
self.redirect('/')
return
class NotifyAll(MyHandler):
def get(self):
count = 0
families = data.Family.all().fetch(1000)
for family in families:
count += 1
notify_url = '/system/notify/' + str(family.key())
logging.info('queuing notify task for [%s] at [%s]', family.name, notify_url)
taskqueue.add(url=notify_url, method='GET')
message = 'queued tasks for %d families' % (count,)
logging.info(message)
self.response.out.write(message)
class NotFound(MyHandler):
def get(self):
self.render('notfound.html')
self.response.set_status(404)
class PopulateData(MyHandler):
def get(self):
libraries = {}
for l in data.Library.all():
libraries[l.name] = l
for l in (
('Waterloo Public Library', 'wpl'),
('Kitchener Public Library', 'kpl'),
('Region of Waterloo Library', 'rwl'),
):
lib = libraries.setdefault(l[0], data.Library())
lib.name = l[0]
lib.type = l[1]
db.put(libraries.values())
self.response.out.write('done')
class Logout(MyHandler):
def get(self):
self.session['impersonating_user_email'] = None
self.session['user_email'] = None
self.redirect('/')
logging.getLogger().setLevel(logging.DEBUG)
logging.info('running main')
handlers = [
('/oauth2/([a-z]+)', OAuth2),
('/checkcard/(.*)$', CheckCard),
('/savecard', SaveCard),
('/removecard/(.*)$', RemoveCard),
('/changepin/(.*)/(.*)$', ChangePin),
('/admin/notify/(.*)$', AdminNotify),
('/system/notify/(.*)$', AdminNotify),
('/admin/notifytest/(.*)$', AdminNotifyTest),
('/admin/impersonate/(.*)$', Impersonate),
('/admin/checkcard/(.*)$', AdminCheckCard),
('/system/checkcard/(.*)$', AdminCheckCard),
('/admin/checkedcards/(.*)$', ViewCheckedCards),
('/admin/auditlog$', AuditLog),
('/admin/auditlog/(.*)$', AuditLog),
('/$', Welcome),
]
for c in (About, Summary, Account, SaveFamily, AddResponsible, SaveCard, RemoveResponsible, Logout):
handlers.append(('/' + c.__name__.lower() + '$', c))
for c in (ListFamilies, PopulateData, NotifyAll, CheckAllCards, StopImpersonating, ControlPanel):
handlers.append(('/admin/' + c.__name__.lower() + '$', c))
for c in (NotifyAll, CheckAllCards):
handlers.append(('/system/' + c.__name__.lower() + '$', c))
handlers.append(('.*', NotFound))
application = webapp2.WSGIApplication(handlers, debug=True, config=config.webapp2_config)
| {
"content_hash": "942ffbfc26456a7b6d5bd69ac67c3bea",
"timestamp": "",
"source": "github",
"line_count": 666,
"max_line_length": 117,
"avg_line_length": 34.7987987987988,
"alnum_prop": 0.5859509837763204,
"repo_name": "blairconrad/LibraryHippo",
"id": "72a9ab38e657a8004e003bb6736448fb57b348ee",
"size": "23176",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "App/libraryhippo.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "695"
},
{
"name": "CSS",
"bytes": "3022"
},
{
"name": "HTML",
"bytes": "34134"
},
{
"name": "JavaScript",
"bytes": "3492"
},
{
"name": "Python",
"bytes": "516038"
}
],
"symlink_target": ""
} |
import re
import os
import sys
import warnings
from numpy.distutils.cpuinfo import cpu
from numpy.distutils.fcompiler import FCompiler
from numpy.distutils.exec_command import exec_command
from numpy.distutils.misc_util import msvc_runtime_library
compilers = ['GnuFCompiler', 'Gnu95FCompiler']
class GnuFCompiler(FCompiler):
compiler_type = 'gnu'
compiler_aliases = ('g77',)
description = 'GNU Fortran 77 compiler'
def gnu_version_match(self, version_string):
"""Handle the different versions of GNU fortran compilers"""
m = re.match(r'GNU Fortran', version_string)
if not m:
return None
m = re.match(r'GNU Fortran\s+95.*?([0-9-.]+)', version_string)
if m:
return ('gfortran', m.group(1))
m = re.match(r'GNU Fortran.*?([0-9-.]+)', version_string)
if m:
v = m.group(1)
if v.startswith('0') or v.startswith('2') or v.startswith('3'):
# the '0' is for early g77's
return ('g77', v)
else:
# at some point in the 4.x series, the ' 95' was dropped
# from the version string
return ('gfortran', v)
def version_match(self, version_string):
v = self.gnu_version_match(version_string)
if not v or v[0] != 'g77':
return None
return v[1]
# 'g77 --version' results
# SunOS: GNU Fortran (GCC 3.2) 3.2 20020814 (release)
# Debian: GNU Fortran (GCC) 3.3.3 20040110 (prerelease) (Debian)
# GNU Fortran (GCC) 3.3.3 (Debian 20040401)
# GNU Fortran 0.5.25 20010319 (prerelease)
# Redhat: GNU Fortran (GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)) 3.2.2 20030222 (Red Hat Linux 3.2.2-5)
# GNU Fortran (GCC) 3.4.2 (mingw-special)
possible_executables = ['g77', 'f77']
executables = {
'version_cmd' : [None, "--version"],
'compiler_f77' : [None, "-g", "-Wall", "-fno-second-underscore"],
'compiler_f90' : None, # Use --fcompiler=gnu95 for f90 codes
'compiler_fix' : None,
'linker_so' : [None, "-g", "-Wall"],
'archiver' : ["ar", "-cr"],
'ranlib' : ["ranlib"],
'linker_exe' : [None, "-g", "-Wall"]
}
module_dir_switch = None
module_include_switch = None
# Cygwin: f771: warning: -fPIC ignored for target (all code is
# position independent)
if os.name != 'nt' and sys.platform != 'cygwin':
pic_flags = ['-fPIC']
# use -mno-cygwin for g77 when Python is not Cygwin-Python
if sys.platform == 'win32':
for key in ['version_cmd', 'compiler_f77', 'linker_so', 'linker_exe']:
executables[key].append('-mno-cygwin')
g2c = 'g2c'
suggested_f90_compiler = 'gnu95'
#def get_linker_so(self):
# # win32 linking should be handled by standard linker
# # Darwin g77 cannot be used as a linker.
# #if re.match(r'(darwin)', sys.platform):
# # return
# return FCompiler.get_linker_so(self)
def get_flags_linker_so(self):
opt = self.linker_so[1:]
if sys.platform=='darwin':
# MACOSX_DEPLOYMENT_TARGET must be at least 10.3. This is
# a reasonable default value even when building on 10.4 when using
# the official Python distribution and those derived from it (when
# not broken).
target = os.environ.get('MACOSX_DEPLOYMENT_TARGET', None)
if target is None or target == '':
target = '10.3'
major, minor = target.split('.')
if int(minor) < 3:
minor = '3'
warnings.warn('Environment variable '
'MACOSX_DEPLOYMENT_TARGET reset to %s.%s' % (major, minor))
os.environ['MACOSX_DEPLOYMENT_TARGET'] = '%s.%s' % (major,
minor)
opt.extend(['-undefined', 'dynamic_lookup', '-bundle'])
else:
opt.append("-shared")
if sys.platform.startswith('sunos'):
# SunOS often has dynamically loaded symbols defined in the
# static library libg2c.a The linker doesn't like this. To
# ignore the problem, use the -mimpure-text flag. It isn't
# the safest thing, but seems to work. 'man gcc' says:
# ".. Instead of using -mimpure-text, you should compile all
# source code with -fpic or -fPIC."
opt.append('-mimpure-text')
return opt
def get_libgcc_dir(self):
status, output = exec_command(self.compiler_f77 +
['-print-libgcc-file-name'],
use_tee=0)
if not status:
return os.path.dirname(output)
return None
def get_library_dirs(self):
opt = []
if sys.platform[:5] != 'linux':
d = self.get_libgcc_dir()
if d:
# if windows and not cygwin, libg2c lies in a different folder
if sys.platform == 'win32' and not d.startswith('/usr/lib'):
d = os.path.normpath(d)
if not os.path.exists(os.path.join(d, 'libg2c.a')):
d2 = os.path.abspath(os.path.join(d,
'../../../../lib'))
if os.path.exists(os.path.join(d2, 'libg2c.a')):
opt.append(d2)
opt.append(d)
return opt
def get_libraries(self):
opt = []
d = self.get_libgcc_dir()
if d is not None:
g2c = self.g2c + '-pic'
f = self.static_lib_format % (g2c, self.static_lib_extension)
if not os.path.isfile(os.path.join(d,f)):
g2c = self.g2c
else:
g2c = self.g2c
if g2c is not None:
opt.append(g2c)
c_compiler = self.c_compiler
if sys.platform == 'win32' and c_compiler and \
c_compiler.compiler_type=='msvc':
# the following code is not needed (read: breaks) when using MinGW
# in case want to link F77 compiled code with MSVC
opt.append('gcc')
runtime_lib = msvc_runtime_library()
if runtime_lib:
opt.append(runtime_lib)
if sys.platform == 'darwin':
opt.append('cc_dynamic')
return opt
def get_flags_debug(self):
return ['-g']
def get_flags_opt(self):
if self.get_version()<='3.3.3':
# With this compiler version building Fortran BLAS/LAPACK
# with -O3 caused failures in lib.lapack heevr,syevr tests.
opt = ['-O2']
else:
opt = ['-O3']
opt.append('-funroll-loops')
return opt
def get_flags_arch(self):
opt = []
if sys.platform == 'darwin':
# Since Apple doesn't distribute a GNU Fortran compiler, we
# can't add -arch ppc or -arch i386, as only their version
# of the GNU compilers accepts those.
for a in '601 602 603 603e 604 604e 620 630 740 7400 7450 750'\
'403 505 801 821 823 860'.split():
if getattr(cpu,'is_ppc%s'%a)():
opt.append('-mcpu='+a)
opt.append('-mtune='+a)
break
return opt
# default march options in case we find nothing better
if cpu.is_i686():
march_opt = '-march=i686'
elif cpu.is_i586():
march_opt = '-march=i586'
elif cpu.is_i486():
march_opt = '-march=i486'
elif cpu.is_i386():
march_opt = '-march=i386'
else:
march_opt = ''
gnu_ver = self.get_version()
if gnu_ver >= '0.5.26': # gcc 3.0
if cpu.is_AthlonK6():
march_opt = '-march=k6'
elif cpu.is_AthlonK7():
march_opt = '-march=athlon'
if gnu_ver >= '3.1.1':
if cpu.is_AthlonK6_2():
march_opt = '-march=k6-2'
elif cpu.is_AthlonK6_3():
march_opt = '-march=k6-3'
elif cpu.is_AthlonMP():
march_opt = '-march=athlon-mp'
# there's also: athlon-tbird, athlon-4, athlon-xp
elif cpu.is_Nocona():
march_opt = '-march=nocona'
elif cpu.is_Core2():
march_opt = '-march=nocona'
elif cpu.is_Xeon() and cpu.is_64bit():
march_opt = '-march=nocona'
elif cpu.is_Prescott():
march_opt = '-march=prescott'
elif cpu.is_PentiumIV():
march_opt = '-march=pentium4'
elif cpu.is_PentiumIII():
march_opt = '-march=pentium3'
elif cpu.is_PentiumM():
march_opt = '-march=pentium3'
elif cpu.is_PentiumII():
march_opt = '-march=pentium2'
if gnu_ver >= '3.4':
# Actually, I think these all do the same things
if cpu.is_Opteron():
march_opt = '-march=opteron'
elif cpu.is_Athlon64():
march_opt = '-march=athlon64'
elif cpu.is_AMD64():
march_opt = '-march=k8'
if gnu_ver >= '3.4.4':
if cpu.is_PentiumM():
march_opt = '-march=pentium-m'
# Future:
# if gnu_ver >= '4.3':
# if cpu.is_Core2():
# march_opt = '-march=core2'
# Note: gcc 3.2 on win32 has breakage with -march specified
if '3.1.1' <= gnu_ver <= '3.4' and sys.platform=='win32':
march_opt = ''
if march_opt:
opt.append(march_opt)
# other CPU flags
if gnu_ver >= '3.1.1':
if cpu.has_mmx(): opt.append('-mmmx')
if cpu.has_3dnow(): opt.append('-m3dnow')
if gnu_ver > '3.2.2':
if cpu.has_sse2(): opt.append('-msse2')
if cpu.has_sse(): opt.append('-msse')
if gnu_ver >= '3.4':
if cpu.has_sse3(): opt.append('-msse3')
if cpu.is_Intel():
opt.append('-fomit-frame-pointer')
if cpu.is_32bit():
opt.append('-malign-double')
return opt
class Gnu95FCompiler(GnuFCompiler):
compiler_type = 'gnu95'
compiler_aliases = ('gfortran',)
description = 'GNU Fortran 95 compiler'
def version_match(self, version_string):
v = self.gnu_version_match(version_string)
if not v or v[0] != 'gfortran':
return None
return v[1]
# 'gfortran --version' results:
# XXX is the below right?
# Debian: GNU Fortran 95 (GCC 4.0.3 20051023 (prerelease) (Debian 4.0.2-3))
# GNU Fortran 95 (GCC) 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)
# OS X: GNU Fortran 95 (GCC) 4.1.0
# GNU Fortran 95 (GCC) 4.2.0 20060218 (experimental)
# GNU Fortran (GCC) 4.3.0 20070316 (experimental)
possible_executables = ['gfortran', 'f95']
executables = {
'version_cmd' : ["<F90>", "--version"],
'compiler_f77' : [None, "-Wall", "-ffixed-form",
"-fno-second-underscore"],
'compiler_f90' : [None, "-Wall", "-fno-second-underscore"],
'compiler_fix' : [None, "-Wall", "-ffixed-form",
"-fno-second-underscore"],
'linker_so' : ["<F90>", "-Wall"],
'archiver' : ["ar", "-cr"],
'ranlib' : ["ranlib"],
'linker_exe' : [None, "-Wall"]
}
# use -mno-cygwin flag for g77 when Python is not Cygwin-Python
if sys.platform == 'win32':
for key in ['version_cmd', 'compiler_f77', 'compiler_f90',
'compiler_fix', 'linker_so', 'linker_exe']:
executables[key].append('-mno-cygwin')
module_dir_switch = '-J'
module_include_switch = '-I'
g2c = 'gfortran'
# Note that this is here instead of GnuFCompiler as gcc < 4 uses a
# different output format (which isn't as useful) than gcc >= 4,
# and we don't have to worry about g77 being universal (as it can't be).
def target_architecture(self, extra_opts=()):
"""Return the architecture that the compiler will build for.
This is most useful for detecting universal compilers in OS X."""
extra_opts = list(extra_opts)
status, output = exec_command(self.compiler_f90 + ['-v'] + extra_opts,
use_tee=False)
if status == 0:
m = re.match(r'(?m)^Target: (.*)$', output)
if m:
return m.group(1)
return None
def is_universal_compiler(self):
"""Return True if this compiler can compile universal binaries
(for OS X).
Currently only checks for i686 and powerpc architectures (no 64-bit
support yet).
"""
if sys.platform != 'darwin':
return False
i686_arch = self.target_architecture(extra_opts=['-arch', 'i686'])
if not i686_arch or not i686_arch.startswith('i686-'):
return False
ppc_arch = self.target_architecture(extra_opts=['-arch', 'ppc'])
if not ppc_arch or not ppc_arch.startswith('powerpc-'):
return False
return True
def _add_arches_for_universal_build(self, flags):
if self.is_universal_compiler():
flags[:0] = ['-arch', 'i686', '-arch', 'ppc']
return flags
def get_flags(self):
flags = GnuFCompiler.get_flags(self)
return self._add_arches_for_universal_build(flags)
def get_flags_linker_so(self):
flags = GnuFCompiler.get_flags_linker_so(self)
return self._add_arches_for_universal_build(flags)
def get_libraries(self):
opt = GnuFCompiler.get_libraries(self)
if sys.platform == 'darwin':
opt.remove('cc_dynamic')
return opt
if __name__ == '__main__':
from distutils import log
log.set_verbosity(2)
compiler = GnuFCompiler()
compiler.customize()
print compiler.get_version()
raw_input('Press ENTER to continue...')
try:
compiler = Gnu95FCompiler()
compiler.customize()
print compiler.get_version()
except Exception, msg:
print msg
raw_input('Press ENTER to continue...')
| {
"content_hash": "c9cdf227394658894f939dc366b10b86",
"timestamp": "",
"source": "github",
"line_count": 387,
"max_line_length": 109,
"avg_line_length": 37.354005167958654,
"alnum_prop": 0.5278085224128389,
"repo_name": "santisiri/popego",
"id": "b281cb5c1513aeee18b742a7f94205315a3f8563",
"size": "14456",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "envs/ALPHA-POPEGO/lib/python2.5/site-packages/numpy-1.0.4-py2.5-linux-x86_64.egg/numpy/distutils/fcompiler/gnu.py",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1246"
},
{
"name": "C",
"bytes": "504141"
},
{
"name": "C++",
"bytes": "26125"
},
{
"name": "CSS",
"bytes": "342653"
},
{
"name": "FORTRAN",
"bytes": "4872"
},
{
"name": "GAP",
"bytes": "13267"
},
{
"name": "Genshi",
"bytes": "407"
},
{
"name": "Groff",
"bytes": "17116"
},
{
"name": "HTML",
"bytes": "383181"
},
{
"name": "JavaScript",
"bytes": "1090769"
},
{
"name": "Makefile",
"bytes": "2441"
},
{
"name": "Mako",
"bytes": "376944"
},
{
"name": "Python",
"bytes": "20895618"
},
{
"name": "Ruby",
"bytes": "3380"
},
{
"name": "Shell",
"bytes": "23581"
},
{
"name": "Smarty",
"bytes": "522"
},
{
"name": "TeX",
"bytes": "35712"
}
],
"symlink_target": ""
} |
from __future__ import absolute_import
import hashlib
import jwt
from six.moves.urllib.parse import quote
from sentry.shared_integrations.exceptions import ApiError
def percent_encode(val):
# see https://en.wikipedia.org/wiki/Percent-encoding
return quote(val.encode("utf8", errors="replace")).replace("%7E", "~").replace("/", "%2F")
def get_query_hash(uri, method, query_params=None):
# see
# https://developer.atlassian.com/static/connect/docs/latest/concepts/understanding-jwt.html#qsh
uri = uri.rstrip("/")
method = method.upper()
if query_params is None:
query_params = {}
sorted_query = []
for k, v in sorted(query_params.items()):
# don't include jwt query param
if k != "jwt":
if isinstance(v, list):
param_val = [percent_encode(val) for val in v].join(",")
else:
param_val = percent_encode(v)
sorted_query.append("%s=%s" % (percent_encode(k), param_val))
query_string = "%s&%s&%s" % (method, uri, "&".join(sorted_query))
return hashlib.sha256(query_string.encode("utf8")).hexdigest()
def get_jira_auth_from_request(request):
# https://developer.atlassian.com/static/connect/docs/latest/concepts/authentication.html
# Extract the JWT token from the request's jwt query
# parameter or the authorization header.
token = request.GET.get("jwt")
if token is None:
raise ApiError("No token parameter")
# Decode the JWT token, without verification. This gives
# you a header JSON object, a claims JSON object, and a signature.
decoded = jwt.decode(token, verify=False)
# Extract the issuer ('iss') claim from the decoded, unverified
# claims object. This is the clientKey for the tenant - an identifier
# for the Atlassian application making the call
issuer = decoded["iss"]
# Look up the sharedSecret for the clientKey, as stored
# by the add-on during the installation handshake
from sentry_plugins.jira_ac.models import JiraTenant
jira_auth = JiraTenant.objects.get(client_key=issuer)
# Verify the signature with the sharedSecret and
# the algorithm specified in the header's alg field.
decoded_verified = jwt.decode(token, jira_auth.secret)
# Verify the query has not been tampered by Creating a Query Hash
# and comparing it against the qsh claim on the verified token.
# TODO: probably shouldn't need to hardcode get... for post maybe
# the secret should just be a hidden field in the form ?
qsh = get_query_hash(request.path, "GET", request.GET)
# qsh = get_query_hash(request.path, request.method, request.GET)
if qsh != decoded_verified["qsh"]:
raise ApiError("Query hash mismatch")
return jira_auth
| {
"content_hash": "c60152f3035965ee0cc869ef28411f06",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 100,
"avg_line_length": 39.77142857142857,
"alnum_prop": 0.6767241379310345,
"repo_name": "beeftornado/sentry",
"id": "8cc28aea3c06f6aa32d4e7ec6ea390ae07958b22",
"size": "2784",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/sentry_plugins/jira_ac/utils.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "157195"
},
{
"name": "HTML",
"bytes": "197026"
},
{
"name": "JavaScript",
"bytes": "380379"
},
{
"name": "Makefile",
"bytes": "2832"
},
{
"name": "Python",
"bytes": "6473603"
}
],
"symlink_target": ""
} |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import compas_rhino
from compas.artists import PrimitiveArtist
from compas.colors import Color
from .artist import RhinoArtist
class PointArtist(RhinoArtist, PrimitiveArtist):
"""Artist for drawing points.
Parameters
----------
point : :class:`~compas.geometry.Point`
A COMPAS point.
layer : str, optional
The layer that should contain the drawing.
**kwargs : dict, optional
Additional keyword arguments.
For more info, see :class:`RhinoArtist` and :class:`PrimitiveArtist`.
"""
def __init__(self, point, layer=None, **kwargs):
super(PointArtist, self).__init__(primitive=point, layer=layer, **kwargs)
def draw(self, color=None):
"""Draw the point.
Parameters
----------
color : tuple[int, int, int] | tuple[float, float, float] | :class:`~compas.colors.Color`, optional
The RGB color of the point.
Default is :attr:`compas.artists.PrimitiveArtist.color`.
Returns
-------
list[System.Guid]
The GUIDs of the created Rhino objects.
"""
color = Color.coerce(color) or self.color
points = [
{
"pos": list(self.primitive),
"color": color.rgb255,
"name": self.primitive.name,
}
]
guids = compas_rhino.draw_points(points, layer=self.layer, clear=False, redraw=False)
return guids
| {
"content_hash": "166ca0cbb892414a5f5e02f240279ace",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 107,
"avg_line_length": 29.81132075471698,
"alnum_prop": 0.5974683544303797,
"repo_name": "compas-dev/compas",
"id": "fb9ca67ff4ad0b4c1ed0084aeb9784482bec33f3",
"size": "1580",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/compas_rhino/artists/pointartist.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "3181804"
}
],
"symlink_target": ""
} |
from conans.util.files import load, save
from conans.model.version import Version
from conans.errors import ConanException
import os
CONAN_VERSION = "version.txt"
class Migrator(object):
def __init__(self, conf_path, store_path, current_version, out):
self.conf_path = conf_path
self.store_path = store_path
self.current_version = current_version
self.file_version_path = os.path.join(self.conf_path, CONAN_VERSION)
self.out = out
def migrate(self):
old_version = self._load_old_version()
if old_version != self.current_version:
self._make_migrations(old_version)
self._update_version_file()
def _make_migrations(self, old_version):
raise NotImplementedError("Implement in subclass")
def _update_version_file(self):
try:
save(self.file_version_path, str(self.current_version))
except Exception:
raise ConanException("Can't write version file in %s" % self.file_version_path)
def _load_old_version(self):
try:
tmp = load(self.file_version_path)
old_version = Version(tmp)
except:
old_version = None
return old_version
| {
"content_hash": "620ebfa450f9873a66e764ab2b2a93fd",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 91,
"avg_line_length": 30.85,
"alnum_prop": 0.6345218800648298,
"repo_name": "mropert/conan",
"id": "8be5f257bc5d3d737bc9842efd4a99cd450cb764",
"size": "1234",
"binary": false,
"copies": "4",
"ref": "refs/heads/develop",
"path": "conans/migrations.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "653"
},
{
"name": "Python",
"bytes": "1898890"
},
{
"name": "Shell",
"bytes": "1342"
}
],
"symlink_target": ""
} |
"""
Herald core beans definition
:author: Thomas Calmant
:copyright: Copyright 2014, isandlaTech
:license: Apache License 2.0
:version: 0.0.4
:status: Alpha
..
Copyright 2014 isandlaTech
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
# Module version
__version_info__ = (0, 0, 4)
__version__ = ".".join(str(x) for x in __version_info__)
# Documentation strings format
__docformat__ = "restructuredtext en"
# ------------------------------------------------------------------------------
# Standard library
import functools
import threading
import time
import uuid
import json
# import herald module to use constantes
import herald
import herald.utils as utils
# ------------------------------------------------------------------------------
@functools.total_ordering
class Peer(object):
"""
Represents a peer in Herald
"""
def __init__(self, uid, node_uid, app_id, groups, directory):
"""
Sets up the peer
:param uid: Peer Unique ID
:param node_uid: Node Unique ID
:param app_id: Peer Application ID
:param groups: The list of groups this peer belongs to
:param directory: Directory to call back on access update
:raise ValueError: Invalid Peer UID
"""
if not uid:
raise ValueError("The UID of a peer can't be empty")
self.__uid = uid
self.__name = uid
self.__node = node_uid or uid
self.__node_name = self.__node
self.__app_id = app_id
self.__groups = set(groups or [])
self.__accesses = {}
self.__directory = directory
self.__lock = threading.RLock()
def __repr__(self):
"""
Peer representation
"""
return "Peer({0})".format(self.__uid)
def __str__(self):
"""
Peer pretty representation
"""
if self.__name and self.__name != self.__uid:
return "{0} ({1})".format(self.__name, self.__uid)
else:
return self.__uid
def __hash__(self):
"""
Use the UID string hash as bean hash
"""
return hash(self.__uid)
def __eq__(self, other):
"""
Equality is based on the UID
"""
if isinstance(other, Peer):
return self.__uid == other.uid
return False
def __lt__(self, other):
"""
Ordering is based on the UID
"""
if isinstance(other, Peer):
return self.__uid < other.uid
return False
@property
def uid(self):
"""
Retrieves the UID of the peer
"""
return self.__uid
@property
def app_id(self):
"""
Returns the ID of the application this peer is part of
"""
return self.__app_id
@property
def name(self):
"""
Retrieves the name of the peer
"""
return self.__name
@name.setter
def name(self, value):
"""
Sets the name of the peer
:param value: A peer name
"""
self.__name = value or self.__uid
@property
def node_uid(self):
"""
Retrieves the UID of the node hosting the peer
"""
return self.__node
@property
def node_name(self):
"""
Retrieves the name of the node hosting the peer
"""
return self.__node_name
@node_name.setter
def node_name(self, value):
"""
Sets the name of the node hosting the peer
:param value: A node name
"""
self.__node_name = value or self.__node
@property
def groups(self):
"""
Retrieves the set of groups this peer belongs
"""
return self.__groups.copy()
def __callback(self, method_name, *args):
"""
Calls back the associated directory
:param method_name: Name of the method to call
:param args: Arguments of the method to call back
"""
try:
method = getattr(self.__directory, method_name)
except AttributeError:
# Directory not available/not fully implemented
pass
else:
# Always give this bean as first parameter
return method(self, *args)
def dump(self):
"""
Dumps the content of this Peer into a dictionary
:return: A dictionary describing this peer
"""
# Properties
dump = {name: getattr(self, name)
for name in ('uid', 'name', 'node_uid', 'node_name',
'app_id', 'groups')}
# Accesses
dump['accesses'] = {access: data.dump()
for access, data in self.__accesses.items()}
return dump
def get_access(self, access_id):
"""
Retrieves the description of the access stored with the given ID
:param access_id: An access ID (xmpp, http, ...)
:return: The description associated to the given ID
:raise KeyError: Access not described
"""
return self.__accesses[access_id]
def get_accesses(self):
"""
Returns the list of access IDs associated to this peer
:return: A list of access IDs
"""
return tuple(self.__accesses)
def has_access(self, access_id):
"""
Checks if the access is described
:param access_id: An access ID
:return: True if the access is described
"""
return access_id in self.__accesses
def has_accesses(self):
"""
Checks if the peer has any access
:return: True if the peer has at least one access
"""
return bool(self.__accesses)
def set_access(self, access_id, data):
"""
Sets the description associated to an access ID.
:param access_id: An access ID (xmpp, http, ...)
:param data: The description associated to the given ID
"""
with self.__lock:
try:
old_data = self.__accesses[access_id]
except KeyError:
# Unknown data
old_data = None
if data != old_data:
# Update only if necessary
self.__accesses[access_id] = data
if not isinstance(data, RawAccess):
self.__callback("peer_access_set", access_id, data)
def unset_access(self, access_id):
"""
Removes and returns the description associated to an access ID.
:param access_id: An access ID (xmpp, http, ...)
:return: The associated description, or None
"""
with self.__lock:
try:
data = self.__accesses.pop(access_id)
except KeyError:
# Unknown access
return None
else:
# Notify the directory
self.__callback("peer_access_unset", access_id, data)
return data
# ------------------------------------------------------------------------------
class Target(object):
"""
The description of a target, used in exceptions
"""
def __init__(self, uid=None, group=None, uids=None, peer=None):
"""
Sets the target definition. Only one argument should be set at once.
:param uid: The UID of the targeted peer
:param group: The targeted group
:param uids: The UIDs of the targeted peers (for groups only)
:param peer: A Peer bean
"""
if peer is not None:
self.__uid = peer.uid
else:
self.__uid = uid
self.__group = group
self.__uids = uids or []
@property
def uid(self):
"""
The UID of the targeted peer
"""
return self.__uid
@property
def group(self):
"""
The targeted group
"""
return self.__group
@property
def uids(self):
"""
The UIDs of the targeted peers (for groups only)
"""
return self.__uids
# ------------------------------------------------------------------------------
class RawAccess(object):
"""
A peer access stored while no transport directory can load it
"""
def __init__(self, access_id, raw_data):
"""
Sets up the bean
:param access_id: Access ID associated to the data
:param raw_data: Raw data to store
"""
self.__access_id = access_id
self.__raw_data = raw_data
@property
def access_id(self):
"""
The access ID associated to the data
"""
return self.__access_id
@property
def data(self):
"""
The stored data
"""
return self.__raw_data
def dump(self):
"""
The dump method returns the raw data as-is
"""
return self.__raw_data
# ------------------------------------------------------------------------------
class DelayedNotification(object):
"""
Bean to use for delayed notification of peer registration
"""
def __init__(self, peer, notification_method):
"""
Sets up the bean
:param peer: The peer being registered
:param notification_method: The method to call to notify listeners
(can be None to ignore notification)
"""
self.__peer = peer
self.__method = notification_method
@property
def peer(self):
"""
The peer being registered
"""
return self.__peer
def notify(self):
"""
Calls the notification method
:return: True if the notification method has been called
"""
if self.__method is not None:
self.__method(self.__peer)
return True
return False
# ------------------------------------------------------------------------------
class Message(object):
"""
Represents a message to be sent
"""
def __init__(self, subject, content=None):
"""
Sets up members
:param subject: Subject of the message
:param content: Content of the message (optional)
"""
self._subject = subject
self._content = content
self._headers = {}
self._headers[herald.MESSAGE_HERALD_VERSION] = herald.HERALD_SPECIFICATION_VERSION
self._headers[herald.MESSAGE_HEADER_TIMESTAMP] = int(time.time() * 1000)
self._headers[herald.MESSAGE_HEADER_UID] = str(uuid.uuid4()).replace('-', '').upper()
self._metadata = {}
def __str__(self):
"""
String representation
"""
return "{0} ({1})".format(self._subject, self.uid)
@property
def subject(self):
"""
The subject of the message
"""
return self._subject
@property
def content(self):
"""
The content of the message
"""
return self._content
@property
def timestamp(self):
"""
Time stamp of the message
"""
return self._headers[herald.MESSAGE_HEADER_TIMESTAMP]
@property
def uid(self):
"""
Message UID
"""
return self._headers[herald.MESSAGE_HEADER_UID]
@property
def headers(self):
"""
Message headers
"""
return self._headers
@property
def metadata(self):
"""
Message metadata
"""
return self._metadata
def add_header(self, key, value):
"""
Adds a header
"""
self._headers[key] = value
def get_header(self, key):
"""
Gets a header value
"""
if key in self._headers:
return self._headers[key]
return None
def remove_header(self, key):
"""
Removes a header from the headers list
"""
if key in self._headers:
del self._headers[key]
def set_content(self, content):
"""
Set content
"""
self._content = content
def add_metadata(self, key, value):
"""
Adds a metadata
"""
self._metadata[key] = value
def get_metadata(self, key):
"""
Gets a metadata
"""
if key in self._metadata:
return self._metadata[key]
return None
def remove_metadata(self, key):
"""
Removes a metadata
"""
if key in self._metadata:
del self._metadata[key]
class MessageReceived(Message):
"""
Represents a message received by a transport
"""
def __init__(self, uid, subject, content, sender_uid, reply_to, access,
timestamp=None, extra=None):
"""
Sets up the bean
:param uid: Message UID
:param subject: Subject of the message
:param content: Content of the message
:param sender_uid: UID of the sending peer
:param reply_to: UID of the message this one replies to
:param access: Access ID of the transport which received this message
:param timestamp: Message sending time stamp
:param extra: Extra configuration for the transport in case of reply
"""
Message.__init__(self, subject, content)
self._headers[herald.MESSAGE_HEADER_UID] = uid
self._headers[herald.MESSAGE_HEADER_SENDER_UID] = sender_uid
self._headers[herald.MESSAGE_HEADER_REPLIES_TO] = reply_to
self._access = access
self._extra = extra
self._headers[herald.MESSAGE_HEADER_TIMESTAMP] = timestamp
def __str__(self):
"""
String representation
"""
return "{0} ({1}) from {2}".format(self._subject, self.uid,
self.sender)
@property
def access(self):
"""
Returns the access ID of the transport which received this message
"""
return self._access
@property
def reply_to(self):
"""
UID of the message this one replies to
"""
return self._headers[herald.MESSAGE_HEADER_REPLIES_TO]
@property
def sender(self):
"""
UID of the peer that sent this message
"""
return self._headers[herald.MESSAGE_HEADER_SENDER_UID]
@property
def extra(self):
"""
Extra information set by the transport that received this message
"""
return self._extra
def set_access(self, access):
"""
Sets the access
"""
self._access = access
def set_extra(self, extra):
"""
Sets the extra
"""
self._extra = extra | {
"content_hash": "edd2f7920cd0cc086986e4728b70c5f7",
"timestamp": "",
"source": "github",
"line_count": 591,
"max_line_length": 93,
"avg_line_length": 26.008460236886634,
"alnum_prop": 0.5244291197709974,
"repo_name": "ahmadshahwan/cohorte-herald",
"id": "9915185e15f64047c68f0b27670da43749742754",
"size": "15421",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "python/herald/beans.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "354906"
},
{
"name": "Python",
"bytes": "369670"
},
{
"name": "Shell",
"bytes": "1801"
}
],
"symlink_target": ""
} |
import abc
import signal
import sys
import six
from oslo_log import log as logging
@six.add_metaclass(abc.ABCMeta)
class StressAction(object):
def __init__(self, manager, max_runs=None, stop_on_error=False):
full_cname = self.__module__ + "." + self.__class__.__name__
self.logger = logging.getLogger(full_cname)
self.manager = manager
self.max_runs = max_runs
self.stop_on_error = stop_on_error
def _shutdown_handler(self, signal, frame):
try:
self.tearDown()
except Exception:
self.logger.exception("Error while tearDown")
sys.exit(0)
@property
def action(self):
"""This methods returns the action.
Overload this if you create a stress test wrapper.
"""
return self.__class__.__name__
def setUp(self, **kwargs):
"""Initialize test structures/resources
This method is called before "run" method to help the test
initialize any structures. kwargs contains arguments passed
in from the configuration json file.
setUp doesn't count against the time duration.
"""
self.logger.debug("setUp")
def tearDown(self):
"""Cleanup test structures/resources
This method is called to do any cleanup after the test is complete.
"""
self.logger.debug("tearDown")
def execute(self, shared_statistic):
"""This is the main execution entry point called by the driver.
We register a signal handler to allow us to tearDown gracefully,
and then exit. We also keep track of how many runs we do.
"""
signal.signal(signal.SIGHUP, self._shutdown_handler)
signal.signal(signal.SIGTERM, self._shutdown_handler)
while self.max_runs is None or (shared_statistic['runs'] <
self.max_runs):
self.logger.debug("Trigger new run (run %d)" %
shared_statistic['runs'])
try:
self.run()
except Exception:
shared_statistic['fails'] += 1
self.logger.exception("Failure in run")
finally:
shared_statistic['runs'] += 1
if self.stop_on_error and (shared_statistic['fails'] > 1):
self.logger.warning("Stop process due to"
"\"stop-on-error\" argument")
self.tearDown()
sys.exit(1)
@abc.abstractmethod
def run(self):
"""This method is where the stress test code runs."""
return
| {
"content_hash": "447fb4c5ae2897c34029301060f653e1",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 75,
"avg_line_length": 32.4390243902439,
"alnum_prop": 0.5710526315789474,
"repo_name": "zsoltdudas/lis-tempest",
"id": "cf0a08a463e4afd70e068b8cd56eca7ca74c8547",
"size": "3298",
"binary": false,
"copies": "6",
"ref": "refs/heads/LIS",
"path": "tempest/stress/stressaction.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "3681961"
},
{
"name": "Shell",
"bytes": "106383"
}
],
"symlink_target": ""
} |
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('studygroups', '0021_auto_20150506_0036'),
]
operations = [
migrations.AlterField(
model_name='application',
name='contact_method',
field=models.CharField(max_length=128, choices=[(b'Email', b'Email'), (b'Text', b'Text')]),
),
]
| {
"content_hash": "6dcaa0872667e7834ca14abbd3e1ab31",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 103,
"avg_line_length": 25.4375,
"alnum_prop": 0.5847665847665847,
"repo_name": "p2pu/learning-circles",
"id": "34ab5b339568b02c82533b11e5e725efa230a39e",
"size": "433",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "studygroups/migrations/0022_remove_contact_options.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6537"
},
{
"name": "Dockerfile",
"bytes": "2110"
},
{
"name": "HTML",
"bytes": "222765"
},
{
"name": "JavaScript",
"bytes": "202138"
},
{
"name": "Python",
"bytes": "859945"
},
{
"name": "SCSS",
"bytes": "122949"
},
{
"name": "Shell",
"bytes": "808"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kolibriauth', '0002_auto_20170208_0110'),
]
operations = [
migrations.AlterField(
model_name='collection',
name='kind',
field=models.CharField(choices=[(b'facility', 'Facility'), (b'classroom', 'Classroom'), (b'learnergroup', 'Learner group')], max_length=20),
),
migrations.AlterField(
model_name='deviceowner',
name='username',
field=models.CharField(help_text='Required. 30 characters or fewer. Letters and digits only', max_length=30, validators=[django.core.validators.RegexValidator('^\\w+$', 'Enter a valid username. This value may contain only letters and numbers.')], verbose_name='username'),
),
migrations.AlterField(
model_name='facilityuser',
name='username',
field=models.CharField(help_text='Required. 30 characters or fewer. Letters and digits only', max_length=30, validators=[django.core.validators.RegexValidator('^\\w+$', 'Enter a valid username. This value may contain only letters and numbers.')], verbose_name='username'),
),
]
| {
"content_hash": "050ece86598c9efa42f07f316c8e1495",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 284,
"avg_line_length": 45,
"alnum_prop": 0.6482758620689655,
"repo_name": "aronasorman/kolibri",
"id": "46a42aeffe7d49a416990aeab9a01e581138684a",
"size": "1377",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kolibri/auth/migrations/0003_auto_20170309_1853.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "26247"
},
{
"name": "HTML",
"bytes": "4007"
},
{
"name": "JavaScript",
"bytes": "330241"
},
{
"name": "Makefile",
"bytes": "3887"
},
{
"name": "Python",
"bytes": "569360"
},
{
"name": "Shell",
"bytes": "7127"
},
{
"name": "Vue",
"bytes": "222681"
}
],
"symlink_target": ""
} |
"""
WSGI config for nspaces project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings")
application = get_wsgi_application()
| {
"content_hash": "c35dc2ebc9aef4610cbdfd5e837af18b",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 78,
"avg_line_length": 24.3125,
"alnum_prop": 0.7686375321336761,
"repo_name": "jstoledano/nspaces",
"id": "05300a07f3c8778bf38e95545f72b424c5ca2030",
"size": "389",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/core/wsgi.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "33602"
},
{
"name": "HTML",
"bytes": "192913"
},
{
"name": "JavaScript",
"bytes": "17838"
},
{
"name": "Python",
"bytes": "45721"
}
],
"symlink_target": ""
} |
from enum import Enum
class EventType(Enum):
"""Enum containing the various types of events that can occur."""
CLIENT_READY = "CLIENT_READY"
CLIENT_RESUMED = "CLIENT_RESUMED"
MESSAGE_RECEIVED = "MESSAGE_RECEIVED"
SERVER_MESSAGE_RECEIVED = "SERVER_MESSAGE_RECEIVED"
PRIVATE_MESSAGE_RECEIVED = "PRIVATE_MESSAGE_RECEIVED"
COMMAND_RECEIVED = "COMMAND_RECEIVED"
MESSAGE_DELETED = "MESSAGE_DELETED"
MESSAGE_EDITED = "MESSAGE_EDITED"
CHANNEL_DELETED = "CHANNEL_DELETED"
CHANNEL_CREATED = "CHANNEL_CREATED"
CHANNEL_UPDATED = "CHANNEL_UPDATED"
MEMBER_JOINED = "MEMBER_JOINED"
MEMBER_REMOVED = "MEMBER_REMOVED"
MEMBER_UPDATED = "MEMBER_UPDATED"
MEMBER_BANNED = "MEMBER_BANNED"
MEMBER_UNBANNED = "MEMBER_UNBANNED"
MEMBER_TYPING = "MEMBER_TYPING"
SERVER_JOINED = "SERVER_JOINED"
SERVER_REMOVED = "SERVER_REMOVED"
SERVER_UPDATED = "SERVER_UPDATED"
ROLE_CREATED = "ROLE_CREATED"
ROLE_DELETED = "ROLE_DELETED"
ROLE_UPDATED = "ROLE_UPDATED"
SERVER_AVAILABLE = "SERVER_AVAILABLE"
SERVER_UNAVAILABLE = "SERVER_UNAVAILABLE"
VOICE_STATE_UPDATED = "VOICE_STATE_UPDATED"
REACTION_ADDED = "REACTION_ADDED"
REACTION_REMOVED = "REACTION_REMOVED"
REACTIONS_CLEARED = "REACTIONS_CLEARED"
MEMBER_JOINED_GROUP = "MEMBER_JOINED_GROUP"
MEMBER_REMOVED_FROM_GROUP = "MEMBER_REMOVED_FROM_GROUP"
SERVER_EMOJIS_UPDATED = "SERVER_EMOJIS_UPDATED"
class RedisStorageScope(Enum):
"""Enum containing the possible Redis storage scopes."""
GLOBAL = "GLOBAL"
PLUGIN = "PLUGIN"
SERVER = "SERVER"
CHANNEL = "CHANNEL"
USER = "USER"
| {
"content_hash": "1e58935a09a4eb775e01a3c4fe36cd8c",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 69,
"avg_line_length": 29.05263157894737,
"alnum_prop": 0.6884057971014492,
"repo_name": "nint8835/NintbotForDiscordV2",
"id": "60336ec8abc6b32d869ad96e29ffb9eebe0a5c03",
"size": "1656",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "NintbotForDiscord/Enums.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "64788"
}
],
"symlink_target": ""
} |
import datetime
from functools import reduce
import logging
from typing import Any, Type
from flask_babel import lazy_gettext
from .filters import BaseFilterConverter, Filters
try:
import enum
_has_enum = True
except ImportError:
_has_enum = False
log = logging.getLogger(__name__)
class BaseInterface:
"""
Base class for all data model interfaces.
Sub class it to implement your own interface for some data engine.
"""
filter_converter_class = Type[BaseFilterConverter]
""" when sub classing override with your own custom filter converter """
""" Messages to display on CRUD Events """
add_row_message = lazy_gettext("Added Row")
edit_row_message = lazy_gettext("Changed Row")
delete_row_message = lazy_gettext("Deleted Row")
delete_integrity_error_message = lazy_gettext(
"Associated data exists, please delete them first"
)
add_integrity_error_message = lazy_gettext(
"Integrity error, probably unique constraint"
)
edit_integrity_error_message = lazy_gettext(
"Integrity error, probably unique constraint"
)
general_error_message = lazy_gettext("General Error")
""" Tuple with message and text with severity type ex: ("Added Row", "info") """
message = ()
def __init__(self, obj: Type[Any]):
self.obj = obj
def __getattr__(self, name: str) -> Any:
"""
Make mypy happy about the injected filters like self.datamodel.FilterEqual
https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html#when-you-re-puzzled-or-when-things-are-complicated
"""
return super().__getattr__(name)
def _get_attr(self, col_name):
if not hasattr(self.obj, col_name):
# it's an inner obj attr
try:
_obj = self.obj
for i in col_name.split("."):
try:
_obj = self.get_related_model(i)
except Exception:
_obj = getattr(_obj, i)
return _obj
except Exception:
return None
return getattr(self.obj, col_name)
@staticmethod
def _get_attr_value(item, col):
if not hasattr(item, col):
# it's an inner obj attr
try:
return reduce(getattr, col.split("."), item)
except Exception:
return ""
if hasattr(getattr(item, col), "__call__"):
# its a function
return getattr(item, col)()
else:
# its an attribute
value = getattr(item, col)
# if value is an Enum instance than list and show widgets should display
# its .value rather than its .name:
if _has_enum and isinstance(value, enum.Enum):
return value.value
return value
def get_filters(self, search_columns=None, search_filters=None):
search_columns = search_columns or []
return Filters(
self.filter_converter_class,
self,
search_columns=search_columns,
search_filters=search_filters,
)
def get_values_item(self, item, show_columns):
return [self._get_attr_value(item, col) for col in show_columns]
def _get_values(self, lst, list_columns):
"""
Get Values: formats values for list template.
returns [{'col_name':'col_value',....},{'col_name':'col_value',....}]
:param lst:
The list of item objects from query
:param list_columns:
The list of columns to include
"""
retlst = []
for item in lst:
retdict = {}
for col in list_columns:
retdict[col] = self._get_attr_value(item, col)
retlst.append(retdict)
return retlst
def get_values(self, lst, list_columns):
"""
Get Values: formats values for list template.
returns [{'col_name':'col_value',....},{'col_name':'col_value',....}]
:param lst:
The list of item objects from query
:param list_columns:
The list of columns to include
"""
for item in lst:
retdict = {}
for col in list_columns:
retdict[col] = self._get_attr_value(item, col)
yield retdict
def get_values_json(self, lst, list_columns):
"""
Converts list of objects from query to JSON
"""
result = []
for item in self.get_values(lst, list_columns):
for key, value in list(item.items()):
if isinstance(value, datetime.datetime) or isinstance(
value, datetime.date
):
value = value.isoformat()
item[key] = value
if isinstance(value, list):
item[key] = [str(v) for v in value]
result.append(item)
return result
"""
Returns the models class name
useful for auto title on views
"""
@property
def model_name(self):
return self.obj.__class__.__name__
"""
Next methods must be overridden
"""
def query(
self,
filters=None,
order_column="",
order_direction="",
page=None,
page_size=None,
):
pass
def is_image(self, col_name):
return False
def is_file(self, col_name):
return False
def is_gridfs_file(self, col_name):
return False
def is_gridfs_image(self, col_name):
return False
def is_string(self, col_name):
return False
def is_text(self, col_name):
return False
def is_binary(self, col_name):
return False
def is_integer(self, col_name):
return False
def is_numeric(self, col_name):
return False
def is_float(self, col_name):
return False
def is_boolean(self, col_name):
return False
def is_date(self, col_name):
return False
def is_datetime(self, col_name):
return False
def is_enum(self, col_name):
return False
def is_relation(self, prop):
return False
def is_relation_col(self, col):
return False
def is_relation_many_to_one(self, prop):
return False
def is_relation_many_to_many(self, prop):
return False
def is_relation_one_to_one(self, prop):
return False
def is_relation_one_to_many(self, prop):
return False
def is_nullable(self, col_name):
return True
def is_unique(self, col_name):
return False
def is_pk(self, col_name):
return False
def is_pk_composite(self):
raise False
def is_fk(self, col_name):
return False
def get_max_length(self, col_name):
return -1
def get_min_length(self, col_name):
return -1
"""
-----------------------------------------
FUNCTIONS FOR CRUD OPERATIONS
-----------------------------------------
"""
def add(self, item):
"""
Adds object
"""
raise NotImplementedError
def edit(self, item):
"""
Edit (change) object
"""
raise NotImplementedError
def delete(self, item):
"""
Deletes object
"""
raise NotImplementedError
def get_col_default(self, col_name):
pass
def get_keys(self, lst):
"""
return a list of pk values from object list
"""
pk_name = self.get_pk_name()
if self.is_pk_composite():
return [[getattr(item, pk) for pk in pk_name] for item in lst]
else:
return [getattr(item, pk_name) for item in lst]
def get_pk_name(self):
"""
Returns the primary key name
"""
raise NotImplementedError
def get_pk_value(self, item):
pk_name = self.get_pk_name()
if self.is_pk_composite():
return [getattr(item, pk) for pk in pk_name]
else:
return getattr(item, pk_name)
def get(self, pk, filter=None):
"""
return the record from key, you can optionally pass filters
if pk exits on the db but filters exclude it it will return none.
"""
pass
def get_related_model(self, prop):
raise NotImplementedError
def get_related_interface(self, col_name):
"""
Returns a BaseInterface for the related model
of column name.
:param col_name: Column name with relation
:return: BaseInterface
"""
raise NotImplementedError
def get_related_obj(self, col_name, value):
raise NotImplementedError
def get_related_fk(self, model):
raise NotImplementedError
def get_columns_list(self):
"""
Returns a list of all the columns names
"""
return []
def get_user_columns_list(self):
"""
Returns a list of user viewable columns names
"""
return self.get_columns_list()
def get_search_columns_list(self):
"""
Returns a list of searchable columns names
"""
return []
def get_order_columns_list(self, list_columns=None):
"""
Returns a list of order columns names
"""
return []
def get_relation_fk(self, prop):
pass
| {
"content_hash": "effe1dd395b536c80db38f862d1dfeca",
"timestamp": "",
"source": "github",
"line_count": 360,
"max_line_length": 117,
"avg_line_length": 26.752777777777776,
"alnum_prop": 0.5453223964282006,
"repo_name": "dpgaspar/Flask-AppBuilder",
"id": "6a1529e6e146bfd9c96a2a263e35dbd5a9e400bf",
"size": "9631",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "flask_appbuilder/models/base.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "10821"
},
{
"name": "HTML",
"bytes": "88195"
},
{
"name": "JavaScript",
"bytes": "13746"
},
{
"name": "Python",
"bytes": "1041543"
},
{
"name": "Shell",
"bytes": "1343"
}
],
"symlink_target": ""
} |
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'chart_data_labels05.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.got_filename = test_dir + '_test_' + filename
self.exp_filename = test_dir + 'xlsx_files/' + filename
self.ignore_files = []
self.ignore_elements = {}
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'line'})
chart.axis_ids = [45678592, 45680128]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column('A1', data[0])
worksheet.write_column('B1', data[1])
worksheet.write_column('C1', data[2])
chart.add_series({
'values': '=Sheet1!$A$1:$A$5',
'data_labels': {'value': 1, 'position': 'right'},
})
chart.add_series({
'values': '=Sheet1!$B$1:$B$5',
'data_labels': {'value': 1, 'position': 'top'},
})
chart.add_series({
'values': '=Sheet1!$C$1:$C$5',
'data_labels': {'value': 1, 'position': 'bottom'},
})
worksheet.insert_chart('E9', chart)
workbook.close()
self.assertExcelEqual()
| {
"content_hash": "ecf9e790f3bfb61c258024d55c9ebb9e",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 68,
"avg_line_length": 26.07936507936508,
"alnum_prop": 0.5349969567863664,
"repo_name": "jkyeung/XlsxWriter",
"id": "fa1f0b11c8e03238b5e0441eefe33dde8ff73cf3",
"size": "1816",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xlsxwriter/test/comparison/test_chart_data_labels05.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "5113"
},
{
"name": "CSS",
"bytes": "16544"
},
{
"name": "HTML",
"bytes": "13100"
},
{
"name": "Makefile",
"bytes": "7819"
},
{
"name": "Perl",
"bytes": "3504"
},
{
"name": "Python",
"bytes": "2430294"
},
{
"name": "Shell",
"bytes": "6064"
}
],
"symlink_target": ""
} |
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
import random
class Population(object):
"""
Genotypes are biallelic in the form of (0, 1) where 0 is a recessive allele
and 1 is a dominant allele. Each genotype is associated with a character of
the organism (e.g., seed color) and recessive and dominant phenotypes (e.g.,
"green" and "yellow").
"""
@classmethod
def create_parental(cls, n, allele):
"""
Create a pure-breeding parental population of the given size, n, consisting
entirely of the given allele.
"""
return cls(np.array([allele] * 2*n).reshape(n, 2))
def __init__(self, population):
"""
Instantiate a population with an array of alleles.
"""
self.population = population
def __repr__(self):
"""
Return representation of the array underlying this population.
"""
return repr(self.population)
def get_alleles(self):
"""
Return a random array of alleles from the given population.
"""
return np.apply_along_axis(np.random.choice, 1, self.population)
def cross(self, other_population):
"""
Create a new population from alleles sampled from this and the given
population.
"""
return self.__class__(np.array([self.get_alleles(), other_population.get_alleles()]).T)
def get_allele_frequencies(self):
"""
Return the frequency of each allele in this population.
"""
unique, inverse = np.unique(self.population, return_inverse=True)
count = np.zeros(len(unique), np.int)
np.add.at(count, inverse, 1)
return count / np.float(count.sum())
def get_expected_genotype_frequencies(self):
"""
Return an array of genotype frequencies expected for this population
based on Hardy-Weinberg equilibrium.
"""
allele_frequencies = self.get_allele_frequencies()
return np.array([
allele_frequencies[0] ** 2,
2 * np.product(allele_frequencies),
allele_frequencies[1] ** 2
])
def get_observed_genotype_frequencies(self):
"""
Return the observed genotype frequencies of this population.
"""
genotypes = np.apply_along_axis(sum, 1, self.population)
return np.bincount(genotypes) / np.sum(genotypes, dtype=np.float64)
| {
"content_hash": "3c0fd090ac8e10d0a5aef179afe7b88f",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 95,
"avg_line_length": 33.270270270270274,
"alnum_prop": 0.6169780666125102,
"repo_name": "huddlej/populations",
"id": "4be224b42b8b240f798aab4a550cbd08334c9d9f",
"size": "2462",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "populations.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "147834"
},
{
"name": "Python",
"bytes": "4201"
}
],
"symlink_target": ""
} |
from hazelcast.serialization.bits import *
from hazelcast.protocol.client_message import ClientMessage
from hazelcast.protocol.custom_codec import *
from hazelcast.util import ImmutableLazyDataList
from hazelcast.protocol.codec.replicated_map_message_type import *
REQUEST_TYPE = REPLICATEDMAP_PUT
RESPONSE_TYPE = 105
RETRYABLE = False
def calculate_size(name, key, value, ttl):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += calculate_size_data(key)
data_size += calculate_size_data(value)
data_size += LONG_SIZE_IN_BYTES
return data_size
def encode_request(name, key, value, ttl):
""" Encode request into client_message"""
client_message = ClientMessage(payload_size=calculate_size(name, key, value, ttl))
client_message.set_message_type(REQUEST_TYPE)
client_message.set_retryable(RETRYABLE)
client_message.append_str(name)
client_message.append_data(key)
client_message.append_data(value)
client_message.append_long(ttl)
client_message.update_frame_length()
return client_message
def decode_response(client_message, to_object=None):
""" Decode response from client message"""
parameters = dict(response=None)
response=None
if not client_message.read_bool():
parameters['response'] = to_object(client_message.read_data())
return parameters
| {
"content_hash": "c48f1dba78c8e2ded1f0555112a06b73",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 86,
"avg_line_length": 32.02272727272727,
"alnum_prop": 0.7310149041873669,
"repo_name": "cangencer/hazelcast-python-client",
"id": "e64dfe4c78f42bff69e665e0211cd45ce5022ded",
"size": "1409",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "hazelcast/protocol/codec/replicated_map_put_codec.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "768768"
}
],
"symlink_target": ""
} |
#!/usr/bin/env python
"""
runtests.py [OPTIONS] [-- ARGS]
Run tests, building the project first.
Examples::
$ python runtests.py
$ python runtests.py -s {SAMPLE_SUBMODULE}
$ python runtests.py -t {SAMPLE_TEST}
$ python runtests.py --ipython
$ python runtests.py --python somescript.py
$ python runtests.py --bench
Run a debugger:
$ gdb --args python runtests.py [...other args...]
Generate C code coverage listing under build/lcov/:
(requires http://ltp.sourceforge.net/coverage/lcov.php)
$ python runtests.py --gcov [...other args...]
$ python runtests.py --lcov-html
"""
#
# This is a generic test runner script for projects using Numpy's test
# framework. Change the following values to adapt to your project:
#
PROJECT_MODULE = "scipy"
PROJECT_ROOT_FILES = ['scipy', 'LICENSE.txt', 'setup.py']
SAMPLE_TEST = "scipy/special/tests/test_basic.py:test_xlogy"
SAMPLE_SUBMODULE = "optimize"
EXTRA_PATH = ['/usr/lib/ccache', '/usr/lib/f90cache',
'/usr/local/lib/ccache', '/usr/local/lib/f90cache']
# ---------------------------------------------------------------------
if __doc__ is None:
__doc__ = "Run without -OO if you want usage info"
else:
__doc__ = __doc__.format(**globals())
import sys
import os
# In case we are run from the source directory, we don't want to import the
# project from there:
sys.path.pop(0)
import shutil
import subprocess
import time
import imp
from argparse import ArgumentParser, REMAINDER
ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__)))
def main(argv):
parser = ArgumentParser(usage=__doc__.lstrip())
parser.add_argument("--verbose", "-v", action="count", default=1,
help="more verbosity")
parser.add_argument("--no-build", "-n", action="store_true", default=False,
help="do not build the project (use system installed version)")
parser.add_argument("--build-only", "-b", action="store_true", default=False,
help="just build, do not run any tests")
parser.add_argument("--doctests", action="store_true", default=False,
help="Run doctests in module")
parser.add_argument("--refguide-check", action="store_true", default=False,
help="Run refguide check (do not run regular tests.)")
parser.add_argument("--coverage", action="store_true", default=False,
help=("report coverage of project code. HTML output goes "
"under build/coverage"))
parser.add_argument("--gcov", action="store_true", default=False,
help=("enable C code coverage via gcov (requires GCC). "
"gcov output goes to build/**/*.gc*"))
parser.add_argument("--lcov-html", action="store_true", default=False,
help=("produce HTML for C code coverage information "
"from a previous run with --gcov. "
"HTML output goes to build/lcov/"))
parser.add_argument("--mode", "-m", default="fast",
help="'fast', 'full', or something that could be "
"passed to nosetests -A [default: fast]")
parser.add_argument("--submodule", "-s", default=None,
help="Submodule whose tests to run (cluster, constants, ...)")
parser.add_argument("--pythonpath", "-p", default=None,
help="Paths to prepend to PYTHONPATH")
parser.add_argument("--tests", "-t", action='append',
help="Specify tests to run")
parser.add_argument("--python", action="store_true",
help="Start a Python shell with PYTHONPATH set")
parser.add_argument("--ipython", "-i", action="store_true",
help="Start IPython shell with PYTHONPATH set")
parser.add_argument("--shell", action="store_true",
help="Start Unix shell with PYTHONPATH set")
parser.add_argument("--debug", "-g", action="store_true",
help="Debug build")
parser.add_argument("--parallel", "-j", type=int, default=1,
help="Number of parallel jobs during build (requires "
"Numpy 1.10 or greater).")
parser.add_argument("--show-build-log", action="store_true",
help="Show build output rather than using a log file")
parser.add_argument("--bench", action="store_true",
help="Run benchmark suite instead of test suite")
parser.add_argument("--bench-compare", action="append", metavar="BEFORE",
help=("Compare benchmark results of current HEAD to BEFORE. "
"Use an additional --bench-compare=COMMIT to override HEAD with COMMIT. "
"Note that you need to commit your changes first!"
))
parser.add_argument("args", metavar="ARGS", default=[], nargs=REMAINDER,
help="Arguments to pass to Nose, Python or shell")
args = parser.parse_args(argv)
if args.bench_compare:
args.bench = True
args.no_build = True # ASV does the building
if args.lcov_html:
# generate C code coverage output
lcov_generate()
sys.exit(0)
if args.pythonpath:
for p in reversed(args.pythonpath.split(os.pathsep)):
sys.path.insert(0, p)
if args.gcov:
gcov_reset_counters()
if args.debug and args.bench:
print("*** Benchmarks should not be run against debug version; remove -g flag ***")
if not args.no_build:
site_dir = build_project(args)
sys.path.insert(0, site_dir)
os.environ['PYTHONPATH'] = site_dir
extra_argv = args.args[:]
if extra_argv and extra_argv[0] == '--':
extra_argv = extra_argv[1:]
if args.python:
if extra_argv:
# Don't use subprocess, since we don't want to include the
# current path in PYTHONPATH.
sys.argv = extra_argv
with open(extra_argv[0], 'r') as f:
script = f.read()
sys.modules['__main__'] = imp.new_module('__main__')
ns = dict(__name__='__main__',
__file__=extra_argv[0])
exec_(script, ns)
sys.exit(0)
else:
import code
code.interact()
sys.exit(0)
if args.ipython:
import IPython
IPython.embed(user_ns={})
sys.exit(0)
if args.shell:
shell = os.environ.get('SHELL', 'sh')
print("Spawning a Unix shell...")
os.execv(shell, [shell] + extra_argv)
sys.exit(1)
if args.coverage:
dst_dir = os.path.join(ROOT_DIR, 'build', 'coverage')
fn = os.path.join(dst_dir, 'coverage_html.js')
if os.path.isdir(dst_dir) and os.path.isfile(fn):
shutil.rmtree(dst_dir)
extra_argv += ['--cover-html',
'--cover-html-dir='+dst_dir]
if args.refguide_check:
cmd = [os.path.join(ROOT_DIR, 'tools', 'refguide_check.py'),
'--doctests']
if args.submodule:
cmd += [args.submodule]
os.execv(sys.executable, [sys.executable] + cmd)
sys.exit(0)
if args.bench:
# Run ASV
items = extra_argv
if args.tests:
items += args.tests
if args.submodule:
items += [args.submodule]
bench_args = []
for a in items:
bench_args.extend(['--bench', a])
if not args.bench_compare:
cmd = [os.path.join(ROOT_DIR, 'benchmarks', 'run.py'),
'run', '-n', '-e', '--python=same'] + bench_args
os.execv(sys.executable, [sys.executable] + cmd)
sys.exit(1)
else:
if len(args.bench_compare) == 1:
commit_a = args.bench_compare[0]
commit_b = 'HEAD'
elif len(args.bench_compare) == 2:
commit_a, commit_b = args.bench_compare
else:
p.error("Too many commits to compare benchmarks for")
# Check for uncommitted files
if commit_b == 'HEAD':
r1 = subprocess.call(['git', 'diff-index', '--quiet', '--cached', 'HEAD'])
r2 = subprocess.call(['git', 'diff-files', '--quiet'])
if r1 != 0 or r2 != 0:
print("*"*80)
print("WARNING: you have uncommitted changes --- these will NOT be benchmarked!")
print("*"*80)
# Fix commit ids (HEAD is local to current repo)
p = subprocess.Popen(['git', 'rev-parse', commit_b], stdout=subprocess.PIPE)
out, err = p.communicate()
commit_b = out.strip()
p = subprocess.Popen(['git', 'rev-parse', commit_a], stdout=subprocess.PIPE)
out, err = p.communicate()
commit_a = out.strip()
cmd = [os.path.join(ROOT_DIR, 'benchmarks', 'run.py'),
'--current-repo', 'continuous', '-e', '-f', '1.05',
commit_a, commit_b] + bench_args
os.execv(sys.executable, [sys.executable] + cmd)
sys.exit(1)
test_dir = os.path.join(ROOT_DIR, 'build', 'test')
if args.build_only:
sys.exit(0)
elif args.submodule:
modname = PROJECT_MODULE + '.' + args.submodule
try:
__import__(modname)
test = sys.modules[modname].test
except (ImportError, KeyError, AttributeError) as e:
print("Cannot run tests for %s (%s)" % (modname, e))
sys.exit(2)
elif args.tests:
def fix_test_path(x):
# fix up test path
p = x.split(':')
p[0] = os.path.relpath(os.path.abspath(p[0]),
test_dir)
return ':'.join(p)
tests = [fix_test_path(x) for x in args.tests]
def test(*a, **kw):
extra_argv = kw.pop('extra_argv', ())
extra_argv = extra_argv + tests[1:]
kw['extra_argv'] = extra_argv
from numpy.testing import Tester
return Tester(tests[0]).test(*a, **kw)
else:
__import__(PROJECT_MODULE)
test = sys.modules[PROJECT_MODULE].test
# Run the tests under build/test
try:
shutil.rmtree(test_dir)
except OSError:
pass
try:
os.makedirs(test_dir)
except OSError:
pass
shutil.copyfile(os.path.join(ROOT_DIR, '.coveragerc'),
os.path.join(test_dir, '.coveragerc'))
cwd = os.getcwd()
try:
os.chdir(test_dir)
result = test(args.mode,
verbose=args.verbose,
extra_argv=extra_argv,
doctests=args.doctests,
coverage=args.coverage)
finally:
os.chdir(cwd)
if isinstance(result, bool):
sys.exit(0 if result else 1)
elif result.wasSuccessful():
sys.exit(0)
else:
sys.exit(1)
def build_project(args):
"""
Build a dev version of the project.
Returns
-------
site_dir
site-packages directory where it was installed
"""
root_ok = [os.path.exists(os.path.join(ROOT_DIR, fn))
for fn in PROJECT_ROOT_FILES]
if not all(root_ok):
print("To build the project, run runtests.py in "
"git checkout or unpacked source")
sys.exit(1)
dst_dir = os.path.join(ROOT_DIR, 'build', 'testenv')
env = dict(os.environ)
cmd = [sys.executable, 'setup.py']
# Always use ccache, if installed
env['PATH'] = os.pathsep.join(EXTRA_PATH + env.get('PATH', '').split(os.pathsep))
if args.debug or args.gcov:
# assume everyone uses gcc/gfortran
env['OPT'] = '-O0 -ggdb'
env['FOPT'] = '-O0 -ggdb'
if args.gcov:
import distutils.sysconfig
cvars = distutils.sysconfig.get_config_vars()
env['OPT'] = '-O0 -ggdb'
env['FOPT'] = '-O0 -ggdb'
env['CC'] = cvars['CC'] + ' --coverage'
env['CXX'] = cvars['CXX'] + ' --coverage'
env['F77'] = 'gfortran --coverage '
env['F90'] = 'gfortran --coverage '
env['LDSHARED'] = cvars['LDSHARED'] + ' --coverage'
env['LDFLAGS'] = " ".join(cvars['LDSHARED'].split()[1:]) + ' --coverage'
cmd += ['build']
if args.parallel > 1:
cmd += ['-j', str(args.parallel)]
cmd += ['install', '--prefix=' + dst_dir]
log_filename = os.path.join(ROOT_DIR, 'build.log')
if args.show_build_log:
ret = subprocess.call(cmd, env=env, cwd=ROOT_DIR)
else:
log_filename = os.path.join(ROOT_DIR, 'build.log')
print("Building, see build.log...")
with open(log_filename, 'w') as log:
p = subprocess.Popen(cmd, env=env, stdout=log, stderr=log,
cwd=ROOT_DIR)
# Wait for it to finish, and print something to indicate the
# process is alive, but only if the log file has grown (to
# allow continuous integration environments kill a hanging
# process accurately if it produces no output)
last_blip = time.time()
last_log_size = os.stat(log_filename).st_size
while p.poll() is None:
time.sleep(0.5)
if time.time() - last_blip > 60:
log_size = os.stat(log_filename).st_size
if log_size > last_log_size:
print(" ... build in progress")
last_blip = time.time()
last_log_size = log_size
ret = p.wait()
if ret == 0:
print("Build OK")
else:
if not args.show_build_log:
with open(log_filename, 'r') as f:
print(f.read())
print("Build failed!")
sys.exit(1)
from distutils.sysconfig import get_python_lib
site_dir = get_python_lib(prefix=dst_dir, plat_specific=True)
return site_dir
#
# GCOV support
#
def gcov_reset_counters():
print("Removing previous GCOV .gcda files...")
build_dir = os.path.join(ROOT_DIR, 'build')
for dirpath, dirnames, filenames in os.walk(build_dir):
for fn in filenames:
if fn.endswith('.gcda') or fn.endswith('.da'):
pth = os.path.join(dirpath, fn)
os.unlink(pth)
#
# LCOV support
#
LCOV_OUTPUT_FILE = os.path.join(ROOT_DIR, 'build', 'lcov.out')
LCOV_HTML_DIR = os.path.join(ROOT_DIR, 'build', 'lcov')
def lcov_generate():
try: os.unlink(LCOV_OUTPUT_FILE)
except OSError: pass
try: shutil.rmtree(LCOV_HTML_DIR)
except OSError: pass
print("Capturing lcov info...")
subprocess.call(['lcov', '-q', '-c',
'-d', os.path.join(ROOT_DIR, 'build'),
'-b', ROOT_DIR,
'--output-file', LCOV_OUTPUT_FILE])
print("Generating lcov HTML output...")
ret = subprocess.call(['genhtml', '-q', LCOV_OUTPUT_FILE,
'--output-directory', LCOV_HTML_DIR,
'--legend', '--highlight'])
if ret != 0:
print("genhtml failed!")
else:
print("HTML output generated under build/lcov/")
#
# Python 3 support
#
if sys.version_info[0] >= 3:
import builtins
exec_ = getattr(builtins, "exec")
else:
def exec_(code, globs=None, locs=None):
"""Execute code in a namespace."""
if globs is None:
frame = sys._getframe(1)
globs = frame.f_globals
if locs is None:
locs = frame.f_locals
del frame
elif locs is None:
locs = globs
exec("""exec code in globs, locs""")
if __name__ == "__main__":
main(argv=sys.argv[1:])
| {
"content_hash": "892159d463722f1be12e628fac1b038d",
"timestamp": "",
"source": "github",
"line_count": 458,
"max_line_length": 103,
"avg_line_length": 34.98471615720524,
"alnum_prop": 0.5384759408350496,
"repo_name": "Shaswat27/scipy",
"id": "88f873c6c3734f664e13fb8734d6369f2300eec2",
"size": "16023",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "runtests.py",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "4240488"
},
{
"name": "C++",
"bytes": "3691569"
},
{
"name": "FORTRAN",
"bytes": "5661284"
},
{
"name": "HTML",
"bytes": "124328"
},
{
"name": "Makefile",
"bytes": "778"
},
{
"name": "Matlab",
"bytes": "4346"
},
{
"name": "Python",
"bytes": "9827641"
},
{
"name": "Shell",
"bytes": "2218"
},
{
"name": "TeX",
"bytes": "52106"
}
],
"symlink_target": ""
} |
from __future__ import print_function
# This is hacky code to analyze data on our support stream. The main
# reusable bits are get_recent_messages and get_words.
import zulip
import re
import collections
def get_recent_messages(client, narrow, count=100):
narrow = [word.split(':') for word in narrow.split()]
req = {
'narrow': narrow,
'num_before': count,
'num_after': 0,
'anchor': 1000000000,
'apply_markdown': False
}
old_messages = client.do_api_query(req, zulip.API_VERSTRING + 'messages', method='GET')
if 'messages' not in old_messages:
return []
return old_messages['messages']
def get_words(content):
regex = "[A-Z]{2,}(?![a-z])|[A-Z][a-z]+(?=[A-Z])|[\'\w\-]+"
words = re.findall(regex, content, re.M)
words = [w.lower() for w in words]
# words = [w.rstrip('s') for w in words]
return words
def analyze_messages(msgs, word_count, email_count):
for msg in msgs:
if False:
if ' ack' in msg['content']:
name = msg['sender_full_name'].split()[0]
print('ACK', name)
m = re.search('ticket (Z....).*email: (\S+).*~~~(.*)', msg['content'], re.M | re.S)
if m:
ticket, email, req = m.groups()
words = get_words(req)
for word in words:
word_count[word] += 1
email_count[email] += 1
if False:
print()
for k, v in msg.items():
print('%-20s: %s' % (k, v))
def generate_support_stats():
client = zulip.Client()
narrow = 'stream:support'
count = 2000
msgs = get_recent_messages(client, narrow, count)
msgs_by_topic = collections.defaultdict(list)
for msg in msgs:
topic = msg['subject']
msgs_by_topic[topic].append(msg)
word_count = collections.defaultdict(int)
email_count = collections.defaultdict(int)
if False:
for topic in msgs_by_topic:
msgs = msgs_by_topic[topic]
analyze_messages(msgs, word_count, email_count)
if True:
words = word_count.keys()
words = [w for w in words if word_count[w] >= 10]
words = [w for w in words if len(w) >= 5]
words = sorted(words, key=lambda w: word_count[w], reverse=True)
for word in words:
print(word, word_count[word])
if False:
emails = email_count.keys()
emails = sorted(emails, key=lambda w: email_count[w], reverse=True)
for email in emails:
print(email, email_count[email])
generate_support_stats()
| {
"content_hash": "5a3c24c1927a3a6d67715e6b0544e5df",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 91,
"avg_line_length": 32.4625,
"alnum_prop": 0.568348093954563,
"repo_name": "alliejones/zulip",
"id": "50959463dc1a424fad3371ebe29d23be7d995542",
"size": "2597",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "bots/summarize_stream.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "164"
},
{
"name": "CSS",
"bytes": "180848"
},
{
"name": "CoffeeScript",
"bytes": "18435"
},
{
"name": "Groovy",
"bytes": "5515"
},
{
"name": "HTML",
"bytes": "351970"
},
{
"name": "JavaScript",
"bytes": "1555365"
},
{
"name": "Nginx",
"bytes": "1228"
},
{
"name": "PHP",
"bytes": "18930"
},
{
"name": "Pascal",
"bytes": "1113"
},
{
"name": "Perl",
"bytes": "383634"
},
{
"name": "Puppet",
"bytes": "90728"
},
{
"name": "Python",
"bytes": "1809617"
},
{
"name": "Ruby",
"bytes": "255867"
},
{
"name": "Shell",
"bytes": "31428"
}
],
"symlink_target": ""
} |
"""read the idf file by just parsing the text"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import eppy.modeleditor as modeleditor
from eppy.modeleditor import IDF
def nocomment(astr, com='!'):
"""
just like the comment in python.
removes any text after the phrase 'com'
"""
alist = astr.splitlines()
for i in range(len(alist)):
element = alist[i]
pnt = element.find(com)
if pnt != -1:
alist[i] = element[:pnt]
return '\n'.join(alist)
def _tofloat(num):
"""to float"""
try:
return float(num)
except ValueError:
return num
def idf2txt(txt):
"""convert the idf text to a simple text"""
astr = nocomment(txt)
objs = astr.split(';')
objs = [obj.split(',') for obj in objs]
objs = [[line.strip() for line in obj] for obj in objs]
objs = [[_tofloat(line) for line in obj] for obj in objs]
objs = [tuple(obj) for obj in objs]
objs.sort()
lst = []
for obj in objs:
for field in obj[:-1]:
lst.append('%s,' % (field, ))
lst.append('%s;\n' % (obj[-1], ))
return '\n'.join(lst)
def idfreadtest(iddhandle, idfhandle1, idfhandle2, verbose=False, save=False):
"""compare the results of eppy reader and simple reader"""
# read using eppy:
try:
IDF.setiddname(iddhandle)
except modeleditor.IDDAlreadySetError:
# idd has already been set
pass
idf = IDF(idfhandle1)
idfstr = idf.idfstr()
idfstr = idf2txt(idfstr)
# -
# do a simple read
simpletxt = idfhandle2.read()
try:
simpletxt = simpletxt.decode('ISO-8859-2')
except AttributeError:
pass
simpletxt = idf2txt(simpletxt)
# -
if save:
open('simpleread.idf', 'w').write(idfstr)
open('eppyread.idf', 'w').write(simpletxt)
# do the compare
lines1 = idfstr.splitlines()
lines2 = simpletxt.splitlines()
for i, (line1, line2) in enumerate(zip(lines1, lines2)):
if line1 != line2:
# test if it is a mismatch in number format
try:
line1 = float(line1[:-1])
line2 = float(line2[:-1])
if line1 != line2:
if verbose:
print()
print("%s- : %s" % (i, line1))
print("%s- : %s" % (i, line2))
return False
except ValueError:
if verbose:
print()
print("%s- : %s" % (i, line1))
print("%s- : %s" % (i, line2))
return False
return True
| {
"content_hash": "4b0263066b361872055e73e00255135b",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 78,
"avg_line_length": 29.340425531914892,
"alnum_prop": 0.5402465554749819,
"repo_name": "eayoungs/eppy",
"id": "7c4f3d1c7e31807f71f6f2da8c3ed79233e8bd6f",
"size": "3064",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "eppy/simpleread.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2050328"
},
{
"name": "Jupyter Notebook",
"bytes": "133046"
},
{
"name": "Python",
"bytes": "7001722"
},
{
"name": "Shell",
"bytes": "166"
}
],
"symlink_target": ""
} |
import logging
import asyncio
from domopyc.subscribers.toolbox import AverageMemoryMessageHandler
logging.basicConfig(format='%(asctime)s [%(name)s] %(levelname)s: %(message)s')
LOGGER = logging.getLogger('domopyc')
class MysqlCurrentCostMessageHandler(AverageMemoryMessageHandler):
CREATE_TABLE_SQL = '''CREATE TABLE IF NOT EXISTS `current_cost` (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`watt` int(11) DEFAULT NULL,
`minutes` int(11) DEFAULT NULL,
`nb_data` int(11) DEFAULT NULL,
`temperature` float DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8'''
def __init__(self, db, average_period_minutes=0):
super(MysqlCurrentCostMessageHandler, self).__init__(['watt', 'temperature'], average_period_minutes)
self.db = db
asyncio.async(self.setup_db())
@asyncio.coroutine
def setup_db(self):
with (yield from self.db) as conn:
cur = yield from conn.cursor()
yield from cur.execute(MysqlCurrentCostMessageHandler.CREATE_TABLE_SQL)
yield from cur.fetchone()
yield from cur.close()
@asyncio.coroutine
def save(self, average_message):
with (yield from self.db) as conn:
cursor = yield from conn.cursor()
yield from cursor.execute(
'INSERT INTO current_cost (timestamp, watt, minutes, nb_data, temperature) values (\'%s\', %s, %s, %s, %s) ' % (
average_message['date'].strftime('%Y-%m-%d %H:%M:%S'), average_message['watt'], average_message['minutes'],
average_message['nb_data'],
average_message['temperature']))
yield from cursor.close()
class MysqlTemperatureMessageHandler(AverageMemoryMessageHandler):
CREATE_TABLE_SQL = '''CREATE TABLE IF NOT EXISTS `%s` (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`temperature` float DEFAULT NULL,
`minutes` int(11) DEFAULT NULL,
`nb_data` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8'''
def __init__(self, db, table_name, average_period_minutes=0):
super().__init__(['temperature'], average_period_minutes)
self.table_name = table_name
self.db = db
asyncio.async(self.setup_db())
@asyncio.coroutine
def setup_db(self):
with (yield from self.db) as conn:
cur = yield from conn.cursor()
yield from cur.execute(MysqlTemperatureMessageHandler.CREATE_TABLE_SQL % self.table_name)
yield from cur.fetchone()
yield from cur.close()
@asyncio.coroutine
def save(self, average_message):
with (yield from self.db) as conn:
cursor = yield from conn.cursor()
yield from cursor.execute(
'INSERT INTO {table_name} (timestamp, temperature, minutes, nb_data) values (%s, %s, %s, %s)'.format(
table_name=self.table_name), (
average_message['date'].strftime('%Y-%m-%d %H:%M:%S'),
average_message['temperature'],
average_message['minutes'],
average_message['nb_data']))
yield from cursor.close()
| {
"content_hash": "f16678554ce91196cf317f68b2b47568",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 128,
"avg_line_length": 46.851851851851855,
"alnum_prop": 0.5588932806324111,
"repo_name": "bamthomas/DomoPyc",
"id": "d5803700ac2a8deadb3b6ad744de009743f48ea6",
"size": "3810",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "domopyc/subscribers/mysql_toolbox.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "7218"
},
{
"name": "CSS",
"bytes": "17103"
},
{
"name": "JavaScript",
"bytes": "18910"
},
{
"name": "Python",
"bytes": "76024"
}
],
"symlink_target": ""
} |
"""Includes all the fields classes from `marshmallow.fields` as well as
fields for serializing JSON API-formatted hyperlinks.
"""
from marshmallow import ValidationError
# Make core fields importable from marshmallow_jsonapi
from marshmallow.fields import * # noqa
from marshmallow.utils import get_value, is_collection
from .utils import resolve_params
class BaseRelationship(Field):
"""Base relationship field.
This is used by `marshmallow_jsonapi.Schema` to determine which
fields should be formatted as relationship objects.
See: http://jsonapi.org/format/#document-resource-object-relationships
"""
pass
class Relationship(BaseRelationship):
"""Framework-independent field which serializes to a "relationship object".
See: http://jsonapi.org/format/#document-resource-object-relationships
Examples: ::
author = Relationship(
related_url='/authors/{author_id}',
related_url_kwargs={'author_id': '<author.id>'},
)
comments = Relationship(
related_url='/posts/{post_id}/comments/',
related_url_kwargs={'post_id': '<id>'},
many=True, include_data=True,
type_='comments'
)
This field is read-only by default.
:param str related_url: Format string for related resource links.
:param dict related_url_kwargs: Replacement fields for `related_url`. String arguments
enclosed in `< >` will be interpreted as attributes to pull from the target object.
:param str self_url: Format string for self relationship links.
:param dict self_url_kwargs: Replacement fields for `self_url`. String arguments
enclosed in `< >` will be interpreted as attributes to pull from the target object.
:param bool include_data: Whether to include a resource linkage
(http://jsonapi.org/format/#document-resource-object-linkage) in the serialized result.
:param bool many: Whether the relationship represents a many-to-one or many-to-many
relationship. Only affects serialization of the resource linkage.
:param str type_: The type of resource.
:param str id_field: Attribute name to pull ids from if a resource linkage is included.
"""
id_field = 'id'
def __init__(
self,
related_url='', related_url_kwargs=None,
self_url='', self_url_kwargs=None,
include_data=False, many=False, type_=None, id_field=None, **kwargs
):
self.related_url = related_url
self.related_url_kwargs = related_url_kwargs or {}
self.self_url = self_url
self.self_url_kwargs = self_url_kwargs or {}
if include_data and not type_:
raise ValueError('include_data=True requires the type_ argument.')
self.many = many
self.include_data = include_data
self.type_ = type_
self.id_field = id_field or self.id_field
super(Relationship, self).__init__(**kwargs)
def get_related_url(self, obj):
if self.related_url:
kwargs = resolve_params(obj, self.related_url_kwargs)
return self.related_url.format(**kwargs)
return None
def get_self_url(self, obj):
if self.self_url:
kwargs = resolve_params(obj, self.self_url_kwargs)
return self.self_url.format(**kwargs)
return None
def add_resource_linkage(self, value):
def stringify(value):
if value is not None:
return str(value)
return value
if self.many:
included_data = [{
'type': self.type_,
'id': stringify(get_value(self.id_field, each, each))
} for each in value]
else:
included_data = {
'type': self.type_,
'id': stringify(get_value(self.id_field, value, value))
}
return included_data
def extract_value(self, data):
"""Extract the id key and validate the request structure."""
errors = []
if 'id' not in data:
errors.append('Must have an `id` field')
if 'type' not in data:
errors.append('Must have a `type` field')
elif data['type'] != self.type_:
errors.append('Invalid `type` specified')
if errors:
raise ValidationError(errors)
return data.get('id')
def deserialize(self, value, attr=None, data=None):
"""Deserialize ``value``.
:raise ValidationError: If the value is not type `dict`, if the
value does not contain a `data` key, and if the value is
required but unspecified.
"""
if not isinstance(value, dict) or 'data' not in value:
raise ValidationError('Must include a `data` key')
return super(Relationship, self).deserialize(value['data'], attr, data)
def _deserialize(self, value, attr, obj):
if self.many:
if not is_collection(value):
raise ValidationError('Relationship is list-like')
return [self.extract_value(item) for item in value]
if is_collection(value):
raise ValidationError('Relationship is not list-like')
return self.extract_value(value)
def _serialize(self, value, attr, obj):
dict_class = self.parent.dict_class if self.parent else dict
ret = dict_class()
self_url = self.get_self_url(obj)
related_url = self.get_related_url(obj)
if self_url or related_url:
ret['links'] = dict_class()
if self_url:
ret['links']['self'] = self_url
if related_url:
ret['links']['related'] = related_url
if self.include_data:
if value is None:
ret['data'] = [] if self.many else None
else:
ret['data'] = self.add_resource_linkage(value)
return ret
| {
"content_hash": "648801f86861125bd320b3208565828c",
"timestamp": "",
"source": "github",
"line_count": 163,
"max_line_length": 95,
"avg_line_length": 36.49079754601227,
"alnum_prop": 0.6114660390047074,
"repo_name": "Tim-Erwin/marshmallow-jsonapi",
"id": "129a69d0282ae52ab35170e690feb39ce19d36d8",
"size": "5972",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "marshmallow_jsonapi/fields.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "52264"
}
],
"symlink_target": ""
} |
from django.contrib.auth.models import User
from django.contrib.auth.tests.utils import skipIfCustomUser
from django.test import TestCase, Client
from django.test import override_settings
from .settings import FLATPAGES_TEMPLATES
@override_settings(
LOGIN_URL='/accounts/login/',
MIDDLEWARE_CLASSES=(
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
),
ROOT_URLCONF='django.contrib.flatpages.tests.urls',
CSRF_FAILURE_VIEW='django.views.csrf.csrf_failure',
TEMPLATES=FLATPAGES_TEMPLATES,
SITE_ID=1,
)
class FlatpageCSRFTests(TestCase):
fixtures = ['sample_flatpages', 'example_site']
def setUp(self):
self.client = Client(enforce_csrf_checks=True)
def test_view_flatpage(self):
"A flatpage can be served through a view, even when the middleware is in use"
response = self.client.get('/flatpage_root/flatpage/')
self.assertEqual(response.status_code, 200)
self.assertContains(response, "<p>Isn't it flat!</p>")
def test_view_non_existent_flatpage(self):
"A non-existent flatpage raises 404 when served through a view, even when the middleware is in use"
response = self.client.get('/flatpage_root/no_such_flatpage/')
self.assertEqual(response.status_code, 404)
@skipIfCustomUser
def test_view_authenticated_flatpage(self):
"A flatpage served through a view can require authentication"
response = self.client.get('/flatpage_root/sekrit/')
self.assertRedirects(response, '/accounts/login/?next=/flatpage_root/sekrit/')
User.objects.create_user('testuser', 'test@example.com', 's3krit')
self.client.login(username='testuser', password='s3krit')
response = self.client.get('/flatpage_root/sekrit/')
self.assertEqual(response.status_code, 200)
self.assertContains(response, "<p>Isn't it sekrit!</p>")
def test_fallback_flatpage(self):
"A flatpage can be served by the fallback middleware"
response = self.client.get('/flatpage/')
self.assertEqual(response.status_code, 200)
self.assertContains(response, "<p>Isn't it flat!</p>")
def test_fallback_non_existent_flatpage(self):
"A non-existent flatpage raises a 404 when served by the fallback middleware"
response = self.client.get('/no_such_flatpage/')
self.assertEqual(response.status_code, 404)
def test_post_view_flatpage(self):
"POSTing to a flatpage served through a view will raise a CSRF error if no token is provided (Refs #14156)"
response = self.client.post('/flatpage_root/flatpage/')
self.assertEqual(response.status_code, 403)
def test_post_fallback_flatpage(self):
"POSTing to a flatpage served by the middleware will raise a CSRF error if no token is provided (Refs #14156)"
response = self.client.post('/flatpage/')
self.assertEqual(response.status_code, 403)
def test_post_unknown_page(self):
"POSTing to an unknown page isn't caught as a 403 CSRF error"
response = self.client.post('/no_such_page/')
self.assertEqual(response.status_code, 404)
| {
"content_hash": "8c82f532fe5bbd9f97517c7c47274966",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 118,
"avg_line_length": 45.68421052631579,
"alnum_prop": 0.6984447004608295,
"repo_name": "iambibhas/django",
"id": "7b35f621fdaf77f3c4a540a4a578a224e3a60608",
"size": "3472",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "django/contrib/flatpages/tests/test_csrf.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "53429"
},
{
"name": "JavaScript",
"bytes": "103687"
},
{
"name": "Makefile",
"bytes": "5765"
},
{
"name": "Python",
"bytes": "10481639"
},
{
"name": "Shell",
"bytes": "10452"
}
],
"symlink_target": ""
} |
"""
Tools for converting PyPI packages to conda recipes.
"""
from __future__ import absolute_import, division, print_function
import requests
import keyword
import os
import re
import subprocess
import sys
from collections import defaultdict
from os import makedirs, listdir, getcwd, chdir
from os.path import join, isdir, exists, isfile
from tempfile import mkdtemp
from shutil import copy2
if sys.version_info < (3,):
from xmlrpclib import ServerProxy, Transport, ProtocolError
else:
from xmlrpc.client import ServerProxy, Transport, ProtocolError
from conda.fetch import (download, handle_proxy_407)
from conda.connection import CondaSession
from conda.utils import human_bytes, hashsum_file
from conda.install import rm_rf
from conda.compat import input, configparser, StringIO, string_types, PY3
from conda.config import get_proxy_servers
from conda.cli.common import spec_from_line
from conda_build.utils import tar_xf, unzip
from conda_build.source import SRC_CACHE, apply_patch
from conda_build.build import create_env
from conda_build.config import config
from requests.packages.urllib3.util.url import parse_url
PYPI_META = """\
package:
name: {packagename}
version: "{version}"
source:
fn: {filename}
url: {pypiurl}
{usemd5}md5: {md5}
# patches:
# List any patch files here
# - fix.patch
{build_comment}build:
{noarch_python_comment}noarch_python: True
{egg_comment}preserve_egg_dir: True
{entry_comment}entry_points:
# Put any entry points (scripts to be generated automatically) here. The
# syntax is module:function. For example
#
# - {packagename} = {packagename}:main
#
# Would create an entry point called {packagename} that calls {packagename}.main()
{entry_points}
# If this is a new build for the same version, increment the build
# number. If you do not include this key, it defaults to 0.
# number: 1
requirements:
build:
- python{build_depends}
run:
- python{run_depends}
{test_comment}test:
# Python imports
{import_comment}imports:{import_tests}
{entry_comment}commands:
# You can put test commands to be run here. Use this to test that the
# entry points work.
{test_commands}
# You can also put a file called run_test.py in the recipe that will be run
# at test time.
{requires_comment}requires:{tests_require}
# Put any additional test requirements here. For example
# - nose
about:
{home_comment}home: {homeurl}
license: {license}
{summary_comment}summary: {summary}
# See
# http://docs.continuum.io/conda/build.html for
# more information about meta.yaml
"""
PYPI_BUILD_SH = """\
#!/bin/bash
$PYTHON setup.py install
# Add more build steps here, if they are necessary.
# See
# http://docs.continuum.io/conda/build.html
# for a list of environment variables that are set during the build process.
"""
PYPI_BLD_BAT = """\
"%PYTHON%" setup.py install
if errorlevel 1 exit 1
:: Add more build steps here, if they are necessary.
:: See
:: http://docs.continuum.io/conda/build.html
:: for a list of environment variables that are set during the build process.
"""
# Note the {} formatting bits here
DISTUTILS_PATCH = '''\
diff core.py core.py
--- core.py
+++ core.py
@@ -166,5 +167,40 @@ def setup (**attrs):
\n
+# ====== BEGIN CONDA SKELETON PYPI PATCH ======
+
+import distutils.core
+import io
+import os.path
+import sys
+import yaml
+from yaml import Loader, SafeLoader
+
+# Override the default string handling function to always return unicode
+# objects (taken from StackOverflow)
+def construct_yaml_str(self, node):
+ return self.construct_scalar(node)
+Loader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str)
+SafeLoader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str)
+
+def setup(*args, **kwargs):
+ data = {{}}
+ data['tests_require'] = kwargs.get('tests_require', [])
+ data['install_requires'] = kwargs.get('install_requires', [])
+ data['extras_require'] = kwargs.get('extras_require', {{}})
+ data['entry_points'] = kwargs.get('entry_points', [])
+ data['packages'] = kwargs.get('packages', [])
+ data['setuptools'] = 'setuptools' in sys.modules
+ data['summary'] = kwargs.get('description', None)
+ data['homeurl'] = kwargs.get('url', None)
+ data['license'] = kwargs.get('license', None)
+ data['name'] = kwargs.get('name', '??PACKAGE-NAME-UNKNOWN??')
+ data['classifiers'] = kwargs.get('classifiers', None)
+ data['version'] = kwargs.get('version', '??PACKAGE-VERSION-UNKNOWN??')
+ with io.open(os.path.join("{}", "pkginfo.yaml"), 'w', encoding='utf-8') as fn:
+ fn.write(yaml.safe_dump(data, encoding=None))
+
+
+# ======= END CONDA SKELETON PYPI PATCH ======
\n
def run_setup (script_name, script_args=None, stop_after="run"):
"""Run a setup script in a somewhat controlled environment, and
'''
INDENT = '\n - '
# https://gist.github.com/chrisguitarguy/2354951
class RequestsTransport(Transport):
"""
Drop in Transport for xmlrpclib that uses Requests instead of httplib
"""
# change our user agent to reflect Requests
user_agent = "Python XMLRPC with Requests (python-requests.org)"
# override this if you'd like to https
use_https = True
session = CondaSession()
def request(self, host, handler, request_body, verbose):
"""
Make an xmlrpc request.
"""
headers = {
'User-Agent': self.user_agent,
'Content-Type': 'text/xml',
}
url = self._build_url(host, handler)
try:
resp = self.session.post(url, data=request_body, headers=headers, proxies=self.session.proxies)
resp.raise_for_status()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 407: # Proxy Authentication Required
handle_proxy_407(url, self.session)
# Try again
return self.request(host, handler, request_body, verbose)
else:
raise
except requests.exceptions.ConnectionError as e:
# requests isn't so nice here. For whatever reason, https gives this
# error and http gives the above error. Also, there is no status_code
# attribute here. We have to just check if it looks like 407. See
# https://github.com/kennethreitz/requests/issues/2061.
if "407" in str(e): # Proxy Authentication Required
handle_proxy_407(url, self.session)
# Try again
return self.request(host, handler, request_body, verbose)
else:
raise
except requests.RequestException as e:
raise ProtocolError(url, resp.status_code, str(e), resp.headers)
else:
return self.parse_response(resp)
def parse_response(self, resp):
"""
Parse the xmlrpc response.
"""
p, u = self.getparser()
p.feed(resp.text)
p.close()
return u.close()
def _build_url(self, host, handler):
"""
Build a url for our request based on the host, handler and use_http
property
"""
scheme = 'https' if self.use_https else 'http'
return '%s://%s/%s' % (scheme, host, handler)
def get_xmlrpc_client(pypi_url):
proxies = get_proxy_servers()
if proxies:
transport = RequestsTransport()
else:
transport = None
return ServerProxy(pypi_url, transport=transport)
def main(args, parser):
client = get_xmlrpc_client(args.pypi_url)
package_dicts = {}
[output_dir] = args.output_dir
all_packages = client.list_packages()
all_packages_lower = [i.lower() for i in all_packages]
args.created_recipes = []
while args.packages:
[output_dir] = args.output_dir
package = args.packages.pop()
args.created_recipes.append(package)
is_url = ':' in package
if not is_url:
dir_path = join(output_dir, package.lower())
if exists(dir_path) and not args.version_compare:
raise RuntimeError("directory already exists: %s" % dir_path)
d = package_dicts.setdefault(package,
{
'packagename': package.lower(),
'run_depends': '',
'build_depends': '',
'entry_points': '',
'build_comment': '# ',
'noarch_python_comment': '# ',
'test_commands': '',
'requires_comment': '#',
'tests_require': '',
'usemd5': '',
'test_comment': '',
'entry_comment': '# ',
'egg_comment': '# ',
'summary_comment': '',
'home_comment': '',
})
if is_url:
del d['packagename']
if is_url:
d['version'] = 'UNKNOWN'
else:
versions = client.package_releases(package, True)
if args.version_compare:
version_compare(args, package, versions)
if args.version:
[version] = args.version
if version not in versions:
sys.exit("Error: Version %s of %s is not available on PyPI."
% (version, package))
d['version'] = version
else:
if not versions:
# The xmlrpc interface is case sensitive, but the index itself
# is apparently not (the last time I checked,
# len(set(all_packages_lower)) == len(set(all_packages)))
if package.lower() in all_packages_lower:
cased_package = all_packages[all_packages_lower.index(package.lower())]
if cased_package != package:
print("%s not found, trying %s" % (package, cased_package))
args.packages.append(cased_package)
del package_dicts[package]
continue
sys.exit("Error: Could not find any versions of package %s" % package)
if len(versions) > 1:
print("Warning, the following versions were found for %s" %
package)
for ver in versions:
print(ver)
print("Using %s" % versions[0])
print("Use --version to specify a different version.")
d['version'] = versions[0]
data, d['pypiurl'], d['filename'], d['md5'] = get_download_data(args,
client,
package,
d['version'],
is_url)
if d['md5'] == '':
d['usemd5'] = '# '
else:
d['usemd5'] = ''
d['import_tests'] = ''
get_package_metadata(args, package, d, data)
if d['import_tests'] == '':
d['import_comment'] = '# '
else:
d['import_comment'] = ''
d['import_tests'] = INDENT + d['import_tests']
if d['tests_require'] == '':
d['requires_comment'] = '# '
else:
d['requires_comment'] = ''
d['tests_require'] = INDENT + d['tests_require']
if d['entry_comment'] == d['import_comment'] == '# ':
d['test_comment'] = '# '
for package in package_dicts:
d = package_dicts[package]
name = d['packagename']
makedirs(join(output_dir, name))
print("Writing recipe for %s" % package.lower())
with open(join(output_dir, name, 'meta.yaml'), 'w') as f:
f.write(PYPI_META.format(**d))
with open(join(output_dir, name, 'build.sh'), 'w') as f:
f.write(PYPI_BUILD_SH.format(**d))
with open(join(output_dir, name, 'bld.bat'), 'w') as f:
f.write(PYPI_BLD_BAT.format(**d))
print("Done")
def get_download_data(args, client, package, version, is_url):
data = client.release_data(package, version) if not is_url else None
urls = client.release_urls(package, version) if not is_url else [package]
if not is_url and not args.all_urls:
# Try to find source urls
urls = [url for url in urls if url['python_version'] == 'source']
if not urls:
if 'download_url' in data:
urls = [defaultdict(str, {'url': data['download_url']})]
if not urls[0]['url']:
# The package doesn't have a url, or maybe it only has a wheel.
sys.exit("Error: Could not build recipe for %s. "
"Could not find any valid urls." % package)
U = parse_url(urls[0]['url'])
if not U.path:
sys.exit("Error: Could not parse url for %s: %s" %
(package, U))
urls[0]['filename'] = U.path.rsplit('/')[-1]
fragment = U.fragment or ''
if fragment.startswith('md5='):
md5 = fragment[len('md5='):]
else:
md5 = ''
else:
sys.exit("Error: No source urls found for %s" % package)
if len(urls) > 1 and not args.noprompt:
print("More than one source version is available for %s:" %
package)
if args.manual_url:
for i, url in enumerate(urls):
print("%d: %s (%s) %s" % (i, url['url'],
human_bytes(url['size']), url['comment_text']))
n = int(input("which version should i use? "))
else:
print("Using the one with the least source size")
print("use --manual-url to override this behavior")
min_siz, n = min([(url['size'], i)
for (i, url) in enumerate(urls)])
else:
n = 0
if not is_url:
print("Using url %s (%s) for %s." % (urls[n]['url'],
human_bytes(urls[n]['size'] or 0), package))
pypiurl = urls[n]['url']
md5 = urls[n]['md5_digest']
filename = urls[n]['filename'] or 'package'
else:
print("Using url %s" % package)
pypiurl = package
U = parse_url(package)
if U.fragment and U.fragment.startswith('md5='):
md5 = U.fragment[len('md5='):]
else:
md5 = ''
# TODO: 'package' won't work with unpack()
filename = U.path.rsplit('/', 1)[-1] or 'package'
return (data, pypiurl, filename, md5)
def version_compare(args, package, versions):
if not versions:
# PyPI is case sensitive, this will pass control
# to a method in main() to take care of that.
return
from os.path import abspath, isdir
from conda_build.metadata import MetaData
from conda.resolve import normalized_version
nv = normalized_version
norm_versions = [nv(ver) for ver in versions]
recipe_dir = abspath(package.lower())
if not isdir(recipe_dir):
sys.exit("Error: no such directory: %s" % recipe_dir)
m = MetaData(recipe_dir)
local_version = nv(m.version())
print("Local recipe for %s has version %s" % (package, local_version))
if local_version not in versions:
sys.exit("Error: %s %s is not available on PyPI."
% (package, local_version))
else:
# Comparing normalized versions, displaying non normalized ones
new_versions = versions[:norm_versions.index(local_version)]
if len(new_versions) > 0:
print("Following new versions of %s are avaliable" % (package))
for ver in new_versions:
print(ver)
else:
print("No new version for %s is available" % (package))
sys.exit()
def get_package_metadata(args, package, d, data):
print("Downloading %s" % package)
[output_dir] = args.output_dir
pkginfo = get_pkginfo(package,
filename=d['filename'],
pypiurl=d['pypiurl'],
md5=d['md5'],
python_version=args.python_version)
setuptools_build = pkginfo['setuptools']
setuptools_run = False
# Look at the entry_points and construct console_script and
# gui_scripts entry_points for conda
entry_points = pkginfo['entry_points']
if entry_points:
if isinstance(entry_points, str):
# makes sure it is left-shifted
newstr = "\n".join(x.strip()
for x in entry_points.splitlines())
config = configparser.ConfigParser()
entry_points = {}
try:
config.readfp(StringIO(newstr))
except Exception as err:
print("WARNING: entry-points not understood: ",
err)
print("The string was", newstr)
entry_points = pkginfo['entry_points']
else:
setuptools_run = True
for section in config.sections():
if section in ['console_scripts', 'gui_scripts']:
value = ['%s=%s' % (option, config.get(section, option))
for option in config.options(section)]
entry_points[section] = value
if not isinstance(entry_points, dict):
print("WARNING: Could not add entry points. They were:")
print(entry_points)
else:
cs = entry_points.get('console_scripts', [])
gs = entry_points.get('gui_scripts', [])
if isinstance(cs, string_types):
cs = [cs]
if isinstance(gs, string_types):
gs = [gs]
# We have *other* kinds of entry-points so we need
# setuptools at run-time
if set(entry_points.keys()) - {'console_scripts', 'gui_scripts'}:
setuptools_build = True
setuptools_run = True
entry_list = (
cs
# TODO: Use pythonw for these
+ gs)
if len(cs + gs) != 0:
d['entry_points'] = INDENT.join([''] + entry_list)
d['entry_comment'] = ''
d['build_comment'] = ''
d['test_commands'] = INDENT.join([''] + make_entry_tests(entry_list))
requires = get_requirements(package, pkginfo, all_extras=args.all_extras)
if requires or setuptools_build or setuptools_run:
deps = []
if setuptools_run:
deps.append('setuptools')
for deptext in requires:
if isinstance(deptext, string_types):
deptext = deptext.splitlines()
# Every item may be a single requirement
# or a multiline requirements string...
for dep in deptext:
#... and may also contain comments...
dep = dep.split('#')[0].strip()
if dep: #... and empty (or comment only) lines
spec = spec_from_line(dep)
if spec is None:
sys.exit("Error: Could not parse: %s" % dep)
deps.append(spec)
if 'setuptools' in deps:
setuptools_build = False
setuptools_run = False
d['egg_comment'] = ''
d['build_comment'] = ''
d['build_depends'] = INDENT.join([''] +
['setuptools'] * setuptools_build +
deps)
d['run_depends'] = INDENT.join([''] +
['setuptools'] * setuptools_run +
deps)
if args.recursive:
for dep in deps:
dep = dep.split()[0]
if not exists(join(output_dir, dep)):
if dep not in args.created_recipes:
args.packages.append(dep)
if args.noarch_python:
d['build_comment'] = ''
d['noarch_python_comment'] = ''
if 'packagename' not in d:
d['packagename'] = pkginfo['name'].lower()
if d['version'] == 'UNKNOWN':
d['version'] = pkginfo['version']
if pkginfo['packages']:
deps = set(pkginfo['packages'])
if d['import_tests']:
if not d['import_tests'] or d['import_tests'] == 'PLACEHOLDER':
olddeps = []
else:
olddeps = [x for x in d['import_tests'].split()
if x != '-']
deps = set(olddeps) | deps
d['import_tests'] = INDENT.join(sorted(deps))
d['import_comment'] = ''
d['tests_require'] = INDENT.join(sorted([spec_from_line(pkg) for pkg
in pkginfo['tests_require']]))
if pkginfo['homeurl'] is not None:
d['homeurl'] = pkginfo['homeurl']
else:
if data and 'homeurl' in data:
d['homeurl'] = data['homeurl']
else:
d['homeurl'] = "The package home page"
d['home_comment'] = '#'
if pkginfo['summary']:
d['summary'] = repr(pkginfo['summary'])
else:
if data:
d['summary'] = repr(data['summary'])
else:
d['summary'] = "Summary of the package"
d['summary_comment'] = '#'
if d['summary'].startswith("u'") or d['summary'].startswith('u"'):
d['summary'] = d['summary'][1:]
license_classifier = "License :: OSI Approved :: "
if pkginfo['classifiers']:
licenses = [classifier.split(license_classifier, 1)[1] for
classifier in pkginfo['classifiers'] if classifier.startswith(license_classifier)]
elif data and 'classifiers' in data:
licenses = [classifier.split(license_classifier, 1)[1] for classifier in
data['classifiers'] if classifier.startswith(license_classifier)]
else:
licenses = []
if not licenses:
if pkginfo['license']:
license = pkginfo['license']
elif data and 'license' in data:
license = data['license']
else:
license = None
if license:
if args.noprompt:
pass
elif '\n' not in license:
print('Using "%s" for the license' % license)
else:
# Some projects put the whole license text in this field
print("This is the license for %s" % package)
print()
print(license)
print()
license = input("What license string should I use? ")
else:
if args.noprompt:
license = "UNKNOWN"
else:
license = input(("No license could be found for %s on " +
"PyPI or in the source. What license should I use? ") %
package)
else:
license = ' or '.join(licenses)
d['license'] = license
def valid(name):
if (re.match("[_A-Za-z][_a-zA-Z0-9]*$", name)
and not keyword.iskeyword(name)):
return name
else:
return ''
def unpack(src_path, tempdir):
if src_path.endswith(('.tar.gz', '.tar.bz2', '.tgz', '.tar.xz', '.tar')):
tar_xf(src_path, tempdir)
elif src_path.endswith('.zip'):
unzip(src_path, tempdir)
else:
raise Exception("not a valid source")
def get_dir(tempdir):
lst = [fn for fn in listdir(tempdir) if not fn.startswith('.') and
isdir(join(tempdir, fn))]
if len(lst) == 1:
dir_path = join(tempdir, lst[0])
if isdir(dir_path):
return dir_path
if not lst:
return tempdir
raise Exception("could not find unpacked source dir")
def get_requirements(package, pkginfo, all_extras=True):
# Look for package[extra,...] features spec:
match_extras = re.match(r'^([^[]+)\[([^]]+)\]$', package)
if match_extras:
package, extras = match_extras.groups()
extras = extras.split(',')
else:
extras = []
# Extract requested extra feature requirements...
if all_extras:
extras_require = list(pkginfo['extras_require'].values())
else:
try:
extras_require = [pkginfo['extras_require'][x] for x in extras]
except KeyError:
sys.exit("Error: Invalid extra features: [%s]" % ','.join(extras))
# ... and collect all needed requirement specs in a single list:
requires = []
for specs in [pkginfo['install_requires']] + extras_require:
if isinstance(specs, string_types):
requires.append(specs)
else:
requires.extend(specs)
return requires
def get_pkginfo(package, filename, pypiurl, md5, python_version):
# Unfortunately, two important pieces of metadata are only stored in
# the package itself: the dependencies, and the entry points (if the
# package uses distribute). Our strategy is to download the package
# and "fake" distribute/setuptools's setup() function to get this
# information from setup.py. If this sounds evil, keep in mind that
# distribute itself already works by monkeypatching distutils.
import yaml
tempdir = mkdtemp('conda_skeleton_' + filename)
if not isdir(SRC_CACHE):
makedirs(SRC_CACHE)
try:
# Download it to the build source cache. That way, you have
# it.
download_path = join(SRC_CACHE, filename)
if not isfile(download_path) or \
hashsum_file(download_path, 'md5') != md5:
download(pypiurl, join(SRC_CACHE, filename))
else:
print("Using cached download")
print("Unpacking %s..." % package)
unpack(join(SRC_CACHE, filename), tempdir)
print("done")
print("working in %s" % tempdir)
src_dir = get_dir(tempdir)
# TODO: find args parameters needed by run_setuppy
run_setuppy(src_dir, tempdir, python_version)
with open(join(tempdir, 'pkginfo.yaml')) as fn:
pkginfo = yaml.load(fn)
finally:
rm_rf(tempdir)
return pkginfo
def run_setuppy(src_dir, temp_dir, python_version):
'''
Patch distutils and then run setup.py in a subprocess.
:param src_dir: Directory containing the source code
:type src_dir: str
:param temp_dir: Temporary directory for doing for storing pkginfo.yaml
:type temp_dir: str
'''
# Do everything in the build env in case the setup.py install goes
# haywire.
# TODO: Try with another version of Python if this one fails. Some
# packages are Python 2 or Python 3 only.
create_env(config.build_prefix, ['python %s*' % python_version, 'pyyaml',
'setuptools', 'numpy'], clear_cache=False)
stdlib_dir = join(config.build_prefix,
'Lib' if sys.platform == 'win32'
else 'lib/python%s' % python_version)
patch = join(temp_dir, 'pypi-distutils.patch')
with open(patch, 'w') as f:
f.write(DISTUTILS_PATCH.format(temp_dir.replace('\\','\\\\')))
if exists(join(stdlib_dir, 'distutils', 'core.py-copy')):
rm_rf(join(stdlib_dir, 'distutils', 'core.py'))
copy2(join(stdlib_dir, 'distutils', 'core.py-copy'), join(stdlib_dir, 'distutils', 'core.py'))
# Avoid race conditions. Invalidate the cache.
if PY3:
rm_rf(join(stdlib_dir, 'distutils', '__pycache__',
'core.cpython-%s%s.pyc' % sys.version_info[:2]))
rm_rf(join(stdlib_dir, 'distutils', '__pycache__',
'core.cpython-%s%s.pyo' % sys.version_info[:2]))
else:
rm_rf(join(stdlib_dir, 'distutils', 'core.pyc'))
rm_rf(join(stdlib_dir, 'distutils', 'core.pyo'))
else:
copy2(join(stdlib_dir, 'distutils', 'core.py'), join(stdlib_dir,
'distutils', 'core.py-copy'))
apply_patch(join(stdlib_dir, 'distutils'), patch)
# Save PYTHONPATH for later
env = os.environ.copy()
if 'PYTHONPATH' in env:
env[str('PYTHONPATH')] = str(src_dir + ':' + env['PYTHONPATH'])
else:
env[str('PYTHONPATH')] = str(src_dir)
cwd = getcwd()
chdir(src_dir)
cmdargs = [config.build_python, 'setup.py', 'install']
try:
subprocess.check_call(cmdargs, env=env)
except subprocess.CalledProcessError:
print('$PYTHONPATH = %s' % env['PYTHONPATH'])
sys.exit('Error: command failed: %s' % ' '.join(cmdargs))
finally:
chdir(cwd)
def make_entry_tests(entry_list):
tests = []
for entry_point in entry_list:
entry = entry_point.partition('=')[0].strip()
tests.append(entry + " --help")
return tests
| {
"content_hash": "02b2006b2130d9d65544dddb0000755a",
"timestamp": "",
"source": "github",
"line_count": 812,
"max_line_length": 107,
"avg_line_length": 35.80541871921182,
"alnum_prop": 0.5546192474375731,
"repo_name": "rmcgibbo/conda-build",
"id": "4be696e52fddee2a117494c80feef6dddd071d54",
"size": "29074",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "conda_build/pypi.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "4537"
},
{
"name": "JavaScript",
"bytes": "10"
},
{
"name": "Python",
"bytes": "369289"
},
{
"name": "Shell",
"bytes": "7751"
}
],
"symlink_target": ""
} |
from setuptools import setup, find_packages
from distutils.command.build import build as distutils_build
from os import chdir
from os.path import abspath, dirname
########################################################################
chdir(dirname(abspath(__file__)))
########################################################################
version_ns_global, version_ns_local = {}, {}
with open('weight_cal_grid/version.py') as f:
exec(f.read(), version_ns_global, version_ns_local)
class Version(object): pass
version = Version()
version.__dict__ = version_ns_local
# Now we can use version.package_version etc as if we had imported
# the version module.
########################################################################
with open('README.md') as readme_file:
long_description = readme_file.read()
########################################################################
# Hook building *.mo from *.po into the standard build target
distutils_build.sub_commands.append(('compile_catalog', None))
########################################################################
setup(
name=version.package_name,
version=version.package_version,
description='print a grid on sheet of paper and mark your weight every day',
long_description=long_description,
url='https://github.com/ndim/weight-calendar-grid',
author='Hans Ulrich Niedermann',
author_email='hun@n-dimensional.de',
license='MIT',
packages=find_packages(exclude=[
'*.tests',
]),
install_requires=[
'PyYAML',
],
package_data={
'': [
'*.md',
'LICENSE',
],
'weight_cal_grid': [
'*.png',
'locale/weight-calendar-grid.pot',
'locale/*/LC_MESSAGES/*.mo',
],
},
include_package_data=True,
extras_require={
'GUI': ['cairo'],
'PDF-reportlab': ['reportlab'],
'PDF-pdflatex': ['pdflatex', 'TikZ'],
},
entry_points = {
'console_scripts': [
'wcg-cli=weight_cal_grid.cli:main',
],
'gui_scripts': [
'wcg-gui=weight_cal_grid.gui:main',
],
},
setup_requires = [
'Babel>=1.3',
],
test_suite='nose.collector',
tests_require=['nose'],
zip_safe=False
)
########################################################################
| {
"content_hash": "70cf61774e75379d0bb2a5724bf1d8d3",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 80,
"avg_line_length": 28.759036144578314,
"alnum_prop": 0.48847926267281105,
"repo_name": "ndim/weight-calendar-grid",
"id": "252e3f02d079f9d289705cf6e320bb0710e7c9b2",
"size": "2485",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "207976"
}
],
"symlink_target": ""
} |
import tarfile
import os
os.mkdir('outdir')
with tarfile.open('example.tar', 'r') as t:
t.extractall('outdir',
members=[t.getmember('README.txt')],
)
print(os.listdir('outdir'))
| {
"content_hash": "6dac016c04e1f7698ded1fe153a0c6e4",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 53,
"avg_line_length": 24.11111111111111,
"alnum_prop": 0.5806451612903226,
"repo_name": "jasonwee/asus-rt-n14uhp-mrtg",
"id": "41ac764be85973e719b1731f2e7962cbfd3fc22c",
"size": "217",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/lesson_data_compression_and_archiving/tarfile_extractall_members.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "45876"
},
{
"name": "HTML",
"bytes": "107072"
},
{
"name": "JavaScript",
"bytes": "161335"
},
{
"name": "Python",
"bytes": "6923750"
},
{
"name": "Shell",
"bytes": "7616"
}
],
"symlink_target": ""
} |
from google.cloud import networkconnectivity_v1alpha1
async def sample_delete_spoke():
# Create a client
client = networkconnectivity_v1alpha1.HubServiceAsyncClient()
# Initialize request argument(s)
request = networkconnectivity_v1alpha1.DeleteSpokeRequest(
name="name_value",
)
# Make the request
operation = client.delete_spoke(request=request)
print("Waiting for operation to complete...")
response = await operation.result()
# Handle the response
print(response)
# [END networkconnectivity_v1alpha1_generated_HubService_DeleteSpoke_async]
| {
"content_hash": "7411e4660bd06a88f5e658a7f529d9aa",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 75,
"avg_line_length": 26.26086956521739,
"alnum_prop": 0.7317880794701986,
"repo_name": "googleapis/python-network-connectivity",
"id": "f41b6ba53a0dfec14f27da2c6749698870a8b1fb",
"size": "2014",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_delete_spoke_async.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2050"
},
{
"name": "Python",
"bytes": "795166"
},
{
"name": "Shell",
"bytes": "30702"
}
],
"symlink_target": ""
} |
from numpy import *
# - given a vector containing all parameters, return a list of unrolled parameters
# - specifically, these parameters, as described in section 3 of the paper, are:
# - rel_dict, dictionary of {dependency relation r: composition matrix W_r}
# - Wv, the matrix for lifting a word embedding to the hidden space
# - b, bias term
# - We, the word embedding matrix
def unroll_params(arr, d, len_voc, rel_list):
mat_size = d * d
rel_dict = {}
ind = 0
for r in rel_list:
rel_dict[r] = arr[ind: ind + mat_size].reshape( (d, d) )
ind += mat_size
Wv = arr[ind : ind + mat_size].reshape( (d, d) )
ind += mat_size
b = arr[ind : ind + d].reshape( (d, 1) )
ind += d
We = arr[ind : ind + len_voc * d].reshape( (d, len_voc))
return [rel_dict, Wv, b, We]
# roll all parameters into a single vector
def roll_params(params, rel_list):
(rel_dict, Wv, b, We) = params
rels = concatenate( [rel_dict[key].ravel() for key in rel_list] )
return concatenate( (rels, Wv.ravel(), b.ravel(), We.ravel() ) )
# randomly initialize all parameters
def gen_dtrnn_params(d, rels):
"""
Returns (dict{rels:[mat]}, Wv, b)
"""
r = sqrt(6) / sqrt(201)
rel_dict = {}
for rel in rels:
rel_dict[rel] = random.rand(d, d) * 2 * r - r
return (
rel_dict,
random.rand(d, d) * 2 * r - r,
zeros((d, 1))
)
# returns list of zero gradients which backprop modifies
def init_dtrnn_grads(rel_list, d, len_voc):
rel_grads = {}
for rel in rel_list:
rel_grads[rel] = zeros( (d, d) )
return [
rel_grads,
zeros((d, d)),
zeros((d, 1)),
zeros((d, len_voc))
]
# random embedding matrix for gradient checks
def gen_rand_we(len_voc, d):
r = sqrt(6) / sqrt(51)
we = random.rand(d, len_voc) * 2 * r - r
return we
| {
"content_hash": "4c5d2fbdb3109253ce3a0a3b3d219466",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 82,
"avg_line_length": 23.933333333333334,
"alnum_prop": 0.6072423398328691,
"repo_name": "ernan/quanta",
"id": "12a1aea01bc8945d78530c2256677a3967318699",
"size": "1795",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "util/gen_util.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "41180"
},
{
"name": "Shell",
"bytes": "485"
}
],
"symlink_target": ""
} |
"""
Django settings for wot_clan_battles project.
Generated by 'django-admin startproject' using Django 1.9.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
import yaml
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '_ex5^g$(23l3%ms)*7s--9k-%!pmm-qw3#mbsci47u!vq2i)o^'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'global_map',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'wot_clan_battles.middleware.WGUserMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'wot_clan_battles.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'wot_clan_battles.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'wotbattles',
'USER': 'wotbattles',
'PASSWORD': 'wotbattles',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s %(module)s:%(lineno)d %(funcName)s %(asctime)s %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
},
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': os.path.join(BASE_DIR, 'debug.log'),
'formatter': 'verbose',
}
},
'loggers': {
'global_map': {
'level': 'DEBUG',
'handlers': ['console', 'file'],
}
}
}
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
DATETIME_FORMAT = 'r'
config = yaml.load(open(os.path.join(BASE_DIR, 'config.yaml')).read())
WARGAMING_KEY = config['WARGAMING_KEY']
| {
"content_hash": "085045366cbe4ae1ff8e230ae59d41e7",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 96,
"avg_line_length": 25.851190476190474,
"alnum_prop": 0.6343541330877274,
"repo_name": "monester/wot-battles",
"id": "d81495cb69b19c27e075ff987f5e9eeffe8a1b18",
"size": "4343",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "wot_clan_battles/settings.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2030"
},
{
"name": "HTML",
"bytes": "5185"
},
{
"name": "JavaScript",
"bytes": "9239"
},
{
"name": "Python",
"bytes": "62515"
},
{
"name": "Shell",
"bytes": "429"
}
],
"symlink_target": ""
} |
from mailchimp import MailChimp
client = MailChimp('didierserrat', 'dde1a01e091c530def679e42f2390b46-us9')
# print client.authorized_app.all()
# print client.authorized_app.get('870970111619')
# print client.automation.all()
# print client.automation.start('870970111619')
print client.growth.all('2822d76480') | {
"content_hash": "c85f14567ce382adf205f1e8d48e23d5",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 74,
"avg_line_length": 22.714285714285715,
"alnum_prop": 0.779874213836478,
"repo_name": "s0x90/python-mailchimp",
"id": "9ad256d579a7a5974ecc5a7392840f06920e7510",
"size": "318",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "27863"
}
],
"symlink_target": ""
} |
"""IoticAgent.IOT module provides a simple wrapper for IoticAgent.Core with
helper objects for Thing, Point, etc.
"""
__version__ = '0.7.0'
from .Client import Client, SearchScope, DescribeScope # NOQA
| {
"content_hash": "cc0110ac7364562bad14feb153433662",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 75,
"avg_line_length": 29.285714285714285,
"alnum_prop": 0.7365853658536585,
"repo_name": "Iotic-Labs/py-IoticAgent",
"id": "54f6a4ac9975884960ca6fa47e40d7cc12cf56cf",
"size": "830",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "src/IoticAgent/IOT/__init__.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "158"
},
{
"name": "HTML",
"bytes": "415"
},
{
"name": "Makefile",
"bytes": "608"
},
{
"name": "Python",
"bytes": "562219"
},
{
"name": "Shell",
"bytes": "193"
}
],
"symlink_target": ""
} |
import os
from setuptools import setup, find_packages
from digits.extensions.view import GROUP as DIGITS_PLUGIN_GROUP
# Utility function to read the README file.
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="digits_image_gradients_view_plugin",
version="0.0.1",
author="Greg Heinrich",
description=("A view plugin for image gradients"),
long_description=read('README'),
license="Apache",
packages=find_packages(),
entry_points={
DIGITS_PLUGIN_GROUP: [
'class=digitsViewPluginImageGradients:Visualization',
]
},
include_package_data=True,
)
| {
"content_hash": "d05bcecd89217d46f2293052b0f00e69",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 70,
"avg_line_length": 25.692307692307693,
"alnum_prop": 0.6781437125748503,
"repo_name": "ethantang95/DIGITS",
"id": "9f23022d96fdc66123f1085e780deebf798eff54",
"size": "738",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "plugins/view/imageGradients/setup.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "4386"
},
{
"name": "HTML",
"bytes": "2638345"
},
{
"name": "JavaScript",
"bytes": "53917"
},
{
"name": "Lua",
"bytes": "110602"
},
{
"name": "Makefile",
"bytes": "113"
},
{
"name": "Protocol Buffer",
"bytes": "1750"
},
{
"name": "Python",
"bytes": "1230584"
},
{
"name": "Shell",
"bytes": "13547"
}
],
"symlink_target": ""
} |
from airflow.contrib.hooks.gcs_hook import GoogleCloudStorageHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
from airflow.exceptions import AirflowException
WILDCARD = '*'
class GoogleCloudStorageToGoogleCloudStorageOperator(BaseOperator):
"""
Copies objects from a bucket to another, with renaming if requested.
:param source_bucket: The source Google cloud storage bucket where the
object is. (templated)
:type source_bucket: str
:param source_object: The source name of the object to copy in the Google cloud
storage bucket. (templated)
You can use only one wildcard for objects (filenames) within your
bucket. The wildcard can appear inside the object name or at the
end of the object name. Appending a wildcard to the bucket name is
unsupported.
:type source_object: str
:param destination_bucket: The destination Google cloud storage bucket
where the object should be. If the destination_bucket is None, it defaults
to source_bucket. (templated)
:type destination_bucket: str
:param destination_object: The destination name of the object in the
destination Google cloud storage bucket. (templated)
If a wildcard is supplied in the source_object argument, this is the
prefix that will be prepended to the final destination objects' paths.
Note that the source path's part before the wildcard will be removed;
if it needs to be retained it should be appended to destination_object.
For example, with prefix ``foo/*`` and destination_object ``blah/``, the
file ``foo/baz`` will be copied to ``blah/baz``; to retain the prefix write
the destination_object as e.g. ``blah/foo``, in which case the copied file
will be named ``blah/foo/baz``.
:type destination_object: str
:param move_object: When move object is True, the object is moved instead
of copied to the new location. This is the equivalent of a mv command
as opposed to a cp command.
:type move_object: bool
:param google_cloud_storage_conn_id: The connection ID to use when
connecting to Google cloud storage.
:type google_cloud_storage_conn_id: str
:param delegate_to: The account to impersonate, if any.
For this to work, the service account making the request must have
domain-wide delegation enabled.
:type delegate_to: str
:param last_modified_time: When specified, the objects will be copied or moved,
only if they were modified after last_modified_time.
If tzinfo has not been set, UTC will be assumed.
:type last_modified_time: datetime.datetime
:Example:
The following Operator would copy a single file named
``sales/sales-2017/january.avro`` in the ``data`` bucket to the file named
``copied_sales/2017/january-backup.avro`` in the ``data_backup`` bucket ::
copy_single_file = GoogleCloudStorageToGoogleCloudStorageOperator(
task_id='copy_single_file',
source_bucket='data',
source_object='sales/sales-2017/january.avro',
destination_bucket='data_backup',
destination_object='copied_sales/2017/january-backup.avro',
google_cloud_storage_conn_id=google_cloud_conn_id
)
The following Operator would copy all the Avro files from ``sales/sales-2017``
folder (i.e. with names starting with that prefix) in ``data`` bucket to the
``copied_sales/2017`` folder in the ``data_backup`` bucket. ::
copy_files = GoogleCloudStorageToGoogleCloudStorageOperator(
task_id='copy_files',
source_bucket='data',
source_object='sales/sales-2017/*.avro',
destination_bucket='data_backup',
destination_object='copied_sales/2017/',
google_cloud_storage_conn_id=google_cloud_conn_id
)
The following Operator would move all the Avro files from ``sales/sales-2017``
folder (i.e. with names starting with that prefix) in ``data`` bucket to the
same folder in the ``data_backup`` bucket, deleting the original files in the
process. ::
move_files = GoogleCloudStorageToGoogleCloudStorageOperator(
task_id='move_files',
source_bucket='data',
source_object='sales/sales-2017/*.avro',
destination_bucket='data_backup',
move_object=True,
google_cloud_storage_conn_id=google_cloud_conn_id
)
"""
template_fields = ('source_bucket', 'source_object', 'destination_bucket',
'destination_object',)
ui_color = '#f0eee4'
@apply_defaults
def __init__(self,
source_bucket,
source_object,
destination_bucket=None,
destination_object=None,
move_object=False,
google_cloud_storage_conn_id='google_cloud_default',
delegate_to=None,
last_modified_time=None,
*args,
**kwargs):
super(GoogleCloudStorageToGoogleCloudStorageOperator,
self).__init__(*args, **kwargs)
self.source_bucket = source_bucket
self.source_object = source_object
self.destination_bucket = destination_bucket
self.destination_object = destination_object
self.move_object = move_object
self.google_cloud_storage_conn_id = google_cloud_storage_conn_id
self.delegate_to = delegate_to
self.last_modified_time = last_modified_time
def execute(self, context):
hook = GoogleCloudStorageHook(
google_cloud_storage_conn_id=self.google_cloud_storage_conn_id,
delegate_to=self.delegate_to
)
if self.destination_bucket is None:
self.log.warning(
'destination_bucket is None. Defaulting it to source_bucket (%s)',
self.source_bucket)
self.destination_bucket = self.source_bucket
if WILDCARD in self.source_object:
total_wildcards = self.source_object.count(WILDCARD)
if total_wildcards > 1:
error_msg = "Only one wildcard '*' is allowed in source_object parameter. " \
"Found {} in {}.".format(total_wildcards, self.source_object)
raise AirflowException(error_msg)
prefix, delimiter = self.source_object.split(WILDCARD, 1)
objects = hook.list(self.source_bucket, prefix=prefix, delimiter=delimiter)
for source_object in objects:
if self.destination_object is None:
destination_object = source_object
else:
destination_object = source_object.replace(prefix,
self.destination_object, 1)
self._copy_single_object(hook=hook, source_object=source_object,
destination_object=destination_object)
else:
self._copy_single_object(hook=hook, source_object=self.source_object,
destination_object=self.destination_object)
def _copy_single_object(self, hook, source_object, destination_object):
if self.last_modified_time is not None:
# Check to see if object was modified after last_modified_time
if hook.is_updated_after(self.source_bucket,
source_object,
self.last_modified_time):
self.log.debug("Object has been modified after %s ", self.last_modified_time)
pass
else:
return
self.log.info('Executing copy of gs://%s/%s to gs://%s/%s',
self.source_bucket, source_object,
self.destination_bucket, destination_object)
hook.rewrite(self.source_bucket, source_object,
self.destination_bucket, destination_object)
if self.move_object:
hook.delete(self.source_bucket, source_object)
| {
"content_hash": "393170f4d72efe27ce678f26f36c9901",
"timestamp": "",
"source": "github",
"line_count": 180,
"max_line_length": 93,
"avg_line_length": 45.81111111111111,
"alnum_prop": 0.6274557361144798,
"repo_name": "owlabs/incubator-airflow",
"id": "4516e6210043a78390c03123f532e51925866cbb",
"size": "9058",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "airflow/contrib/operators/gcs_to_gcs.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "57045"
},
{
"name": "HTML",
"bytes": "147187"
},
{
"name": "JavaScript",
"bytes": "1370838"
},
{
"name": "Mako",
"bytes": "1037"
},
{
"name": "Python",
"bytes": "1647566"
},
{
"name": "Shell",
"bytes": "18823"
}
],
"symlink_target": ""
} |
from __future__ import print_function, unicode_literals
from six.moves import zip
from past.builtins import basestring
import unicodecsv as csv
import itertools
import re
import subprocess
import time
from tempfile import NamedTemporaryFile
import hive_metastore
from airflow import configuration as conf
from airflow.exceptions import AirflowException
from airflow.hooks.base_hook import BaseHook
from airflow.utils.helpers import as_flattened_list
from airflow.utils.file import TemporaryDirectory
from airflow import configuration
import airflow.security.utils as utils
HIVE_QUEUE_PRIORITIES = ['VERY_HIGH', 'HIGH', 'NORMAL', 'LOW', 'VERY_LOW']
class HiveCliHook(BaseHook):
"""Simple wrapper around the hive CLI.
It also supports the ``beeline``
a lighter CLI that runs JDBC and is replacing the heavier
traditional CLI. To enable ``beeline``, set the use_beeline param in the
extra field of your connection as in ``{ "use_beeline": true }``
Note that you can also set default hive CLI parameters using the
``hive_cli_params`` to be used in your connection as in
``{"hive_cli_params": "-hiveconf mapred.job.tracker=some.jobtracker:444"}``
Parameters passed here can be overridden by run_cli's hive_conf param
The extra connection parameter ``auth`` gets passed as in the ``jdbc``
connection string as is.
:param mapred_queue: queue used by the Hadoop Scheduler (Capacity or Fair)
:type mapred_queue: string
:param mapred_queue_priority: priority within the job queue.
Possible settings include: VERY_HIGH, HIGH, NORMAL, LOW, VERY_LOW
:type mapred_queue_priority: string
:param mapred_job_name: This name will appear in the jobtracker.
This can make monitoring easier.
:type mapred_job_name: string
"""
def __init__(
self,
hive_cli_conn_id="hive_cli_default",
run_as=None,
mapred_queue=None,
mapred_queue_priority=None,
mapred_job_name=None):
conn = self.get_connection(hive_cli_conn_id)
self.hive_cli_params = conn.extra_dejson.get('hive_cli_params', '')
self.use_beeline = conn.extra_dejson.get('use_beeline', False)
self.auth = conn.extra_dejson.get('auth', 'noSasl')
self.conn = conn
self.run_as = run_as
if mapred_queue_priority:
mapred_queue_priority = mapred_queue_priority.upper()
if mapred_queue_priority not in HIVE_QUEUE_PRIORITIES:
raise AirflowException(
"Invalid Mapred Queue Priority. Valid values are: "
"{}".format(', '.join(HIVE_QUEUE_PRIORITIES)))
self.mapred_queue = mapred_queue or conf.get('hive',
'default_hive_mapred_queue')
self.mapred_queue_priority = mapred_queue_priority
self.mapred_job_name = mapred_job_name
def _prepare_cli_cmd(self):
"""
This function creates the command list from available information
"""
conn = self.conn
hive_bin = 'hive'
cmd_extra = []
if self.use_beeline:
hive_bin = 'beeline'
jdbc_url = "jdbc:hive2://{conn.host}:{conn.port}/{conn.schema}"
if configuration.conf.get('core', 'security') == 'kerberos':
template = conn.extra_dejson.get(
'principal', "hive/_HOST@EXAMPLE.COM")
if "_HOST" in template:
template = utils.replace_hostname_pattern(
utils.get_components(template))
proxy_user = "" # noqa
if conn.extra_dejson.get('proxy_user') == "login" and conn.login:
proxy_user = "hive.server2.proxy.user={0}".format(conn.login)
elif conn.extra_dejson.get('proxy_user') == "owner" and self.run_as:
proxy_user = "hive.server2.proxy.user={0}".format(self.run_as)
jdbc_url += ";principal={template};{proxy_user}"
elif self.auth:
jdbc_url += ";auth=" + self.auth
jdbc_url = jdbc_url.format(**locals())
cmd_extra += ['-u', jdbc_url]
if conn.login:
cmd_extra += ['-n', conn.login]
if conn.password:
cmd_extra += ['-p', conn.password]
hive_params_list = self.hive_cli_params.split()
return [hive_bin] + cmd_extra + hive_params_list
def _prepare_hiveconf(self, d):
"""
This function prepares a list of hiveconf params
from a dictionary of key value pairs.
:param d:
:type d: dict
>>> hh = HiveCliHook()
>>> hive_conf = {"hive.exec.dynamic.partition": "true",
... "hive.exec.dynamic.partition.mode": "nonstrict"}
>>> hh._prepare_hiveconf(hive_conf)
["-hiveconf", "hive.exec.dynamic.partition=true",\
"-hiveconf", "hive.exec.dynamic.partition.mode=nonstrict"]
"""
if not d:
return []
return as_flattened_list(
zip(["-hiveconf"] * len(d),
["{}={}".format(k, v) for k, v in d.items()])
)
def run_cli(self, hql, schema=None, verbose=True, hive_conf=None):
"""
Run an hql statement using the hive cli. If hive_conf is specified
it should be a dict and the entries will be set as key/value pairs
in HiveConf
:param hive_conf: if specified these key value pairs will be passed
to hive as ``-hiveconf "key"="value"``. Note that they will be
passed after the ``hive_cli_params`` and thus will override
whatever values are specified in the database.
:type hive_conf: dict
>>> hh = HiveCliHook()
>>> result = hh.run_cli("USE airflow;")
>>> ("OK" in result)
True
"""
conn = self.conn
schema = schema or conn.schema
if schema:
hql = "USE {schema};\n{hql}".format(**locals())
with TemporaryDirectory(prefix='airflow_hiveop_') as tmp_dir:
with NamedTemporaryFile(dir=tmp_dir) as f:
f.write(hql.encode('UTF-8'))
f.flush()
hive_cmd = self._prepare_cli_cmd()
hive_conf_params = self._prepare_hiveconf(hive_conf)
if self.mapred_queue:
hive_conf_params.extend(
['-hiveconf',
'mapreduce.job.queuename={}'
.format(self.mapred_queue),
'-hiveconf',
'mapred.job.queue.name={}'
.format(self.mapred_queue),
'-hiveconf',
'tez.job.queue.name={}'
.format(self.mapred_queue)
])
if self.mapred_queue_priority:
hive_conf_params.extend(
['-hiveconf',
'mapreduce.job.priority={}'
.format(self.mapred_queue_priority)])
if self.mapred_job_name:
hive_conf_params.extend(
['-hiveconf',
'mapred.job.name={}'
.format(self.mapred_job_name)])
hive_cmd.extend(hive_conf_params)
hive_cmd.extend(['-f', f.name])
if verbose:
self.log.info(" ".join(hive_cmd))
sp = subprocess.Popen(
hive_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
cwd=tmp_dir,
close_fds=True)
self.sp = sp
stdout = ''
while True:
line = sp.stdout.readline()
if not line:
break
stdout += line.decode('UTF-8')
if verbose:
self.log.info(line.decode('UTF-8').strip())
sp.wait()
if sp.returncode:
raise AirflowException(stdout)
return stdout
def test_hql(self, hql):
"""
Test an hql statement using the hive cli and EXPLAIN
"""
create, insert, other = [], [], []
for query in hql.split(';'): # naive
query_original = query
query = query.lower().strip()
if query.startswith('create table'):
create.append(query_original)
elif query.startswith(('set ',
'add jar ',
'create temporary function')):
other.append(query_original)
elif query.startswith('insert'):
insert.append(query_original)
other = ';'.join(other)
for query_set in [create, insert]:
for query in query_set:
query_preview = ' '.join(query.split())[:50]
self.log.info("Testing HQL [%s (...)]", query_preview)
if query_set == insert:
query = other + '; explain ' + query
else:
query = 'explain ' + query
try:
self.run_cli(query, verbose=False)
except AirflowException as e:
message = e.args[0].split('\n')[-2]
self.log.info(message)
error_loc = re.search('(\d+):(\d+)', message)
if error_loc and error_loc.group(1).isdigit():
l = int(error_loc.group(1))
begin = max(l-2, 0)
end = min(l+3, len(query.split('\n')))
context = '\n'.join(query.split('\n')[begin:end])
self.log.info("Context :\n %s", context)
else:
self.log.info("SUCCESS")
def load_df(
self,
df,
table,
create=True,
recreate=False,
field_dict=None,
delimiter=',',
encoding='utf8',
pandas_kwargs=None, **kwargs):
"""
Loads a pandas DataFrame into hive.
Hive data types will be inferred if not passed but column names will
not be sanitized.
:param table: target Hive table, use dot notation to target a
specific database
:type table: str
:param create: whether to create the table if it doesn't exist
:type create: bool
:param recreate: whether to drop and recreate the table at every
execution
:type recreate: bool
:param field_dict: mapping from column name to hive data type
:type field_dict: dict
:param encoding: string encoding to use when writing DataFrame to file
:type encoding: str
:param pandas_kwargs: passed to DataFrame.to_csv
:type pandas_kwargs: dict
:param kwargs: passed to self.load_file
"""
def _infer_field_types_from_df(df):
DTYPE_KIND_HIVE_TYPE = {
'b': 'BOOLEAN', # boolean
'i': 'BIGINT', # signed integer
'u': 'BIGINT', # unsigned integer
'f': 'DOUBLE', # floating-point
'c': 'STRING', # complex floating-point
'O': 'STRING', # object
'S': 'STRING', # (byte-)string
'U': 'STRING', # Unicode
'V': 'STRING' # void
}
return dict((col, DTYPE_KIND_HIVE_TYPE[dtype.kind]) for col, dtype in df.dtypes.iteritems())
if pandas_kwargs is None:
pandas_kwargs = {}
with TemporaryDirectory(prefix='airflow_hiveop_') as tmp_dir:
with NamedTemporaryFile(dir=tmp_dir) as f:
if field_dict is None and (create or recreate):
field_dict = _infer_field_types_from_df(df)
df.to_csv(f, sep=delimiter, **pandas_kwargs)
return self.load_file(filepath=f.name,
table=table,
delimiter=delimiter,
field_dict=field_dict,
**kwargs)
def load_file(
self,
filepath,
table,
delimiter=",",
field_dict=None,
create=True,
overwrite=True,
partition=None,
recreate=False,
tblproperties=None):
"""
Loads a local file into Hive
Note that the table generated in Hive uses ``STORED AS textfile``
which isn't the most efficient serialization format. If a
large amount of data is loaded and/or if the tables gets
queried considerably, you may want to use this operator only to
stage the data into a temporary table before loading it into its
final destination using a ``HiveOperator``.
:param filepath: local filepath of the file to load
:type filepath: str
:param table: target Hive table, use dot notation to target a
specific database
:type table: str
:param delimiter: field delimiter in the file
:type delimiter: str
:param field_dict: A dictionary of the fields name in the file
as keys and their Hive types as values
:type field_dict: dict
:param create: whether to create the table if it doesn't exist
:type create: bool
:param overwrite: whether to overwrite the data in table or partition
:type overwrite: bool
:param partition: target partition as a dict of partition columns
and values
:type partition: dict
:param recreate: whether to drop and recreate the table at every
execution
:type recreate: bool
:param tblproperties: TBLPROPERTIES of the hive table being created
:type tblproperties: dict
"""
hql = ''
if recreate:
hql += "DROP TABLE IF EXISTS {table};\n"
if create or recreate:
if field_dict is None:
raise ValueError("Must provide a field dict when creating a table")
fields = ",\n ".join(
[k + ' ' + v for k, v in field_dict.items()])
hql += "CREATE TABLE IF NOT EXISTS {table} (\n{fields})\n"
if partition:
pfields = ",\n ".join(
[p + " STRING" for p in partition])
hql += "PARTITIONED BY ({pfields})\n"
hql += "ROW FORMAT DELIMITED\n"
hql += "FIELDS TERMINATED BY '{delimiter}'\n"
hql += "STORED AS textfile\n"
if tblproperties is not None:
tprops = ", ".join(
["'{0}'='{1}'".format(k, v) for k, v in tblproperties.items()])
hql += "TBLPROPERTIES({tprops})\n"
hql += ";"
hql = hql.format(**locals())
self.log.info(hql)
self.run_cli(hql)
hql = "LOAD DATA LOCAL INPATH '{filepath}' "
if overwrite:
hql += "OVERWRITE "
hql += "INTO TABLE {table} "
if partition:
pvals = ", ".join(
["{0}='{1}'".format(k, v) for k, v in partition.items()])
hql += "PARTITION ({pvals});"
hql = hql.format(**locals())
self.log.info(hql)
self.run_cli(hql)
def kill(self):
if hasattr(self, 'sp'):
if self.sp.poll() is None:
print("Killing the Hive job")
self.sp.terminate()
time.sleep(60)
self.sp.kill()
class HiveMetastoreHook(BaseHook):
""" Wrapper to interact with the Hive Metastore"""
# java short max val
MAX_PART_COUNT = 32767
def __init__(self, metastore_conn_id='metastore_default'):
self.metastore_conn = self.get_connection(metastore_conn_id)
self.metastore = self.get_metastore_client()
def __getstate__(self):
# This is for pickling to work despite the thirft hive client not
# being pickable
d = dict(self.__dict__)
del d['metastore']
return d
def __setstate__(self, d):
self.__dict__.update(d)
self.__dict__['metastore'] = self.get_metastore_client()
def get_metastore_client(self):
"""
Returns a Hive thrift client.
"""
from thrift.transport import TSocket, TTransport
from thrift.protocol import TBinaryProtocol
from hive_service import ThriftHive
ms = self.metastore_conn
auth_mechanism = ms.extra_dejson.get('authMechanism', 'NOSASL')
if configuration.conf.get('core', 'security') == 'kerberos':
auth_mechanism = ms.extra_dejson.get('authMechanism', 'GSSAPI')
kerberos_service_name = ms.extra_dejson.get('kerberos_service_name', 'hive')
socket = TSocket.TSocket(ms.host, ms.port)
if configuration.conf.get('core', 'security') == 'kerberos' \
and auth_mechanism == 'GSSAPI':
try:
import saslwrapper as sasl
except ImportError:
import sasl
def sasl_factory():
sasl_client = sasl.Client()
sasl_client.setAttr("host", ms.host)
sasl_client.setAttr("service", kerberos_service_name)
sasl_client.init()
return sasl_client
from thrift_sasl import TSaslClientTransport
transport = TSaslClientTransport(sasl_factory, "GSSAPI", socket)
else:
transport = TTransport.TBufferedTransport(socket)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
return ThriftHive.Client(protocol)
def get_conn(self):
return self.metastore
def check_for_partition(self, schema, table, partition):
"""
Checks whether a partition exists
:param schema: Name of hive schema (database) @table belongs to
:type schema: string
:param table: Name of hive table @partition belongs to
:type schema: string
:partition: Expression that matches the partitions to check for
(eg `a = 'b' AND c = 'd'`)
:type schema: string
:rtype: boolean
>>> hh = HiveMetastoreHook()
>>> t = 'static_babynames_partitioned'
>>> hh.check_for_partition('airflow', t, "ds='2015-01-01'")
True
"""
self.metastore._oprot.trans.open()
partitions = self.metastore.get_partitions_by_filter(
schema, table, partition, 1)
self.metastore._oprot.trans.close()
if partitions:
return True
else:
return False
def check_for_named_partition(self, schema, table, partition_name):
"""
Checks whether a partition with a given name exists
:param schema: Name of hive schema (database) @table belongs to
:type schema: string
:param table: Name of hive table @partition belongs to
:type schema: string
:partition: Name of the partitions to check for (eg `a=b/c=d`)
:type schema: string
:rtype: boolean
>>> hh = HiveMetastoreHook()
>>> t = 'static_babynames_partitioned'
>>> hh.check_for_named_partition('airflow', t, "ds=2015-01-01")
True
>>> hh.check_for_named_partition('airflow', t, "ds=xxx")
False
"""
self.metastore._oprot.trans.open()
try:
self.metastore.get_partition_by_name(
schema, table, partition_name)
return True
except hive_metastore.ttypes.NoSuchObjectException:
return False
finally:
self.metastore._oprot.trans.close()
def get_table(self, table_name, db='default'):
"""Get a metastore table object
>>> hh = HiveMetastoreHook()
>>> t = hh.get_table(db='airflow', table_name='static_babynames')
>>> t.tableName
'static_babynames'
>>> [col.name for col in t.sd.cols]
['state', 'year', 'name', 'gender', 'num']
"""
self.metastore._oprot.trans.open()
if db == 'default' and '.' in table_name:
db, table_name = table_name.split('.')[:2]
table = self.metastore.get_table(dbname=db, tbl_name=table_name)
self.metastore._oprot.trans.close()
return table
def get_tables(self, db, pattern='*'):
"""
Get a metastore table object
"""
self.metastore._oprot.trans.open()
tables = self.metastore.get_tables(db_name=db, pattern=pattern)
objs = self.metastore.get_table_objects_by_name(db, tables)
self.metastore._oprot.trans.close()
return objs
def get_databases(self, pattern='*'):
"""
Get a metastore table object
"""
self.metastore._oprot.trans.open()
dbs = self.metastore.get_databases(pattern)
self.metastore._oprot.trans.close()
return dbs
def get_partitions(
self, schema, table_name, filter=None):
"""
Returns a list of all partitions in a table. Works only
for tables with less than 32767 (java short max val).
For subpartitioned table, the number might easily exceed this.
>>> hh = HiveMetastoreHook()
>>> t = 'static_babynames_partitioned'
>>> parts = hh.get_partitions(schema='airflow', table_name=t)
>>> len(parts)
1
>>> parts
[{'ds': '2015-01-01'}]
"""
self.metastore._oprot.trans.open()
table = self.metastore.get_table(dbname=schema, tbl_name=table_name)
if len(table.partitionKeys) == 0:
raise AirflowException("The table isn't partitioned")
else:
if filter:
parts = self.metastore.get_partitions_by_filter(
db_name=schema, tbl_name=table_name,
filter=filter, max_parts=HiveMetastoreHook.MAX_PART_COUNT)
else:
parts = self.metastore.get_partitions(
db_name=schema, tbl_name=table_name,
max_parts=HiveMetastoreHook.MAX_PART_COUNT)
self.metastore._oprot.trans.close()
pnames = [p.name for p in table.partitionKeys]
return [dict(zip(pnames, p.values)) for p in parts]
@staticmethod
def _get_max_partition_from_part_specs(part_specs, partition_key, filter_map):
"""
Helper method to get max partition of partitions with partition_key
from part specs. key:value pair in filter_map will be used to
filter out partitions.
:param part_specs: list of partition specs.
:type part_specs: list
:param partition_key: partition key name.
:type partition_key: string
:param filter_map: partition_key:partition_value map used for partition filtering,
e.g. {'key1': 'value1', 'key2': 'value2'}.
Only partitions matching all partition_key:partition_value
pairs will be considered as candidates of max partition.
:type filter_map: map
:return: Max partition or None if part_specs is empty.
"""
if not part_specs:
return None
# Assuming all specs have the same keys.
if partition_key not in part_specs[0].keys():
raise AirflowException("Provided partition_key {} "
"is not in part_specs.".format(partition_key))
if filter_map and not set(filter_map.keys()) < set(part_specs[0].keys()):
raise AirflowException("Keys in provided filter_map {} "
"are not subset of part_spec keys: {}"
.format(', '.join(filter_map.keys()),
', '.join(part_specs[0].keys())))
candidates = [p_dict[partition_key] for p_dict in part_specs
if filter_map is None or
all(item in p_dict.items() for item in filter_map.items())]
if not candidates:
return None
else:
return max(candidates).encode('utf-8')
def max_partition(self, schema, table_name, field=None, filter_map=None):
"""
Returns the maximum value for all partitions with given field in a table.
If only one partition key exist in the table, the key will be used as field.
filter_map should be a partition_key:partition_value map and will be used to
filter out partitions.
:param schema: schema name.
:type schema: string
:param table_name: table name.
:type table_name: string
:param field: partition key to get max partition from.
:type field: string
:param filter_map: partition_key:partition_value map used for partition filtering.
:type filter_map: map
>>> hh = HiveMetastoreHook()
>> filter_map = {'p_key': 'p_val'}
>>> t = 'static_babynames_partitioned'
>>> hh.max_partition(schema='airflow',\
... table_name=t, field='ds', filter_map=filter_map)
'2015-01-01'
"""
self.metastore._oprot.trans.open()
table = self.metastore.get_table(dbname=schema, tbl_name=table_name)
key_name_set = set(key.name for key in table.partitionKeys)
if len(table.partitionKeys) == 1:
field = table.partitionKeys[0].name
elif not field:
raise AirflowException("Please specify the field you want the max "
"value for.")
elif field not in key_name_set:
raise AirflowException("Provided field is not a partition key.")
if filter_map and not set(filter_map.keys()).issubset(key_name_set):
raise AirflowException("Provided filter_map contains keys "
"that are not partition key.")
part_names = \
self.metastore.get_partition_names(schema,
table_name,
max_parts=HiveMetastoreHook.MAX_PART_COUNT)
part_specs = [self.metastore.partition_name_to_spec(part_name)
for part_name in part_names]
self.metastore._oprot.trans.close()
return HiveMetastoreHook._get_max_partition_from_part_specs(part_specs,
field,
filter_map)
def table_exists(self, table_name, db='default'):
"""
Check if table exists
>>> hh = HiveMetastoreHook()
>>> hh.table_exists(db='airflow', table_name='static_babynames')
True
>>> hh.table_exists(db='airflow', table_name='does_not_exist')
False
"""
try:
t = self.get_table(table_name, db)
return True
except Exception as e:
return False
class HiveServer2Hook(BaseHook):
"""
Wrapper around the impyla library
Note that the default authMechanism is PLAIN, to override it you
can specify it in the ``extra`` of your connection in the UI as in
"""
def __init__(self, hiveserver2_conn_id='hiveserver2_default'):
self.hiveserver2_conn_id = hiveserver2_conn_id
def get_conn(self, schema=None):
db = self.get_connection(self.hiveserver2_conn_id)
auth_mechanism = db.extra_dejson.get('authMechanism', 'PLAIN')
kerberos_service_name = None
if configuration.conf.get('core', 'security') == 'kerberos':
auth_mechanism = db.extra_dejson.get('authMechanism', 'GSSAPI')
kerberos_service_name = db.extra_dejson.get('kerberos_service_name', 'hive')
# impyla uses GSSAPI instead of KERBEROS as a auth_mechanism identifier
if auth_mechanism == 'KERBEROS':
self.log.warning(
"Detected deprecated 'KERBEROS' for authMechanism for %s. Please use 'GSSAPI' instead",
self.hiveserver2_conn_id
)
auth_mechanism = 'GSSAPI'
from impala.dbapi import connect
return connect(
host=db.host,
port=db.port,
auth_mechanism=auth_mechanism,
kerberos_service_name=kerberos_service_name,
user=db.login,
database=schema or db.schema or 'default')
def get_results(self, hql, schema='default', arraysize=1000):
from impala.error import ProgrammingError
with self.get_conn(schema) as conn:
if isinstance(hql, basestring):
hql = [hql]
results = {
'data': [],
'header': [],
}
cur = conn.cursor()
for statement in hql:
cur.execute(statement)
records = []
try:
# impala Lib raises when no results are returned
# we're silencing here as some statements in the list
# may be `SET` or DDL
records = cur.fetchall()
except ProgrammingError:
self.log.debug("get_results returned no records")
if records:
results = {
'data': records,
'header': cur.description,
}
return results
def to_csv(
self,
hql,
csv_filepath,
schema='default',
delimiter=',',
lineterminator='\r\n',
output_header=True,
fetch_size=1000):
schema = schema or 'default'
with self.get_conn(schema) as conn:
with conn.cursor() as cur:
self.log.info("Running query: %s", hql)
cur.execute(hql)
schema = cur.description
with open(csv_filepath, 'wb') as f:
writer = csv.writer(f,
delimiter=delimiter,
lineterminator=lineterminator,
encoding='utf-8')
if output_header:
writer.writerow([c[0] for c in cur.description])
i = 0
while True:
rows = [row for row in cur.fetchmany(fetch_size) if row]
if not rows:
break
writer.writerows(rows)
i += len(rows)
self.log.info("Written %s rows so far.", i)
self.log.info("Done. Loaded a total of %s rows.", i)
def get_records(self, hql, schema='default'):
"""
Get a set of records from a Hive query.
>>> hh = HiveServer2Hook()
>>> sql = "SELECT * FROM airflow.static_babynames LIMIT 100"
>>> len(hh.get_records(sql))
100
"""
return self.get_results(hql, schema=schema)['data']
def get_pandas_df(self, hql, schema='default'):
"""
Get a pandas dataframe from a Hive query
>>> hh = HiveServer2Hook()
>>> sql = "SELECT * FROM airflow.static_babynames LIMIT 100"
>>> df = hh.get_pandas_df(sql)
>>> len(df.index)
100
"""
import pandas as pd
res = self.get_results(hql, schema=schema)
df = pd.DataFrame(res['data'])
df.columns = [c[0] for c in res['header']]
return df
| {
"content_hash": "91bd188a7212ec60a1dfd1c219c4ea45",
"timestamp": "",
"source": "github",
"line_count": 830,
"max_line_length": 104,
"avg_line_length": 38.665060240963854,
"alnum_prop": 0.535554032157547,
"repo_name": "Tagar/incubator-airflow",
"id": "d278483afcbcbdd6cef5919372e1134f1c98cada",
"size": "32908",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "airflow/hooks/hive_hooks.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "109698"
},
{
"name": "HTML",
"bytes": "270515"
},
{
"name": "JavaScript",
"bytes": "1988427"
},
{
"name": "Mako",
"bytes": "1284"
},
{
"name": "Python",
"bytes": "3580255"
},
{
"name": "Shell",
"bytes": "36912"
}
],
"symlink_target": ""
} |
"""Definitions for the `AllTimes` class."""
from collections import OrderedDict
import numpy as np
from mosfit.modules.arrays.array import Array
from mosfit.utils import frequency_unit
# Important: Only define one ``Module`` class per file.
class AllTimes(Array):
"""Generate all times for which observations will be constructed.
Create lists of observation times that associated with real observations
and interpolations/extrapolations if such flags are passed to MOSFiT.
"""
def __init__(self, **kwargs):
"""Initialize module."""
super(AllTimes, self).__init__(**kwargs)
self._obs_keys = [
'times', 'bands', 'telescopes', 'systems', 'instruments', 'modes',
'bandsets', 'frequencies', 'u_frequencies', 'zeropoints',
'measures', 'observed'
]
self._okeys = [i for i in self._obs_keys if i not in ['observed']]
for key in self._obs_keys:
setattr(self, '_' + key, [])
def process(self, **kwargs):
"""Process module."""
old_observations = tuple(
getattr(self, '_' + x) for x in self._obs_keys)
if (kwargs.get('root', 'output') == 'output'
and 'extra_times' in kwargs):
obslist = (
list(
zip(*([kwargs.get(k) for k in self._okeys] +
[[True for x in range(len(kwargs['times']))]]))) +
list(
zip(*([kwargs.get('extra_' + k) for k in self._okeys] +
[[False
for x in range(len(kwargs['extra_times']))]]))))
obslist.sort()
self._all_observations = np.concatenate(
[np.atleast_2d(np.array(x, dtype=object)) for x in obslist],
axis=0).T
for ki, key in enumerate(self._obs_keys):
setattr(self, '_' + key, self._all_observations[ki])
else:
for key in list(
set(self._obs_keys) - set(['frequencies', 'observed'])):
setattr(self, '_' + key, kwargs[key])
self._frequencies = np.array([
x / frequency_unit(y) if x is not None else None
for x, y in zip(kwargs['frequencies'], kwargs['u_frequencies'])
])
self._observed = np.full_like(kwargs['times'], True, dtype=bool)
self._all_observations = tuple(
getattr(self, '_' + x) for x in self._obs_keys)
outputs = OrderedDict(
[('all_' + x, getattr(self, '_' + x))
for x in list(set(self._obs_keys) - set(['observed']))])
if any(not np.array_equal(x, y)
for x, y in zip(old_observations, self._all_observations)):
self._all_band_indices = np.array(
[(self._photometry.find_band_index(
b, telescope=t, instrument=i, mode=m, bandset=bs, system=s)
if f is None else -1) for ti, b, t, s, i, m, bs, f, uf, zps,
msr, o in zip(*self._all_observations)])
self._zps = np.array(
[x[9] for x in zip(*self._all_observations)])
self._measures = np.array(
[x[10] for x in zip(*self._all_observations)])
self._observation_types = np.array([
'magcount' if
('countrate' in msr and 'magnitude' in msr and zp is not None
and self._model._fitter._prefer_fluxes) else
self._photometry._band_kinds[bi] if bi >= 0 else 'fluxdensity'
for bi, zp, msr in zip(self._all_band_indices,
self._zps, self._measures)
],
dtype=object)
outputs['all_band_indices'] = self._all_band_indices
outputs['observation_types'] = self._observation_types
outputs['observed'] = np.array(self._observed, dtype=bool)
return outputs
def receive_requests(self, **requests):
"""Receive requests from other ``Module`` objects."""
self._photometry = requests.get('photometry', None)
| {
"content_hash": "a4c26e982c5d3e7e1eb29584c04edf21",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 79,
"avg_line_length": 44.89247311827957,
"alnum_prop": 0.5233532934131736,
"repo_name": "bmockler/MOSFiT",
"id": "4276238172bec6aee80c22e8d19e67fac5374f59",
"size": "4175",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "mosfit/modules/arrays/alltimes.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "15866"
},
{
"name": "Python",
"bytes": "505142"
},
{
"name": "Shell",
"bytes": "2421"
}
],
"symlink_target": ""
} |
import sys
import os
sys.path.append(sys.path[0]+'/..') # Set the path so we can find procgame. We are assuming (stupidly?) that the first member is our directory.
import pinproc
from procgame import *
from threading import Thread
import random
import string
import time
import locale
import math
import copy
locale.setlocale(locale.LC_ALL, "") # Used to put commas in the score.
config_path = "JD.yaml"
class ScoreTester(game.Mode):
left_players_justify_left = True
def sw_flipperLwL_active(self, sw):
self.game.score(random.randint(0, 100000)*10)
return True
def sw_flipperLwR_active(self, sw):
self.game.end_ball()
return True
def sw_fireL_active(self, sw):
self.left_players_justify_left = not self.left_players_justify_left
if self.left_players_justify_left:
self.game.score_display.set_left_players_justify("left")
else:
self.game.score_display.set_left_players_justify("right")
return True
class TestGame(game.BasicGame):
"""docstring for TestGame"""
def setup(self):
"""docstring for setup"""
self.load_config(config_path)
self.reset()
self.start_game()
for i in range(4):
self.add_player()
self.players[i].score = random.randint(0, 1e5)*10
self.current_player_index = 0#random.randint(0, 3)
self.start_ball()
def reset(self):
super(TestGame, self).reset()
self.modes.add(ScoreTester(self, 5))
# Make sure flippers are off, especially for user-initiated resets.
self.enable_flippers(enable=False)
def main():
game = None
try:
game = TestGame(pinproc.MachineTypeWPC)
game.setup()
game.run_loop()
finally:
del game
if __name__ == '__main__': main()
| {
"content_hash": "95354fe6039c528202f8a8d3dffd5120",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 143,
"avg_line_length": 24.567164179104477,
"alnum_prop": 0.7108140947752126,
"repo_name": "mjocean/PyProcGameHD-SkeletonGame",
"id": "7fa43c63d6405e6d6fb9d15b9dc7aab2c7026665",
"size": "1646",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tools/scoredisplaytest.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "915538"
}
],
"symlink_target": ""
} |
import _plotly_utils.basevalidators
class HovermodeValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="hovermode", parent_name="layout.scene", **kwargs):
super(HovermodeValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "modebar"),
values=kwargs.pop("values", ["closest", False]),
**kwargs,
)
| {
"content_hash": "720f352b85d2d5311187fb1bde52fd06",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 86,
"avg_line_length": 39.666666666666664,
"alnum_prop": 0.6239495798319328,
"repo_name": "plotly/plotly.py",
"id": "89f547c020c929b5436baad5d45b2b27d4e5d8f3",
"size": "476",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/python/plotly/plotly/validators/layout/scene/_hovermode.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "545"
},
{
"name": "JavaScript",
"bytes": "2074"
},
{
"name": "PostScript",
"bytes": "565328"
},
{
"name": "Python",
"bytes": "31506317"
},
{
"name": "TypeScript",
"bytes": "71337"
}
],
"symlink_target": ""
} |
"""Support for Ankuoo RecSwitch MS6126 devices."""
import logging
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice
from homeassistant.const import CONF_HOST, CONF_MAC, CONF_NAME
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = 'RecSwitch {0}'
DATA_RSN = 'RSN'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_MAC): vol.All(cv.string, vol.Upper),
vol.Optional(CONF_NAME): cv.string,
})
async def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
"""Set up the device."""
from pyrecswitch import RSNetwork
host = config[CONF_HOST]
mac_address = config[CONF_MAC]
device_name = config.get(CONF_NAME)
if not hass.data.get(DATA_RSN):
hass.data[DATA_RSN] = RSNetwork()
job = hass.data[DATA_RSN].create_datagram_endpoint(loop=hass.loop)
hass.async_create_task(job)
device = hass.data[DATA_RSN].register_device(mac_address, host)
async_add_entities([RecSwitchSwitch(device, device_name, mac_address)])
class RecSwitchSwitch(SwitchDevice):
"""Representation of a recswitch device."""
def __init__(self, device, device_name, mac_address):
"""Initialize a recswitch device."""
self.gpio_state = False
self.device = device
self.device_name = device_name
self.mac_address = mac_address
if not self.device_name:
self.device_name = DEFAULT_NAME.format(self.mac_address)
@property
def unique_id(self):
"""Return the switch unique ID."""
return self.mac_address
@property
def name(self):
"""Return the switch name."""
return self.device_name
@property
def is_on(self):
"""Return true if switch is on."""
return self.gpio_state
async def async_turn_on(self, **kwargs):
"""Turn on the switch."""
await self.async_set_gpio_status(True)
async def async_turn_off(self, **kwargs):
"""Turn off the switch."""
await self.async_set_gpio_status(False)
async def async_set_gpio_status(self, status):
"""Set the switch status."""
from pyrecswitch import RSNetworkError
try:
ret = await self.device.set_gpio_status(status)
self.gpio_state = ret.state
except RSNetworkError as error:
_LOGGER.error('Setting status to %s: %r', self.name, error)
async def async_update(self):
"""Update the current switch status."""
from pyrecswitch import RSNetworkError
try:
ret = await self.device.get_gpio_status()
self.gpio_state = ret.state
except RSNetworkError as error:
_LOGGER.error('Reading status from %s: %r', self.name, error)
| {
"content_hash": "ff82d630814b847891a042416d7135b3",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 75,
"avg_line_length": 31.04255319148936,
"alnum_prop": 0.6394790952707334,
"repo_name": "molobrakos/home-assistant",
"id": "c43064c56749a3321dc68d470f92472a50061895",
"size": "2918",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "homeassistant/components/recswitch/switch.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1175"
},
{
"name": "Dockerfile",
"bytes": "1081"
},
{
"name": "HCL",
"bytes": "407"
},
{
"name": "Python",
"bytes": "15057917"
},
{
"name": "Ruby",
"bytes": "745"
},
{
"name": "Shell",
"bytes": "17609"
}
],
"symlink_target": ""
} |
import pytest
import json
from indy_node.test.validator_info.helper import sdk_get_validator_info
from plenum.common.exceptions import RequestRejectedException
from indy_common.constants import VALIDATOR_INFO
from plenum.common.constants import REPLY, TXN_TYPE, DATA
from plenum.common.types import f
from plenum.test.helper import sdk_gen_request, sdk_sign_and_submit_req_obj, \
sdk_get_reply, sdk_send_signed_requests, sdk_get_and_check_replies
def test_validator_info_command(
sdk_pool_handle, sdk_wallet_trustee, looper):
req, resp = sdk_get_validator_info(looper,
sdk_wallet_trustee,
sdk_pool_handle)
_comparison_reply(resp, req)
def test_fail_validator_info_command(
sdk_pool_handle, sdk_wallet_client, looper):
with pytest.raises(RequestRejectedException) as excinfo:
sdk_get_validator_info(looper,
sdk_wallet_client,
sdk_pool_handle)
assert excinfo.match("None role cannot do action with type = " +
VALIDATOR_INFO)
def _comparison_reply(responses, req_obj):
for json_resp in responses.values():
resp = json.loads(json_resp)
assert resp["op"] == REPLY
assert resp[f.RESULT.nm][f.IDENTIFIER.nm] == req_obj[f.IDENTIFIER.nm]
assert resp[f.RESULT.nm][f.REQ_ID.nm] == req_obj[f.REQ_ID.nm]
assert resp[f.RESULT.nm][TXN_TYPE] == VALIDATOR_INFO
assert resp[f.RESULT.nm][DATA] is not None
| {
"content_hash": "45dd49383d9faeb9d14d26aadcbf7a38",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 78,
"avg_line_length": 37.65853658536585,
"alnum_prop": 0.6502590673575129,
"repo_name": "spivachuk/sovrin-node",
"id": "5c79dda9ad8c2d47adaba15d14eff709d5fdb69c",
"size": "1544",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "indy_node/test/validator_info/test_validator_info_command.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3329"
},
{
"name": "Dockerfile",
"bytes": "7269"
},
{
"name": "Groovy",
"bytes": "8984"
},
{
"name": "Makefile",
"bytes": "11151"
},
{
"name": "Python",
"bytes": "1681637"
},
{
"name": "Ruby",
"bytes": "65393"
},
{
"name": "Rust",
"bytes": "25532"
},
{
"name": "Shell",
"bytes": "132633"
}
],
"symlink_target": ""
} |
from frappe.tests.utils import FrappeTestCase
class TestDropboxSettings(FrappeTestCase):
pass
| {
"content_hash": "0a181190271f304a7e97a15f41a71e6f",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 45,
"avg_line_length": 19.4,
"alnum_prop": 0.845360824742268,
"repo_name": "StrellaGroup/frappe",
"id": "1c95b130e856d4f532088ed82576f830a521e2c5",
"size": "200",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "frappe/integrations/doctype/dropbox_settings/test_dropbox_settings.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "65093"
},
{
"name": "HTML",
"bytes": "250858"
},
{
"name": "JavaScript",
"bytes": "2515308"
},
{
"name": "Less",
"bytes": "10921"
},
{
"name": "Python",
"bytes": "3605011"
},
{
"name": "SCSS",
"bytes": "261492"
},
{
"name": "Vue",
"bytes": "98456"
}
],
"symlink_target": ""
} |
from cx_Freeze import setup, Executable
import os
from os.path import dirname, join
import subprocess
import sys
from app.util import autoversioning
from app.util.process_utils import is_windows
buildOptions = {
'excludes': [],
'append_script_to_exe': False,
'build_exe': 'dist',
'compressed': True,
'copy_dependent_files': True,
'create_shared_zip': True,
'include_in_shared_zip': True,
'include_files': [
('bin/git_askpass.sh', 'bin/git_askpass.sh'),
('bin/git_ssh.sh', 'bin/git_ssh.sh'),
('conf/default_clusterrunner.conf', 'conf/default_clusterrunner.conf'),
],
'optimize': 1, # This should not be set to 2 because that removes docstrings needed for command line help.
}
base = 'Console'
executable_name = 'clusterrunner.exe' if is_windows() else 'clusterrunner'
executables = [
Executable('main.py', base=base, targetName=executable_name)
]
if sys.platform.startswith('linux'):
# Fixes compatibility between rhel and ubuntu
bin_includes = ['/usr/lib64/libssl.so.10', '/usr/lib64/libcrypto.so.10']
file_exists = [os.path.isfile(filename) for filename in bin_includes]
if all(file_exists):
buildOptions['bin_includes'] = bin_includes
version = autoversioning.get_version()
autoversioning.write_package_version_file(version)
setup(name='ClusterRunner',
version=version,
description='',
options=dict(build_exe=buildOptions),
executables=executables)
autoversioning.restore_original_package_version_file()
if sys.platform == 'darwin':
# Fix a cx_freeze issue on mac.
# (See similar fix at https://bitbucket.org/iep-project/iep/commits/1e845c0f35)
abs_python_path = None
clusterrunner_path = join(dirname(__file__), 'dist', executable_name)
# Get the Python reference in clusterrunner
otool_proc = subprocess.Popen(('otool', '-L', clusterrunner_path), stdout=subprocess.PIPE)
clusterrunner_libs = otool_proc.stdout.readlines()
for lib in clusterrunner_libs[1:]:
lib = lib.decode().strip()
lib_filename, _ = lib.split(maxsplit=1)
if lib_filename.endswith('/Python'):
abs_python_path = lib_filename
# Replace the absolute path reference in clusterrunner with a relative path
if abs_python_path:
rel_python_path = '@executable_path/Python'
print('Replacing reference: "{}" -> "{}"'.format(abs_python_path, rel_python_path))
subproc_args = ['install_name_tool', '-change', abs_python_path, rel_python_path, clusterrunner_path]
subprocess.Popen(subproc_args)
| {
"content_hash": "d4658751b8482281c3c82ef2e6b67aed",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 111,
"avg_line_length": 35.49315068493151,
"alnum_prop": 0.6819760710150521,
"repo_name": "Medium/ClusterRunner",
"id": "5992553f11f6b0e6c5f3f2f19be8b2dbe0950a42",
"size": "2591",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "66"
},
{
"name": "Makefile",
"bytes": "1860"
},
{
"name": "PowerShell",
"bytes": "1467"
},
{
"name": "Python",
"bytes": "678935"
},
{
"name": "Shell",
"bytes": "545"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('projects', '0006_auto_20170921_2218'),
]
operations = [
migrations.AlterIndexTogether(
name='projectcollaborator',
index_together=set([('user', 'project')]),
),
]
| {
"content_hash": "0f094f89db35d71ff00163f87898c291",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 66,
"avg_line_length": 24.36842105263158,
"alnum_prop": 0.6436285097192225,
"repo_name": "srtab/alexandria-docs",
"id": "adc264223ebe2dcb0f266b0857a8226f9cc685d7",
"size": "536",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "alexandriadocs/projects/migrations/0007_auto_20170921_2233.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3663"
},
{
"name": "HTML",
"bytes": "11362"
},
{
"name": "Python",
"bytes": "45048"
},
{
"name": "Shell",
"bytes": "145"
}
],
"symlink_target": ""
} |
import requests
from bs4 import BeautifulSoup
import sys
import csv
# Scraping URL for the Names of the top numTeams NCAA Team Names
def teamsNameScraper(URL):
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')
dat = []
rows = soup.find_all("tr", {"class": ["odd", "even"]})
track = 1
count = 0
for row in rows:
for entry in row.findAll("td"):
entry = entry.get_text()
if(track == 3):
dat.append([entry])
count = count + 1
if(track < 9):
track = track + 1
else:
track = 1
return dat
# Scraping URL for the Stats of the given teams
def teamsStatScraper(site, nameFlag):
firstTeam = True
dat = {}
for page in range(1, 8):
if(firstTeam and page == 1):
headerFlag = True
else:
headerFlag = False
firstTeam = False
URL = "http://www.ncaa.com/stats/basketball-men/d1/current/team/" + str(site) + "/p" + str(page)
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')
if(headerFlag):
header = soup.find_all("th")
entries = []
for entry in header:
entries.append(str(entry.get_text()))
if(nameFlag):
temp = str(entries[1])
temp = [temp, str(entries[-1])]
else:
temp = [str(entries[-1])]
dat['header'] = temp
rows = soup.find_all("tr", {"class": ["odd", "even"]})
for row in rows:
entries = []
for entry in row.findAll("td"):
entries.append(str(entry.get_text()))
name = str(entries[1])
dat[name] = [entries[-1]]
return dat
# Writing Data to a CSV
def CSV_datWriter(result, fileName):
with open(fileName,'wb') as resultFile:
writer = csv.writer(resultFile, delimiter = ',')
for line in result:
if('N' not in line):
writer.writerow(line) | {
"content_hash": "8add68918689fab37efc43f640a28c73",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 104,
"avg_line_length": 26.72151898734177,
"alnum_prop": 0.5153955471340597,
"repo_name": "parekhmitchell/NCAA-ML",
"id": "7eab7db2badd2f73a7bcbdbbdb79ad8aa7ba3cd9",
"size": "2172",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/NCAAScraper.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "6273"
}
],
"symlink_target": ""
} |
import time
import wpan
from wpan import verify
#-----------------------------------------------------------------------------------------------------------------------
# Test description: verifies `ChannelManager` channel change process
test_name = __file__[:-3] if __file__.endswith('.py') else __file__
print '-' * 120
print 'Starting \'{}\''.format(test_name)
def verify_channel(nodes, new_channel, wait_time=20):
"""
This function checks the channel on a given list of `nodes` and verifies that all nodes
switch to a given `new_channel` (as int) within certain `wait_time` (int and in seconds)
"""
start_time = time.time()
while not all([ (new_channel == int(node.get(wpan.WPAN_CHANNEL), 0)) for node in nodes ]):
if time.time() - start_time > wait_time:
print 'Took too long to switch to channel {} ({}>{} sec)'.format(new_channel, time.time() - start_time,
wait_time)
exit(1)
time.sleep(0.1)
#-----------------------------------------------------------------------------------------------------------------------
# Creating `wpan.Nodes` instances
speedup = 4
wpan.Node.set_time_speedup_factor(speedup)
r1 = wpan.Node()
r2 = wpan.Node()
r3 = wpan.Node()
sc1 = wpan.Node()
ec1 = wpan.Node()
sc2 = wpan.Node()
sc3 = wpan.Node()
all_nodes = [r1, r2, r3, sc1, ec1, sc2, sc3]
#-----------------------------------------------------------------------------------------------------------------------
# Init all nodes
wpan.Node.init_all_nodes()
#-----------------------------------------------------------------------------------------------------------------------
# Build network topology
for node in all_nodes:
node.set(wpan.WPAN_OT_LOG_LEVEL, '0')
r1.whitelist_node(r2)
r2.whitelist_node(r1)
r1.whitelist_node(r3)
r3.whitelist_node(r1)
r1.whitelist_node(sc1)
r1.whitelist_node(ec1)
r2.whitelist_node(sc2)
r3.whitelist_node(sc3)
r1.form('channel-manager', channel=12)
r2.join_node(r1, node_type=wpan.JOIN_TYPE_ROUTER)
r3.join_node(r1, node_type=wpan.JOIN_TYPE_ROUTER)
sc1.join_node(r1, node_type=wpan.JOIN_TYPE_SLEEPY_END_DEVICE)
ec1.join_node(r1, node_type=wpan.JOIN_TYPE_END_DEVICE)
sc2.join_node(r2, node_type=wpan.JOIN_TYPE_SLEEPY_END_DEVICE)
sc3.join_node(r3, node_type=wpan.JOIN_TYPE_SLEEPY_END_DEVICE)
sc1.set(wpan.WPAN_POLL_INTERVAL, '500')
sc2.set(wpan.WPAN_POLL_INTERVAL, '500')
sc3.set(wpan.WPAN_POLL_INTERVAL, '500')
#-----------------------------------------------------------------------------------------------------------------------
# Test implementation
# The channel manager delay is set from "openthread-core-toranj-config.h". Verify that it is 2 seconds.
verify(int(r1.get(wpan.WPAN_CHANNEL_MANAGER_DELAY), 0) == 2)
verify_channel(all_nodes, 12)
# Request a channel change to channel 13 from router r1
r1.set(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL, '13')
verify(int(r1.get(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL), 0) == 13)
verify_channel(all_nodes, 13)
# Request same channel change on multiple routers at the same time
r1.set(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL, '14')
r2.set(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL, '14')
r3.set(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL, '14')
verify_channel(all_nodes, 14)
# Request different channel changes from same router (router r1).
r1.set(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL, '15')
verify_channel(all_nodes, 14)
r1.set(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL, '16')
verify_channel(all_nodes, 16)
# Request different channels from two routers (r1 and r2)
r1.set(wpan.WPAN_CHANNEL_MANAGER_DELAY, '20') # increase the time to ensure r1 change is in process
r1.set(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL, '17')
time.sleep(10.5 / speedup)
verify_channel(all_nodes, 16)
r2.set(wpan.WPAN_CHANNEL_MANAGER_NEW_CHANNEL, '18')
verify_channel(all_nodes, 18)
#-----------------------------------------------------------------------------------------------------------------------
# Test finished
wpan.Node.finalize_all_nodes()
print '\'{}\' passed.'.format(test_name)
| {
"content_hash": "96ad057b928f9d8245cc56096ab755f3",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 120,
"avg_line_length": 34.175,
"alnum_prop": 0.5703486954401366,
"repo_name": "erja-gp/openthread",
"id": "82744799a90c32f009ef91ab648bbec051876a43",
"size": "5703",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "tests/toranj/test-601-channel-manager-channel-change.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "15850"
},
{
"name": "C",
"bytes": "940119"
},
{
"name": "C#",
"bytes": "18077"
},
{
"name": "C++",
"bytes": "4306681"
},
{
"name": "Dockerfile",
"bytes": "6256"
},
{
"name": "M4",
"bytes": "63303"
},
{
"name": "Makefile",
"bytes": "133368"
},
{
"name": "Python",
"bytes": "2012919"
},
{
"name": "Ruby",
"bytes": "3397"
},
{
"name": "Shell",
"bytes": "74907"
}
],
"symlink_target": ""
} |
from malcolm.yamlutil import check_yaml_names, make_include_creator
compoundmotor_collection = make_include_creator(
__file__, "compoundmotor_collection.yaml"
)
cs_collection = make_include_creator(__file__, "cs_collection.yaml")
motor_records = make_include_creator(__file__, "motor_records.yaml")
rawmotor_collection = make_include_creator(__file__, "rawmotor_collection.yaml")
trajectory_collection = make_include_creator(__file__, "trajectory_collection.yaml")
__all__ = check_yaml_names(globals())
| {
"content_hash": "d0580160eaa94ce60e075a33f711976f",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 84,
"avg_line_length": 46.27272727272727,
"alnum_prop": 0.7485265225933202,
"repo_name": "dls-controls/pymalcolm",
"id": "8aed9050e21b340a8ad7d78668bdeffe7a281efb",
"size": "509",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "malcolm/modules/pmac/includes/__init__.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "549"
},
{
"name": "Python",
"bytes": "1583458"
},
{
"name": "Shell",
"bytes": "580"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals, print_function, absolute_import
import sys
import json
import logging
import argparse
import re
from marklogic.connection import Connection
from marklogic.models.database import Database
from marklogic import MarkLogic
from requests.auth import HTTPDigestAuth
from resources import TestConnection as tc
logging.basicConfig(level=logging.WARNING)
logging.getLogger("requests").setLevel(logging.WARNING)
logging.getLogger("marklogic").setLevel(logging.DEBUG)
logging.getLogger("marklogic.examples").setLevel(logging.INFO)
class Properties:
def __init__(self):
self._artifact_types = {'database': 'D',
'server': 'S',
'host': 'H',
'user': 'U',
'forest': 'F',
'role': 'R'}
def artifact_types(self):
return self._artifact_types
def connect(self, args):
try:
adminuser, adminpass = re.split(":", args['credentials'])
except ValueError:
print ("--credentials value must be 'user:password':",
args['credentials'])
sys.exit(1)
if args['debug']:
logging.basicConfig(level=logging.WARNING)
logging.getLogger("requests").setLevel(logging.WARNING)
logging.getLogger("marklogic").setLevel(logging.DEBUG)
self.connection \
= Connection(args['hostname'], HTTPDigestAuth(adminuser, adminpass))
self.mls = MarkLogic(self.connection)
self.args = args
def list_artifacts(self):
alltypes = True
artifact_types = self.artifact_types()
args = self.args
mls = self.mls
for atype in artifact_types:
if args[atype]:
alltypes = False
for atype in artifact_types:
if not alltypes and not args[atype]:
continue
if atype == 'database':
print("Databases:")
for db in mls.databases():
print("\t{0}".format(db))
elif atype == 'server':
alist = mls.http_servers()
if alist:
print("HTTP Servers:")
for server in alist:
print("\t{0}".format(server))
alist = mls.xdbc_servers()
if alist:
print("XDBC Servers:")
for server in alist:
print("\t{0}".format(server))
alist = mls.odbc_servers()
if alist:
print("ODBC Servers:")
for server in alist:
print("\t{0}".format(server))
alist = mls.webdav_servers()
if alist:
print("WebDAV Servers:")
for server in alist:
print("\t{0}".format(server))
elif atype == 'host':
alist = mls.hosts()
if alist:
print("Hosts:")
for host in alist:
print("\t{0}".format(host))
elif atype == 'user':
alist = mls.users()
if alist:
print("Users:")
for user in alist:
print("\t{0}".format(user))
elif atype == 'forest':
alist = mls.forests()
if alist:
print("Forests:")
for forest in alist:
print("\t{0}".format(forest))
elif atype == 'role':
alist = mls.roles()
if alist:
print("Roles:")
for role in alist:
print("\t{0}".format(role))
else:
print("Internal error: unexpected artifact type:", atype)
def show_artifact(self, artifact):
alltypes = True
artifact_types = self.artifact_types()
args = self.args
mls = self.mls
for atype in artifact_types:
if args[atype]:
alltypes = False
for atype in artifact_types:
if not alltypes and not args[atype]:
continue
if atype == 'database':
alist = mls.databases()
if artifact in alist:
prop = mls.database(artifact)
print(json.dumps(prop.marshal()))
sys.exit(0)
elif atype == 'server':
try:
servername,groupname = re.split(":", artifact)
except ValueError:
servername = artifact
groupname = "Default"
key = "{0}|{1}".format(groupname, servername)
alist = mls.http_servers()
if key in alist:
prop = mls.http_server(key)
print(json.dumps(prop.marshal()))
sys.exit(0)
alist = mls.odbc_servers()
if key in alist:
prop = mls.odbc_server(key)
print(json.dumps(prop.marshal()))
sys.exit(0)
alist = mls.xdbc_servers()
if key in alist:
prop = mls.xdbc_server(key)
print(json.dumps(prop.marshal()))
sys.exit(0)
alist = mls.webdav_servers()
if key in alist:
prop = mls.webdav_server(key)
print(json.dumps(prop.marshal()))
sys.exit(0)
elif atype == 'host':
alist = mls.hosts()
if artifact in alist:
prop = mls.host(artifact)
print(json.dumps(prop.marshal()))
sys.exit(0)
elif atype == 'user':
alist = mls.users()
if artifact in alist:
prop = mls.user(artifact)
print(json.dumps(prop.marshal()))
sys.exit(0)
elif atype == 'forest':
alist = mls.forests()
if artifact in alist:
prop = mls.forest(artifact)
print(json.dumps(prop.marshal()))
sys.exit(0)
elif atype == 'role':
alist = mls.roles()
if artifact in alist:
prop = mls.role(artifact)
print(json.dumps(prop.marshal()))
sys.exit(0)
else:
print("Internal error: unexpected artifact type:", atype)
print("No artifact named:", artifact)
def main():
props = Properties()
parser = argparse.ArgumentParser(
description="Dump MarkLogic server artifact properties.")
artifact_types = props.artifact_types()
parser.add_argument('artifact', metavar='artifact-name', nargs="?",
help='The name of an artifact (database, server, ...)')
parser.add_argument('hostname', metavar='host', nargs="?", default='localhost',
help='The host to query')
parser.add_argument('-u', '--credentials', default='admin:admin',
metavar='USER:PASS',
help='Admin user:pass for new cluster')
parser.add_argument('--debug', action='store_true',
help='Turn on debug logging')
for atype in artifact_types:
parser.add_argument("-{0}".format(artifact_types[atype]),
"--{0}".format(atype),
action='store_true',
help='Select only ' + atype + ' artifacts')
args = vars(parser.parse_args())
props.connect(args)
if args['artifact'] is None:
props.list_artifacts()
else:
props.show_artifact(args['artifact'])
if __name__ == '__main__':
main()
| {
"content_hash": "87de4e7b677eef467ea3271bd09495dc",
"timestamp": "",
"source": "github",
"line_count": 227,
"max_line_length": 83,
"avg_line_length": 35.83700440528634,
"alnum_prop": 0.47215734480639215,
"repo_name": "supriyantomaftuh/python_api",
"id": "dda5eabc96d5e5abf5400aaa4c6040ec526f7f5c",
"size": "8643",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "examples/properties.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "213"
},
{
"name": "Python",
"bytes": "719010"
},
{
"name": "Shell",
"bytes": "2535"
}
],
"symlink_target": ""
} |
from fabric.api import sudo, put, run, cd
from fabric.contrib.files import append, exists, comment
def install():
sudo("apt-get update")
sudo("apt-get install python-dev python-pip python-opencv libevent-dev python-virtualenv nginx ajaxterm")
sudo("service apache2 stop")
sudo("update-rc.d apache2 disable")
install_adb()
def install_adb():
put("./adb", "/usr/bin/adb", use_sudo=True)
sudo("chmod +x /usr/bin/adb")
LOG_PATH = "/var/log/monitor_daemon"
def config(zk):
def update_hosts(zk):
comment("/etc/hosts", r"^[0-9]+.[0-9]+.[0-9]+.[0-9]+\s+zookeeper_server", use_sudo=True)
append("/etc/hosts", "%s\tzookeeper_server" % zk, use_sudo=True)
def update_nginx():
put("./nginx.default", "/etc/nginx/sites-available/default", use_sudo=True)
sudo("service nginx restart")
def update_rc_local():
put("./rc.local", "/etc/rc.local", use_sudo=True)
sudo("chmod +x /etc/rc.local")
def update_log_rotate():
put("./log-rotate", "/etc/logrotate.d/monitor_daemon", use_sudo=True)
def mkdir_dirs():
if not exists(LOG_PATH):
sudo("mkdir %s" % LOG_PATH)
if not exists("/home/pi/jobs"):
run("mkdir /home/pi/jobs")
update_hosts(zk)
update_nginx()
update_rc_local()
mkdir_dirs()
update_log_rotate()
def deploy(branch="master"):
if exists("/home/pi/app"):
with cd("/home/pi/app"):
run("git checkout -B %s --track origin/%s" % (branch, branch))
run("git pull")
else:
run("git clone -b %s https://github.com/xiaocong/remote-task-http-server.git /home/pi/app" % branch)
with cd("/home/pi/app"):
sudo("pip install -r requirements.txt --upgrade")
restart()
def restart():
with cd("/home/pi/app"):
if not exists("/var/run/gunicorn.pid"):
sudo("gunicorn -u 1000 --pid /var/run/gunicorn.pid -c gunicorn.config.py app:app -D", pty=False)
if exists("/var/run/monitor_daemon.pid"):
sudo("python monitor_daemon.py stop")
sudo("python monitor_daemon.py start", pty=False)
def reboot():
from fabric.api import reboot as rb
rb()
| {
"content_hash": "6387dd5537f5f6824a6730b75e422f97",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 109,
"avg_line_length": 30.583333333333332,
"alnum_prop": 0.6026339691189827,
"repo_name": "xiaocong/remote-task-http-server-fab",
"id": "ca7ffbd92c50f217e25ba545b11a2f94ff6b1bc1",
"size": "2249",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "fabfile.py",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
import os
import logging
import optparse
from django.db import models
from django.utils.daemonize import become_daemon
from django.core.management.base import NoArgsCommand
from ...utils import get_backend, get_middleware, configure_logging
from ...runner import runner
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
optparse.make_option('--pidfile', action='store', dest='pidfile', default=None,
help="Fork and write pidfile to this file."),
optparse.make_option('--logfile', action='store', dest='logfile', default=None,
help="Log to the specified file."),
optparse.make_option('--touchfile', action='store', dest='touchfile', default=None,
help="touch(1) the specified file after running a job."),
)
def handle_noargs(self, **options):
# Django < 1.8.3 leaves options['verbosity'] as a string so we cast to
# ensure an int.
verbosity = int(options['verbosity'])
level = {
0: logging.WARNING,
1: logging.INFO,
2: logging.DEBUG,
}[verbosity]
def log_filename(name):
try:
return options['logfile'] % name
except TypeError:
return options['logfile']
def touch_filename(name):
try:
return options['touchfile'] % name
except TypeError:
return None
configure_logging(
level=level,
format='%(asctime)-15s %(process)d %(levelname).1s: %(message)s',
filename=log_filename('master'),
)
log = logging.getLogger()
log.info("Starting queue runner")
# Ensure children will be able to import our backend
get_backend()
get_middleware()
log.info("Loaded middleware")
# Ensure children will be able to import most things, but also try and
# save memory by importing as much as possible before the fork() as it
# has copy-on-write semantics.
models.get_models()
log.info("Loaded models")
# fork() only after we have started enough to catch failure, including
# being able to write to our pidfile.
if options['pidfile']:
with open(options['pidfile'], 'w') as f:
become_daemon(our_home_dir='/')
print >>f, os.getpid()
runner(log, log_filename, touch_filename)
| {
"content_hash": "d817ba59820ab87d7157bec4b89ba50b",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 91,
"avg_line_length": 33.445945945945944,
"alnum_prop": 0.593939393939394,
"repo_name": "prophile/django-lightweight-queue",
"id": "248fff7eee2608482552d1ffa49acb4c5f6dc0ae",
"size": "2475",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "django_lightweight_queue/management/commands/queue_runner.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "26256"
},
{
"name": "Shell",
"bytes": "1888"
}
],
"symlink_target": ""
} |
import os
import sys
import imp
import pkg_resources
import mimetypes
from paste import request
from paste import fileapp
from paste.util import import_string
from paste.deploy import converters
from paste import httpexceptions
from paste.httpheaders import ETAG
from paste.urlparser import StaticURLParser
class CacheableStaticURLParser( StaticURLParser ):
def __init__( self, directory, cache_seconds=None ):
StaticURLParser.__init__( self, directory )
self.cache_seconds = cache_seconds
def __call__( self, environ, start_response ):
path_info = environ.get('PATH_INFO', '')
if not path_info:
return self.add_slash(environ, start_response)
if path_info == '/':
# @@: This should obviously be configurable
filename = 'index.html'
else:
filename = request.path_info_pop(environ)
full = os.path.join(self.directory, filename)
if not os.path.exists(full):
return self.not_found(environ, start_response)
if os.path.isdir(full):
# @@: Cache?
return self.__class__(full)(environ, start_response)
if environ.get('PATH_INFO') and environ.get('PATH_INFO') != '/':
return self.error_extra_path(environ, start_response)
if_none_match = environ.get('HTTP_IF_NONE_MATCH')
if if_none_match:
mytime = os.stat(full).st_mtime
if str(mytime) == if_none_match:
headers = []
ETAG.update(headers, mytime)
start_response('304 Not Modified',headers)
return [''] # empty body
app = fileapp.FileApp(full)
if self.cache_seconds:
app.cache_control( max_age = int( self.cache_seconds ) )
return app(environ, start_response)
def make_static( global_conf, document_root, cache_seconds=None ):
return CacheableStaticURLParser( document_root, cache_seconds ) | {
"content_hash": "e0ebe35b26cbe2076ee8f1807a8e3ca3",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 72,
"avg_line_length": 39.34,
"alnum_prop": 0.6273512963904423,
"repo_name": "jmchilton/galaxy-central",
"id": "7fd9467c216eda5a42b7531d4eb1f7bdb0cc22e9",
"size": "1967",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "galaxy/web/static.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "32128"
},
{
"name": "HTML",
"bytes": "96150"
},
{
"name": "JavaScript",
"bytes": "37270"
},
{
"name": "Makefile",
"bytes": "1035"
},
{
"name": "Python",
"bytes": "1341118"
},
{
"name": "Shell",
"bytes": "3787"
}
],
"symlink_target": ""
} |
"""
proxy.py
~~~~~~~~
⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
Network monitoring, controls & Application development, testing, debugging.
:copyright: (c) 2013-present by Abhinav Singh and contributors.
:license: BSD, see LICENSE for more details.
"""
import time
import logging
import multiprocessing
from typing import Any, Dict, Optional
from proxy.core.event import (
EventQueue, EventManager, EventSubscriber, eventNames,
)
from proxy.common.constants import DEFAULT_LOG_FORMAT
logging.basicConfig(level=logging.DEBUG, format=DEFAULT_LOG_FORMAT)
logger = logging.getLogger(__name__)
num_events_received = [0, 0]
# Execute within a separate thread context
def on_event(payload: Dict[str, Any]) -> None:
'''Subscriber callback.'''
global num_events_received
if payload['request_id'] == '1234':
num_events_received[0] += 1
else:
num_events_received[1] += 1
def publisher_process(
shutdown_event: multiprocessing.synchronize.Event,
dispatcher_queue: EventQueue,
) -> None:
logger.info('publisher started')
try:
while not shutdown_event.is_set():
dispatcher_queue.publish(
request_id='12345',
event_name=eventNames.WORK_STARTED,
event_payload={'time': time.time()},
publisher_id='eventing_pubsub_process',
)
except KeyboardInterrupt:
pass
logger.info('publisher shutdown')
if __name__ == '__main__':
start_time = time.time()
# Start eventing core
subscriber: Optional[EventSubscriber] = None
with EventManager() as event_manager:
assert event_manager.queue
# Create a subscriber.
# Internally, subscribe will start a separate thread
# to receive incoming published messages.
with EventSubscriber(event_manager.queue, callback=on_event) as subscriber:
# Start a publisher process to demonstrate safe exchange
# of messages between processes.
publisher_shutdown_event = multiprocessing.Event()
publisher = multiprocessing.Process(
target=publisher_process, args=(
publisher_shutdown_event, event_manager.queue, ),
)
publisher.start()
# Dispatch event from main process too
# to demonstrate safe exchange of messages
# between threads.
try:
while True:
event_manager.queue.publish(
request_id='1234',
event_name=eventNames.WORK_STARTED,
event_payload={'time': time.time()},
publisher_id='eventing_pubsub_main',
)
except KeyboardInterrupt:
logger.info('KBE!!!')
finally:
# Stop publisher process
publisher_shutdown_event.set()
publisher.join()
logger.info(
'Received {0} events from main thread, {1} events from another process, in {2} seconds'.format(
num_events_received[0], num_events_received[1], time.time(
) - start_time,
),
)
logger.info('Done!!!')
| {
"content_hash": "21121b1b1b07dbb7e04d4415e6704d6e",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 115,
"avg_line_length": 33.40594059405941,
"alnum_prop": 0.5880260818020154,
"repo_name": "abhinavsingh/proxy.py",
"id": "936e455b76ef7df9be28759a11944cc677d2cf22",
"size": "3404",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "examples/pubsub_eventing.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "891"
},
{
"name": "Dockerfile",
"bytes": "1222"
},
{
"name": "HTML",
"bytes": "3454"
},
{
"name": "JavaScript",
"bytes": "2260"
},
{
"name": "Jupyter Notebook",
"bytes": "29773"
},
{
"name": "Makefile",
"bytes": "6399"
},
{
"name": "Procfile",
"bytes": "387"
},
{
"name": "Python",
"bytes": "680280"
},
{
"name": "Ruby",
"bytes": "990"
},
{
"name": "Shell",
"bytes": "19211"
},
{
"name": "TypeScript",
"bytes": "23642"
}
],
"symlink_target": ""
} |
"""
Revision ID: 0208_fix_unique_index
Revises: 0207_set_callback_history_type
Create Date: 2018-07-25 13:55:24.941794
"""
from alembic import op
revision = "84c3b6eb16b3"
down_revision = "0207_set_callback_history_type"
def upgrade():
op.create_unique_constraint("uix_service_callback_type", "service_callback_api", ["service_id", "callback_type"])
op.drop_index("ix_service_callback_api_service_id", table_name="service_callback_api")
op.create_index(op.f("ix_service_callback_api_service_id"), "service_callback_api", ["service_id"], unique=False)
def downgrade():
op.drop_index(op.f("ix_service_callback_api_service_id"), table_name="service_callback_api")
op.create_index("ix_service_callback_api_service_id", "service_callback_api", ["service_id"], unique=True)
op.drop_constraint("uix_service_callback_type", "service_callback_api", type_="unique")
| {
"content_hash": "9c519cd4aa630ac64ceb4500e1d8afec",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 117,
"avg_line_length": 38.56521739130435,
"alnum_prop": 0.7215332581736189,
"repo_name": "alphagov/notifications-api",
"id": "0ad53f814d3c85ef714b8ec7b1c2dad9a47e4e76",
"size": "887",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "migrations/versions/0208_fix_unique_index.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "719"
},
{
"name": "Jinja",
"bytes": "5543"
},
{
"name": "Makefile",
"bytes": "6627"
},
{
"name": "Mako",
"bytes": "361"
},
{
"name": "Procfile",
"bytes": "35"
},
{
"name": "Python",
"bytes": "3506225"
},
{
"name": "Shell",
"bytes": "13179"
}
],
"symlink_target": ""
} |
"""Creates a grd file for packaging the inspector files."""
import os
import shlex
import sys
from xml.dom import minidom
kDevToolsResourcePrefix = 'IDR_DEVTOOLS_'
kGrdTemplate = '''<?xml version="1.0" encoding="UTF-8"?>
<grit latest_public_release="0" current_release="1"
output_all_resource_defines="false">
<outputs>
<output filename="grit/devtools_resources.h" type="rc_header">
<emit emit_type='prepend'></emit>
</output>
<output filename="grit/devtools_resources_map.cc" type="resource_file_map_source" />
<output filename="grit/devtools_resources_map.h" type="resource_map_header" />
<output filename="devtools_resources.pak" type="data_package" />
</outputs>
<release seq="1">
<includes>
<include name="COMPRESSED_PROTOCOL_JSON" file="${protocol_file}" use_base_dir="false" compress="brotli" type="BINDATA" skip_in_resource_map = "true"/>
</includes>
</release>
</grit>
'''
class ParsedArgs:
def __init__(self, file_list, output_filename, compress):
self.file_list = file_list
file_list_file = open(file_list, 'r')
file_list_contents = file_list_file.read()
self.source_files = shlex.split(file_list_contents)
self.output_filename = output_filename
self.compress = compress
def parse_args(argv):
# The arguments are of the format:
# --file_list <input_file_list>
# --output <output_file>
# --compress
file_list_position = argv.index('--file_list')
output_position = argv.index('--output')
file_list = argv[file_list_position + 1]
compress = argv.count('--compress') > 0
return ParsedArgs(file_list, argv[output_position + 1], compress)
def make_name_from_filename(filename):
return (filename.replace('/', '_').replace('\\', '_').replace('-', '_').replace('.', '_')).upper()
def add_file_to_grd(grd_doc, relative_filename, compress):
includes_node = grd_doc.getElementsByTagName('includes')[0]
includes_node.appendChild(grd_doc.createTextNode('\n '))
ext = os.path.splitext(relative_filename)[1]
new_include_node = grd_doc.createElement('include')
if compress and ext in ['.css', '.html', '.js', '.svg', '.json', '.md']:
new_include_node.setAttribute('file',
relative_filename + '.compressed')
else:
new_include_node.setAttribute('file', relative_filename)
new_include_node.setAttribute('name', make_name_from_filename(relative_filename))
new_include_node.setAttribute('resource_path', relative_filename)
new_include_node.setAttribute('type', 'BINDATA')
new_include_node.setAttribute('compress', 'false')
includes_node.appendChild(new_include_node)
def main(argv):
parsed_args = parse_args(argv[1:])
doc = minidom.parseString(kGrdTemplate)
written_filenames = set()
for filename in parsed_args.source_files:
# Avoid writing duplicate relative filenames.
if filename in written_filenames:
raise Exception("Duplicate file detected: %s" % filename)
written_filenames.add(filename)
add_file_to_grd(doc, filename, parsed_args.compress)
with open(parsed_args.output_filename, 'wb') as output_file:
output_file.write(doc.toxml(encoding='UTF-8'))
if __name__ == '__main__':
sys.exit(main(sys.argv))
| {
"content_hash": "3d57b8a1cab6bfc4317d26c572f7f2c6",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 156,
"avg_line_length": 35.27368421052632,
"alnum_prop": 0.6559236048940614,
"repo_name": "ChromeDevTools/devtools-frontend",
"id": "be215c0181090f90383db3cc7f3c4bc736b238f1",
"size": "4918",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "scripts/build/generate_devtools_grd.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "615241"
},
{
"name": "Dart",
"bytes": "205"
},
{
"name": "HTML",
"bytes": "317251"
},
{
"name": "JavaScript",
"bytes": "1401177"
},
{
"name": "LLVM",
"bytes": "1918"
},
{
"name": "Makefile",
"bytes": "687"
},
{
"name": "Python",
"bytes": "133111"
},
{
"name": "Shell",
"bytes": "1122"
},
{
"name": "TypeScript",
"bytes": "15230731"
},
{
"name": "WebAssembly",
"bytes": "921"
}
],
"symlink_target": ""
} |
from .abstract_data_converter import AbstractDataConverter
from .pickle_data_converter import PickleDataConverter
from .json_data_converter import JSONDataConverter
| {
"content_hash": "605b522092193c3308812ecbd5c3be4e",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 58,
"avg_line_length": 55,
"alnum_prop": 0.8727272727272727,
"repo_name": "darjus/botoflow",
"id": "996b1969f3c7df5e2264429194773d23287b6d9c",
"size": "727",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "botoflow/data_converter/__init__.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "477649"
}
],
"symlink_target": ""
} |
import sys
import os
import servicemanager
import logging
import logging.handlers
import weakref
import traceback
#from winsys import event_logs
import util
class EventLog:
# The singleton instance of our logger class
_LOG_INSTANCE = None
_OPE_STATE_LOG_INSTANCE = None
@staticmethod
def get_current_instance():
if EventLog._LOG_INSTANCE is None:
# Invalid log instance!
#print("No Logger Setup!")
return None
return EventLog._LOG_INSTANCE
@staticmethod
def get_ope_state_instance():
if EventLog._OPE_STATE_LOG_INSTANCE is None:
# Make the state logger and set it up.
# NOTE - this is to log to the background of the OPE laptops
lf = os.path.join(util.LOG_FOLDER, 'ope-state.log') #"%programdata%\ope\tmp\log\ope-state.log"
l = logging.getLogger("OPE_STATE")
l.setLevel(logging.DEBUG)
fmt = logging.Formatter('%(asctime)-15s %(message)s',
'%Y-%m-%d %I:%M:%S%p')
f_handler = logging.handlers.RotatingFileHandler(os.path.expandvars(lf),
mode='a', maxBytes=2*1024, backupCount=1, delay=0, encoding=None)
f_handler.setFormatter(fmt)
f_handler.setLevel(logging.DEBUG)
l.addHandler(f_handler)
# Make flush of logs available
l.flush = f_handler.flush
EventLog._OPE_STATE_LOG_INSTANCE = l
return EventLog._OPE_STATE_LOG_INSTANCE
def __init__(self, log_file=None, service_name="OPEService"):
EventLog._LOG_INSTANCE = self
#print("Creating Event Logger " + log_file + "/" + service_name)
self.log_file = log_file
self.service_name = service_name
# Queue of messages - keep in the list until we get the log init properly?
self.log_messages = []
# Queue for win messages - save up and log at the end
self.log_messages_win = []
# Log levels = 1 - error(only), 2 - warnings, 3 - info, 4 - debug (all)
self.log_level = 3
self.logger = None
# Setup the destructor
self._finalizer = weakref.finalize(self, self.flush_win_logs,
self.log_messages_win)
if self.init_logger() is False:
print("***** MAJOR ERROR - Couldn't init logging! *****")
#self.log_event("Connected to Log: " + self.log_file + "/" + self.service_name)
def init_logger(self):
if self.logger is None:
# Setup logging
#print("Initializing logging....")
try:
# Don't do basicConfig - it auto creates a streamhandler
# logging.basicConfig(
# level=logging.DEBUG,
# datefmt='%Y-%m-%d %H:%M:%S',
# format='[ope-svc] %(asctime)-15s %(levelname)-7.7s %(message)s',
# filename=self.log_file
# )
self.logger = logging.getLogger()
self.logger.setLevel(logging.DEBUG)
#self.logger.setFormatter(fmt)
except Exception as ex:
print("*** Error setting up logger!\n" + str(ex))
return False
self.add_file_handler()
# Add a stream handler so it outputs on the screen
# sh = logging.StreamHandler()
# sh.setFormatter(fmt)
# sh.setLevel(logging.DEBUG)
# self.logger.addHandler(sh)
# NOTE - this got moved to flush_win_logs so we
# can dump them all in one shot instead of seperate events
# Log to win event log if possible
# try:
# #if self.service_name == "OPEService":
# # dllname = "%programdata%\\ope\\Services\\OPEService\\OPEService.exe"
# #else:
# # dllname = "%programdata%\\ope\\Services\\mgmt\\mgmt.exe"
# #dllname = "%programdata%\\ope\\Services\\OPEService\\mgmt_EventLogMessages.dll"
# #dllname = "%programdata%\\ope\\Services\\OPEService\\servicemanager.pyd"
# dllname = None
# win_handler = logging.handlers.NTEventLogHandler(self.service_name,
# dllname, "Application")
# win_handler.setFormatter(fmt)
# win_handler.setLevel(logging.DEBUG)
# self.logger.addHandler(win_handler)
# except Exception as ex:
# print("Error setting up windows event logging!\n" + str(ex))
return True
def add_file_handler(self, log_file=None, fallback_log_file="%tmp%/mgmt.log"):
if self.logger is None:
# No logger!
print("No logger present, can't add file handler!")
return False
fmt = logging.Formatter('[' + self.service_name + '] %(asctime)-15s %(levelname)-7.7s %(message)s',
'%Y-%m-%d %H:%M:%S')
# Get the current log file to try
# 1st - current log_file param
# 2nd - self.log_file
# 3rd - fallback log file
lf = log_file
if lf is None:
lf = self.log_file
if lf is None:
lf = fallback_log_file
# Collect error messages
errors = []
failed_lf = ""
# Try the current log file
try:
f_handler = logging.handlers.RotatingFileHandler(os.path.expandvars(lf),
mode='a', maxBytes=3*1024*1024, backupCount=1, delay=0, encoding=None)
f_handler.setFormatter(fmt)
f_handler.setLevel(logging.DEBUG)
self.logger.addHandler(f_handler)
return True
except Exception as ex:
errors.append("S1 - Unable to add file handler " + str(lf) + "\n" + str(ex))
failed_lf = lf
if lf == fallback_log_file:
# No more to try!
# If we get here, we can't log
print("-- Error setting up file logging! " + \
str(lf) + "\n" + str(errors))
return False
# Try the next log file - try self.logfile
lf = self.log_file
if lf is None:
# Skip to fallback
lf = fallback_log_file
# Try the current log file
try:
f_handler = logging.handlers.RotatingFileHandler(os.path.expandvars(lf),
mode='a', maxBytes=3*1024*1024, backupCount=1, delay=0, encoding=None)
f_handler.setFormatter(fmt)
f_handler.setLevel(logging.DEBUG)
self.logger.addHandler(f_handler)
return True
except Exception as ex:
errors.append("S2 - Unable to add file handler " + str(lf) + "\n" + str(ex))
failed_lf = lf
if lf == fallback_log_file:
# No more to try!
# If we get here, we can't log
print("-- Error setting up file logging! " + \
str(lf) + "\n" + str(errors))
return False
# Try the fallback
lf = fallback_log_file
# Try the current log file
try:
f_handler = logging.handlers.RotatingFileHandler(os.path.expandvars(lf),
mode='a', maxBytes=3*1024*1024, backupCount=1, delay=0, encoding=None)
f_handler.setFormatter(fmt)
f_handler.setLevel(logging.DEBUG)
self.logger.addHandler(f_handler)
return True
except Exception as ex:
errors.append("S3 - Unable to add file handler " + str(lf) + "\n" + str(ex))
failed_lf = lf
# If we get here, we can't log
print("-- Error setting up file logging! " + \
str(lf) + "\n" + str(errors))
return False
def log_event(self, msg, is_error=False, show_in_event_log=True, log_level=3):
self.init_logger()
# Queue up messages - in case our logger isn't ready yet?
if log_level > self.log_level:
# Ignore this log item if we aren't at least level 5
# if self.log_level >= 5:
# print("SVC --> Skipping Log Event (Log Level " + str(log_level) +
# "/" + str(self.log_level) + ")\n")
# print("\t" + msg)
return
# Remove }}rn?? type codes from the message - no need for them in text file or event log
#msg = strip_color_codes(msg)
#msg = translate_color_codes(msg)
msg_entry = dict(msg=msg, is_error=is_error, show_in_event_log=show_in_event_log)
self.log_messages.append(msg_entry)
self.log_messages_win.append(msg_entry)
# If there are messages waiting, log them.
m_queue = self.log_messages.copy()
self.log_messages.clear()
if self.logger:
try:
for m in m_queue:
if m["is_error"]:
self.logger.error(m["msg"])
else:
self.logger.info(m["msg"])
except Exception as ex:
print("Error writing to service log!\n" + str(ex))
else:
# No logger? Print to the console
print("(console) " + self.service_name + ": " + msg)
# if self.win_logger:
# try:
# for m in m_queue:
# if m["show_in_event_log"]:
# if m["is_error"]:
# self.win_logger.log_event(type="error", message=m["msg"])
# #servicemanager.LogMsg(
# # servicemanager.EVENTLOG_ERROR_TYPE,
# # 0xF000, # generic message
# # (m["msg"], '')
# #)
# else:
# self.win_logger.log_event(type="information", message=m["msg"])
# # servicemanager.LogMsg(
# # servicemanager.EVENTLOG_INFORMATION_TYPE,
# # 0xF000, # generic message
# # (m["msg"], '')
# # )
# except Exception as ex:
# print("Error writing to win event log!\n" + str(ex))
return
def flush_win_logs(self, lines=None):
#print("Flush_win_logs_called")
# Flush the current logs to the win event logger
#print("Flushing win logs")
if lines is None:
lines = self.log_messages_win
if lines is None:
print("NO WIN LOG LINES FOUND!")
return False
if len(lines) < 1:
# Nothing to log?
#print("No Lines?!")
return True
cp_lines = lines.copy()
lines.clear()
# Build up the output from the logs
output = ""
for line in cp_lines:
l = line["msg"].strip()
# Line might be packed together, split it out and then re-combine so it looks
# correct in event log
new_txt = ""
parts = l.split("\n")
for p in parts:
new_txt += p.strip() + "\r\n"
output += new_txt
#output += line["msg"].strip() + "\r\n"
#print(output)
try:
#servicemanager.SetEventSourceName("OPE")
servicemanager.Initialize(self.service_name,
"%programdata%\\ope\\Services\\OPEService\\servicemanager.pyd")
except Exception as ex:
print("}}mnError setting source name for event logs!}}xx\n" + str(ex))
try:
# servicemanager.LogMsg(
# servicemanager.EVENTLOG_INFORMATION_TYPE,
# 0xF000, # generic message
# (output, '')
# )
servicemanager.LogInfoMsg(output)
except Exception as ex:
print("}}mnError writing to windows event log!}}xx\n" +
str(ex))
return True
| {
"content_hash": "b25f6e70bbfa925b73e26efb7b8f5f1f",
"timestamp": "",
"source": "github",
"line_count": 331,
"max_line_length": 107,
"avg_line_length": 37,
"alnum_prop": 0.5106556707765167,
"repo_name": "operepo/ope",
"id": "4730a1cc2b3c00f94de4872aec50c9ee22b33948",
"size": "12247",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client_tools/svc/mgmt_EventLog.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AL",
"bytes": "40379"
},
{
"name": "Awk",
"bytes": "22377"
},
{
"name": "Batchfile",
"bytes": "81725"
},
{
"name": "C",
"bytes": "655"
},
{
"name": "C++",
"bytes": "200907"
},
{
"name": "CMake",
"bytes": "8149"
},
{
"name": "CSS",
"bytes": "103747"
},
{
"name": "Dockerfile",
"bytes": "47152"
},
{
"name": "Emacs Lisp",
"bytes": "90665"
},
{
"name": "HTML",
"bytes": "37373861"
},
{
"name": "Java",
"bytes": "916104"
},
{
"name": "JavaScript",
"bytes": "9115492"
},
{
"name": "Makefile",
"bytes": "7428"
},
{
"name": "NewLisp",
"bytes": "111955"
},
{
"name": "PHP",
"bytes": "5053"
},
{
"name": "Perl",
"bytes": "45839826"
},
{
"name": "PostScript",
"bytes": "192210"
},
{
"name": "PowerShell",
"bytes": "2870"
},
{
"name": "Procfile",
"bytes": "114"
},
{
"name": "Prolog",
"bytes": "248055"
},
{
"name": "Python",
"bytes": "9037346"
},
{
"name": "QML",
"bytes": "125647"
},
{
"name": "QMake",
"bytes": "7566"
},
{
"name": "Raku",
"bytes": "7174577"
},
{
"name": "Roff",
"bytes": "25148"
},
{
"name": "Ruby",
"bytes": "162111"
},
{
"name": "Shell",
"bytes": "2574077"
},
{
"name": "Smalltalk",
"bytes": "77031"
},
{
"name": "SystemVerilog",
"bytes": "83394"
},
{
"name": "Tcl",
"bytes": "7061959"
},
{
"name": "Vim script",
"bytes": "27705984"
},
{
"name": "kvlang",
"bytes": "60630"
}
],
"symlink_target": ""
} |
try:
# For Django >= 1.5, use get_user_model() and store result User
from django.contrib.auth import get_user_model
User = get_user_model()
except ImportError:
# Django < 1.5, load User from registration.models
from django.contrib.auth.models import User
| {
"content_hash": "9a3a88445667db34ec442d94ff85ca76",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 67,
"avg_line_length": 39.285714285714285,
"alnum_prop": 0.7054545454545454,
"repo_name": "bruth/django-registration2",
"id": "f18f729f606aed721fd21a863c273226e4d5af2b",
"size": "504",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "registration/user.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "50004"
}
],
"symlink_target": ""
} |
from builtins import range
import sys, os
sys.path.insert(1, os.path.join("..","..",".."))
import h2o
from tests import pyunit_utils
from h2o.estimators.gbm import H2OGradientBoostingEstimator
from h2o.estimators.random_forest import H2ORandomForestEstimator
from h2o.estimators.isolation_forest import H2OIsolationForestEstimator
def feature_frequencies():
prostate_train = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate_train.csv"))
prostate_train["CAPSULE"] = prostate_train["CAPSULE"].asfactor()
features = list(range(1,prostate_train.ncol))
gbm = H2OGradientBoostingEstimator(ntrees=5)
gbm.train(x=features, y="CAPSULE", training_frame=prostate_train)
ff_gbm = gbm.feature_frequencies(prostate_train)
print(ff_gbm.shape)
assert ff_gbm.shape == (prostate_train.nrow, len(features))
drf = H2ORandomForestEstimator(ntrees=5)
drf.train(x=features, y="CAPSULE", training_frame=prostate_train)
ff_drf = drf.feature_frequencies(prostate_train)
assert ff_drf.shape == (prostate_train.nrow, len(features))
iforest = H2OIsolationForestEstimator(ntrees=5)
iforest.train(x=features, training_frame=prostate_train)
ff_iforest = drf.feature_frequencies(prostate_train)
assert ff_iforest.shape == (prostate_train.nrow, len(features))
if __name__ == "__main__":
pyunit_utils.standalone_test(feature_frequencies)
else:
feature_frequencies()
| {
"content_hash": "2ac1109dfc9b877ed692e55cf6469846",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 101,
"avg_line_length": 35.26829268292683,
"alnum_prop": 0.7344398340248963,
"repo_name": "h2oai/h2o-3",
"id": "0a58a74d7ff1c89e64d8689fb0289a27f38c2ecb",
"size": "1446",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "h2o-py/tests/testdir_algos/sharedtree/pyunit_feature_frequencies.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "12803"
},
{
"name": "CSS",
"bytes": "882321"
},
{
"name": "CoffeeScript",
"bytes": "7550"
},
{
"name": "DIGITAL Command Language",
"bytes": "106"
},
{
"name": "Dockerfile",
"bytes": "10459"
},
{
"name": "Emacs Lisp",
"bytes": "2226"
},
{
"name": "Groovy",
"bytes": "205646"
},
{
"name": "HCL",
"bytes": "36232"
},
{
"name": "HTML",
"bytes": "8018117"
},
{
"name": "HiveQL",
"bytes": "3985"
},
{
"name": "Java",
"bytes": "15981357"
},
{
"name": "JavaScript",
"bytes": "148426"
},
{
"name": "Jupyter Notebook",
"bytes": "20638329"
},
{
"name": "Makefile",
"bytes": "46043"
},
{
"name": "PHP",
"bytes": "800"
},
{
"name": "Python",
"bytes": "8188608"
},
{
"name": "R",
"bytes": "4149977"
},
{
"name": "Ruby",
"bytes": "64"
},
{
"name": "Sass",
"bytes": "23790"
},
{
"name": "Scala",
"bytes": "4845"
},
{
"name": "Shell",
"bytes": "214495"
},
{
"name": "Smarty",
"bytes": "1792"
},
{
"name": "TeX",
"bytes": "554940"
}
],
"symlink_target": ""
} |
import base64
import binascii
import os
import re
import StringIO
from boto.exception import BotoClientError
from boto.s3.key import Key as S3Key
from boto.s3.keyfile import KeyFile
from boto.utils import compute_hash
from boto.utils import get_utf8_value
class Key(S3Key):
"""
Represents a key (object) in a GS bucket.
:ivar bucket: The parent :class:`boto.gs.bucket.Bucket`.
:ivar name: The name of this Key object.
:ivar metadata: A dictionary containing user metadata that you
wish to store with the object or that has been retrieved from
an existing object.
:ivar cache_control: The value of the `Cache-Control` HTTP header.
:ivar content_type: The value of the `Content-Type` HTTP header.
:ivar content_encoding: The value of the `Content-Encoding` HTTP header.
:ivar content_disposition: The value of the `Content-Disposition` HTTP
header.
:ivar content_language: The value of the `Content-Language` HTTP header.
:ivar etag: The `etag` associated with this object.
:ivar last_modified: The string timestamp representing the last
time this object was modified in GS.
:ivar owner: The ID of the owner of this object.
:ivar storage_class: The storage class of the object. Currently, one of:
STANDARD | DURABLE_REDUCED_AVAILABILITY.
:ivar md5: The MD5 hash of the contents of the object.
:ivar size: The size, in bytes, of the object.
:ivar generation: The generation number of the object.
:ivar metageneration: The generation number of the object metadata.
:ivar encrypted: Whether the object is encrypted while at rest on
the server.
:ivar cloud_hashes: Dictionary of checksums as supplied by the storage
provider.
"""
def __init__(self, bucket=None, name=None, generation=None):
super(Key, self).__init__(bucket=bucket, name=name)
self.generation = generation
self.meta_generation = None
self.cloud_hashes = {}
self.component_count = None
def __repr__(self):
if self.generation and self.metageneration:
ver_str = '#%s.%s' % (self.generation, self.metageneration)
else:
ver_str = ''
if self.bucket:
return '<Key: %s,%s%s>' % (self.bucket.name, self.name, ver_str)
else:
return '<Key: None,%s%s>' % (self.name, ver_str)
def endElement(self, name, value, connection):
if name == 'Key':
self.name = value
elif name == 'ETag':
self.etag = value
elif name == 'IsLatest':
if value == 'true':
self.is_latest = True
else:
self.is_latest = False
elif name == 'LastModified':
self.last_modified = value
elif name == 'Size':
self.size = int(value)
elif name == 'StorageClass':
self.storage_class = value
elif name == 'Owner':
pass
elif name == 'VersionId':
self.version_id = value
elif name == 'Generation':
self.generation = value
elif name == 'MetaGeneration':
self.metageneration = value
else:
setattr(self, name, value)
def handle_version_headers(self, resp, force=False):
self.metageneration = resp.getheader('x-goog-metageneration', None)
self.generation = resp.getheader('x-goog-generation', None)
def handle_restore_headers(self, response):
return
def handle_addl_headers(self, headers):
for key, value in headers:
if key == 'x-goog-hash':
for hash_pair in value.split(','):
alg, b64_digest = hash_pair.strip().split('=', 1)
self.cloud_hashes[alg] = binascii.a2b_base64(b64_digest)
elif key == 'x-goog-component-count':
self.component_count = int(value)
elif key == 'x-goog-generation':
self.generation = value
# Use x-goog-stored-content-encoding and
# x-goog-stored-content-length to indicate original content length
# and encoding, which are transcoding-invariant (so are preferable
# over using content-encoding and size headers).
elif key == 'x-goog-stored-content-encoding':
self.content_encoding = value
elif key == 'x-goog-stored-content-length':
self.size = int(value)
def open_read(self, headers=None, query_args='',
override_num_retries=None, response_headers=None):
"""
Open this key for reading
:type headers: dict
:param headers: Headers to pass in the web request
:type query_args: string
:param query_args: Arguments to pass in the query string
(ie, 'torrent')
:type override_num_retries: int
:param override_num_retries: If not None will override configured
num_retries parameter for underlying GET.
:type response_headers: dict
:param response_headers: A dictionary containing HTTP
headers/values that will override any headers associated
with the stored object in the response. See
http://goo.gl/EWOPb for details.
"""
# For GCS we need to include the object generation in the query args.
# The rest of the processing is handled in the parent class.
if self.generation:
if query_args:
query_args += '&'
query_args += 'generation=%s' % self.generation
super(Key, self).open_read(headers=headers, query_args=query_args,
override_num_retries=override_num_retries,
response_headers=response_headers)
def get_file(self, fp, headers=None, cb=None, num_cb=10,
torrent=False, version_id=None, override_num_retries=None,
response_headers=None, hash_algs=None):
query_args = None
if self.generation:
query_args = ['generation=%s' % self.generation]
self._get_file_internal(fp, headers=headers, cb=cb, num_cb=num_cb,
override_num_retries=override_num_retries,
response_headers=response_headers,
hash_algs=hash_algs,
query_args=query_args)
def get_contents_to_file(self, fp, headers=None,
cb=None, num_cb=10,
torrent=False,
version_id=None,
res_download_handler=None,
response_headers=None,
hash_algs=None):
"""
Retrieve an object from GCS using the name of the Key object as the
key in GCS. Write the contents of the object to the file pointed
to by 'fp'.
:type fp: File -like object
:param fp:
:type headers: dict
:param headers: additional HTTP headers that will be sent with
the GET request.
:type cb: function
:param cb: a callback function that will be called to report
progress on the upload. The callback should accept two
integer parameters, the first representing the number of
bytes that have been successfully transmitted to GCS and
the second representing the size of the to be transmitted
object.
:type cb: int
:param num_cb: (optional) If a callback is specified with the
cb parameter this parameter determines the granularity of
the callback by defining the maximum number of times the
callback will be called during the file transfer.
:type torrent: bool
:param torrent: If True, returns the contents of a torrent
file as a string.
:type res_upload_handler: ResumableDownloadHandler
:param res_download_handler: If provided, this handler will
perform the download.
:type response_headers: dict
:param response_headers: A dictionary containing HTTP
headers/values that will override any headers associated
with the stored object in the response. See
http://goo.gl/sMkcC for details.
"""
if self.bucket is not None:
if res_download_handler:
res_download_handler.get_file(self, fp, headers, cb, num_cb,
torrent=torrent,
version_id=version_id,
hash_algs=hash_algs)
else:
self.get_file(fp, headers, cb, num_cb, torrent=torrent,
version_id=version_id,
response_headers=response_headers,
hash_algs=hash_algs)
def compute_hash(self, fp, algorithm, size=None):
"""
:type fp: file
:param fp: File pointer to the file to hash. The file
pointer will be reset to the same position before the
method returns.
:type algorithm: zero-argument constructor for hash objects that
implements update() and digest() (e.g. hashlib.md5)
:type size: int
:param size: (optional) The Maximum number of bytes to read
from the file pointer (fp). This is useful when uploading
a file in multiple parts where the file is being split
in place into different parts. Less bytes may be available.
"""
hex_digest, b64_digest, data_size = compute_hash(
fp, size=size, hash_algorithm=algorithm)
# The internal implementation of compute_hash() needs to return the
# data size, but we don't want to return that value to the external
# caller because it changes the class interface (i.e. it might
# break some code), so we consume the third tuple value here and
# return the remainder of the tuple to the caller, thereby preserving
# the existing interface.
self.size = data_size
return (hex_digest, b64_digest)
def send_file(self, fp, headers=None, cb=None, num_cb=10,
query_args=None, chunked_transfer=False, size=None,
hash_algs=None):
"""
Upload a file to GCS.
:type fp: file
:param fp: The file pointer to upload. The file pointer must
point point at the offset from which you wish to upload.
ie. if uploading the full file, it should point at the
start of the file. Normally when a file is opened for
reading, the fp will point at the first byte. See the
bytes parameter below for more info.
:type headers: dict
:param headers: The headers to pass along with the PUT request
:type num_cb: int
:param num_cb: (optional) If a callback is specified with the
cb parameter this parameter determines the granularity of
the callback by defining the maximum number of times the
callback will be called during the file
transfer. Providing a negative integer will cause your
callback to be called with each buffer read.
:type query_args: string
:param query_args: Arguments to pass in the query string.
:type chunked_transfer: boolean
:param chunked_transfer: (optional) If true, we use chunked
Transfer-Encoding.
:type size: int
:param size: (optional) The Maximum number of bytes to read
from the file pointer (fp). This is useful when uploading
a file in multiple parts where you are splitting the file
up into different ranges to be uploaded. If not specified,
the default behaviour is to read all bytes from the file
pointer. Less bytes may be available.
:type hash_algs: dictionary
:param hash_algs: (optional) Dictionary of hash algorithms and
corresponding hashing class that implements update() and digest().
Defaults to {'md5': hashlib.md5}.
"""
self._send_file_internal(fp, headers=headers, cb=cb, num_cb=num_cb,
query_args=query_args,
chunked_transfer=chunked_transfer, size=size,
hash_algs=hash_algs)
def delete(self, headers=None):
return self.bucket.delete_key(self.name, version_id=self.version_id,
generation=self.generation,
headers=headers)
def add_email_grant(self, permission, email_address):
"""
Convenience method that provides a quick way to add an email grant to a
key. This method retrieves the current ACL, creates a new grant based on
the parameters passed in, adds that grant to the ACL and then PUT's the
new ACL back to GS.
:type permission: string
:param permission: The permission being granted. Should be one of:
READ|FULL_CONTROL
See http://code.google.com/apis/storage/docs/developer-guide.html#authorization
for more details on permissions.
:type email_address: string
:param email_address: The email address associated with the Google
account to which you are granting the permission.
"""
acl = self.get_acl()
acl.add_email_grant(permission, email_address)
self.set_acl(acl)
def add_user_grant(self, permission, user_id):
"""
Convenience method that provides a quick way to add a canonical user
grant to a key. This method retrieves the current ACL, creates a new
grant based on the parameters passed in, adds that grant to the ACL and
then PUT's the new ACL back to GS.
:type permission: string
:param permission: The permission being granted. Should be one of:
READ|FULL_CONTROL
See http://code.google.com/apis/storage/docs/developer-guide.html#authorization
for more details on permissions.
:type user_id: string
:param user_id: The canonical user id associated with the GS account to
which you are granting the permission.
"""
acl = self.get_acl()
acl.add_user_grant(permission, user_id)
self.set_acl(acl)
def add_group_email_grant(self, permission, email_address, headers=None):
"""
Convenience method that provides a quick way to add an email group
grant to a key. This method retrieves the current ACL, creates a new
grant based on the parameters passed in, adds that grant to the ACL and
then PUT's the new ACL back to GS.
:type permission: string
:param permission: The permission being granted. Should be one of:
READ|FULL_CONTROL
See http://code.google.com/apis/storage/docs/developer-guide.html#authorization
for more details on permissions.
:type email_address: string
:param email_address: The email address associated with the Google
Group to which you are granting the permission.
"""
acl = self.get_acl(headers=headers)
acl.add_group_email_grant(permission, email_address)
self.set_acl(acl, headers=headers)
def add_group_grant(self, permission, group_id):
"""
Convenience method that provides a quick way to add a canonical group
grant to a key. This method retrieves the current ACL, creates a new
grant based on the parameters passed in, adds that grant to the ACL and
then PUT's the new ACL back to GS.
:type permission: string
:param permission: The permission being granted. Should be one of:
READ|FULL_CONTROL
See http://code.google.com/apis/storage/docs/developer-guide.html#authorization
for more details on permissions.
:type group_id: string
:param group_id: The canonical group id associated with the Google
Groups account you are granting the permission to.
"""
acl = self.get_acl()
acl.add_group_grant(permission, group_id)
self.set_acl(acl)
def set_contents_from_file(self, fp, headers=None, replace=True,
cb=None, num_cb=10, policy=None, md5=None,
res_upload_handler=None, size=None, rewind=False,
if_generation=None):
"""
Store an object in GS using the name of the Key object as the
key in GS and the contents of the file pointed to by 'fp' as the
contents.
:type fp: file
:param fp: the file whose contents are to be uploaded
:type headers: dict
:param headers: additional HTTP headers to be sent with the PUT request.
:type replace: bool
:param replace: If this parameter is False, the method will first check
to see if an object exists in the bucket with the same key. If it
does, it won't overwrite it. The default value is True which will
overwrite the object.
:type cb: function
:param cb: a callback function that will be called to report
progress on the upload. The callback should accept two integer
parameters, the first representing the number of bytes that have
been successfully transmitted to GS and the second representing the
total number of bytes that need to be transmitted.
:type num_cb: int
:param num_cb: (optional) If a callback is specified with the cb
parameter, this parameter determines the granularity of the callback
by defining the maximum number of times the callback will be called
during the file transfer.
:type policy: :class:`boto.gs.acl.CannedACLStrings`
:param policy: A canned ACL policy that will be applied to the new key
in GS.
:type md5: A tuple containing the hexdigest version of the MD5 checksum
of the file as the first element and the Base64-encoded version of
the plain checksum as the second element. This is the same format
returned by the compute_md5 method.
:param md5: If you need to compute the MD5 for any reason prior to
upload, it's silly to have to do it twice so this param, if present,
will be used as the MD5 values of the file. Otherwise, the checksum
will be computed.
:type res_upload_handler: ResumableUploadHandler
:param res_upload_handler: If provided, this handler will perform the
upload.
:type size: int
:param size: (optional) The Maximum number of bytes to read from
the file pointer (fp). This is useful when uploading
a file in multiple parts where you are splitting the
file up into different ranges to be uploaded. If not
specified, the default behaviour is to read all bytes
from the file pointer. Less bytes may be available.
Notes:
1. The "size" parameter currently cannot be used when
a resumable upload handler is given but is still
useful for uploading part of a file as implemented
by the parent class.
2. At present Google Cloud Storage does not support
multipart uploads.
:type rewind: bool
:param rewind: (optional) If True, the file pointer (fp) will be
rewound to the start before any bytes are read from
it. The default behaviour is False which reads from
the current position of the file pointer (fp).
:type if_generation: int
:param if_generation: (optional) If set to a generation number, the
object will only be written to if its current generation number is
this value. If set to the value 0, the object will only be written
if it doesn't already exist.
:rtype: int
:return: The number of bytes written to the key.
TODO: At some point we should refactor the Bucket and Key classes,
to move functionality common to all providers into a parent class,
and provider-specific functionality into subclasses (rather than
just overriding/sharing code the way it currently works).
"""
provider = self.bucket.connection.provider
if res_upload_handler and size:
# could use size instead of file_length if provided but...
raise BotoClientError(
'"size" param not supported for resumable uploads.')
headers = headers or {}
if policy:
headers[provider.acl_header] = policy
if rewind:
# caller requests reading from beginning of fp.
fp.seek(0, os.SEEK_SET)
else:
# The following seek/tell/seek logic is intended
# to detect applications using the older interface to
# set_contents_from_file(), which automatically rewound the
# file each time the Key was reused. This changed with commit
# 14ee2d03f4665fe20d19a85286f78d39d924237e, to support uploads
# split into multiple parts and uploaded in parallel, and at
# the time of that commit this check was added because otherwise
# older programs would get a success status and upload an empty
# object. Unfortuantely, it's very inefficient for fp's implemented
# by KeyFile (used, for example, by gsutil when copying between
# providers). So, we skip the check for the KeyFile case.
# TODO: At some point consider removing this seek/tell/seek
# logic, after enough time has passed that it's unlikely any
# programs remain that assume the older auto-rewind interface.
if not isinstance(fp, KeyFile):
spos = fp.tell()
fp.seek(0, os.SEEK_END)
if fp.tell() == spos:
fp.seek(0, os.SEEK_SET)
if fp.tell() != spos:
# Raise an exception as this is likely a programming
# error whereby there is data before the fp but nothing
# after it.
fp.seek(spos)
raise AttributeError('fp is at EOF. Use rewind option '
'or seek() to data start.')
# seek back to the correct position.
fp.seek(spos)
if hasattr(fp, 'name'):
self.path = fp.name
if self.bucket is not None:
if isinstance(fp, KeyFile):
# Avoid EOF seek for KeyFile case as it's very inefficient.
key = fp.getkey()
size = key.size - fp.tell()
self.size = size
# At present both GCS and S3 use MD5 for the etag for
# non-multipart-uploaded objects. If the etag is 32 hex
# chars use it as an MD5, to avoid having to read the file
# twice while transferring.
if (re.match('^"[a-fA-F0-9]{32}"$', key.etag)):
etag = key.etag.strip('"')
md5 = (etag, base64.b64encode(binascii.unhexlify(etag)))
if size:
self.size = size
else:
# If md5 is provided, still need to size so
# calculate based on bytes to end of content
spos = fp.tell()
fp.seek(0, os.SEEK_END)
self.size = fp.tell() - spos
fp.seek(spos)
size = self.size
if md5 is None:
md5 = self.compute_md5(fp, size)
self.md5 = md5[0]
self.base64md5 = md5[1]
if self.name is None:
self.name = self.md5
if not replace:
if self.bucket.lookup(self.name):
return
if if_generation is not None:
headers['x-goog-if-generation-match'] = str(if_generation)
if res_upload_handler:
res_upload_handler.send_file(self, fp, headers, cb, num_cb)
else:
# Not a resumable transfer so use basic send_file mechanism.
self.send_file(fp, headers, cb, num_cb, size=size)
def set_contents_from_filename(self, filename, headers=None, replace=True,
cb=None, num_cb=10, policy=None, md5=None,
reduced_redundancy=None,
res_upload_handler=None,
if_generation=None):
"""
Store an object in GS using the name of the Key object as the
key in GS and the contents of the file named by 'filename'.
See set_contents_from_file method for details about the
parameters.
:type filename: string
:param filename: The name of the file that you want to put onto GS
:type headers: dict
:param headers: Additional headers to pass along with the request to GS.
:type replace: bool
:param replace: If True, replaces the contents of the file if it
already exists.
:type cb: function
:param cb: (optional) a callback function that will be called to report
progress on the download. The callback should accept two integer
parameters, the first representing the number of bytes that have
been successfully transmitted from GS and the second representing
the total number of bytes that need to be transmitted.
:type cb: int
:param num_cb: (optional) If a callback is specified with the cb
parameter this parameter determines the granularity of the callback
by defining the maximum number of times the callback will be called
during the file transfer.
:type policy: :class:`boto.gs.acl.CannedACLStrings`
:param policy: A canned ACL policy that will be applied to the new key
in GS.
:type md5: A tuple containing the hexdigest version of the MD5 checksum
of the file as the first element and the Base64-encoded version of
the plain checksum as the second element. This is the same format
returned by the compute_md5 method.
:param md5: If you need to compute the MD5 for any reason prior to
upload, it's silly to have to do it twice so this param, if present,
will be used as the MD5 values of the file. Otherwise, the checksum
will be computed.
:type res_upload_handler: ResumableUploadHandler
:param res_upload_handler: If provided, this handler will perform the
upload.
:type if_generation: int
:param if_generation: (optional) If set to a generation number, the
object will only be written to if its current generation number is
this value. If set to the value 0, the object will only be written
if it doesn't already exist.
"""
# Clear out any previously computed hashes, since we are setting the
# content.
self.local_hashes = {}
with open(filename, 'rb') as fp:
self.set_contents_from_file(fp, headers, replace, cb, num_cb,
policy, md5, res_upload_handler,
if_generation=if_generation)
def set_contents_from_string(self, s, headers=None, replace=True,
cb=None, num_cb=10, policy=None, md5=None,
if_generation=None):
"""
Store an object in GCS using the name of the Key object as the
key in GCS and the string 's' as the contents.
See set_contents_from_file method for details about the
parameters.
:type headers: dict
:param headers: Additional headers to pass along with the
request to AWS.
:type replace: bool
:param replace: If True, replaces the contents of the file if
it already exists.
:type cb: function
:param cb: a callback function that will be called to report
progress on the upload. The callback should accept
two integer parameters, the first representing the
number of bytes that have been successfully
transmitted to GCS and the second representing the
size of the to be transmitted object.
:type cb: int
:param num_cb: (optional) If a callback is specified with
the cb parameter this parameter determines the
granularity of the callback by defining
the maximum number of times the callback will
be called during the file transfer.
:type policy: :class:`boto.gs.acl.CannedACLStrings`
:param policy: A canned ACL policy that will be applied to the
new key in GCS.
:type md5: A tuple containing the hexdigest version of the MD5
checksum of the file as the first element and the
Base64-encoded version of the plain checksum as the
second element. This is the same format returned by
the compute_md5 method.
:param md5: If you need to compute the MD5 for any reason prior
to upload, it's silly to have to do it twice so this
param, if present, will be used as the MD5 values
of the file. Otherwise, the checksum will be computed.
:type if_generation: int
:param if_generation: (optional) If set to a generation number, the
object will only be written to if its current generation number is
this value. If set to the value 0, the object will only be written
if it doesn't already exist.
"""
# Clear out any previously computed md5 hashes, since we are setting the content.
self.md5 = None
self.base64md5 = None
fp = StringIO.StringIO(get_utf8_value(s))
r = self.set_contents_from_file(fp, headers, replace, cb, num_cb,
policy, md5,
if_generation=if_generation)
fp.close()
return r
def set_contents_from_stream(self, *args, **kwargs):
"""
Store an object using the name of the Key object as the key in
cloud and the contents of the data stream pointed to by 'fp' as
the contents.
The stream object is not seekable and total size is not known.
This has the implication that we can't specify the
Content-Size and Content-MD5 in the header. So for huge
uploads, the delay in calculating MD5 is avoided but with a
penalty of inability to verify the integrity of the uploaded
data.
:type fp: file
:param fp: the file whose contents are to be uploaded
:type headers: dict
:param headers: additional HTTP headers to be sent with the
PUT request.
:type replace: bool
:param replace: If this parameter is False, the method will first check
to see if an object exists in the bucket with the same key. If it
does, it won't overwrite it. The default value is True which will
overwrite the object.
:type cb: function
:param cb: a callback function that will be called to report
progress on the upload. The callback should accept two integer
parameters, the first representing the number of bytes that have
been successfully transmitted to GS and the second representing the
total number of bytes that need to be transmitted.
:type num_cb: int
:param num_cb: (optional) If a callback is specified with the
cb parameter, this parameter determines the granularity of
the callback by defining the maximum number of times the
callback will be called during the file transfer.
:type policy: :class:`boto.gs.acl.CannedACLStrings`
:param policy: A canned ACL policy that will be applied to the new key
in GS.
:type size: int
:param size: (optional) The Maximum number of bytes to read from
the file pointer (fp). This is useful when uploading a
file in multiple parts where you are splitting the file up
into different ranges to be uploaded. If not specified,
the default behaviour is to read all bytes from the file
pointer. Less bytes may be available.
:type if_generation: int
:param if_generation: (optional) If set to a generation number, the
object will only be written to if its current generation number is
this value. If set to the value 0, the object will only be written
if it doesn't already exist.
"""
if_generation = kwargs.pop('if_generation', None)
if if_generation is not None:
headers = kwargs.get('headers', {})
headers['x-goog-if-generation-match'] = str(if_generation)
kwargs['headers'] = headers
super(Key, self).set_contents_from_stream(*args, **kwargs)
def set_acl(self, acl_or_str, headers=None, generation=None,
if_generation=None, if_metageneration=None):
"""Sets the ACL for this object.
:type acl_or_str: string or :class:`boto.gs.acl.ACL`
:param acl_or_str: A canned ACL string (see
:data:`~.gs.acl.CannedACLStrings`) or an ACL object.
:type headers: dict
:param headers: Additional headers to set during the request.
:type generation: int
:param generation: If specified, sets the ACL for a specific generation
of a versioned object. If not specified, the current version is
modified.
:type if_generation: int
:param if_generation: (optional) If set to a generation number, the acl
will only be updated if its current generation number is this value.
:type if_metageneration: int
:param if_metageneration: (optional) If set to a metageneration number,
the acl will only be updated if its current metageneration number is
this value.
"""
if self.bucket is not None:
self.bucket.set_acl(acl_or_str, self.name, headers=headers,
generation=generation,
if_generation=if_generation,
if_metageneration=if_metageneration)
def get_acl(self, headers=None, generation=None):
"""Returns the ACL of this object.
:param dict headers: Additional headers to set during the request.
:param int generation: If specified, gets the ACL for a specific
generation of a versioned object. If not specified, the current
version is returned.
:rtype: :class:`.gs.acl.ACL`
"""
if self.bucket is not None:
return self.bucket.get_acl(self.name, headers=headers,
generation=generation)
def get_xml_acl(self, headers=None, generation=None):
"""Returns the ACL string of this object.
:param dict headers: Additional headers to set during the request.
:param int generation: If specified, gets the ACL for a specific
generation of a versioned object. If not specified, the current
version is returned.
:rtype: str
"""
if self.bucket is not None:
return self.bucket.get_xml_acl(self.name, headers=headers,
generation=generation)
def set_xml_acl(self, acl_str, headers=None, generation=None,
if_generation=None, if_metageneration=None):
"""Sets this objects's ACL to an XML string.
:type acl_str: string
:param acl_str: A string containing the ACL XML.
:type headers: dict
:param headers: Additional headers to set during the request.
:type generation: int
:param generation: If specified, sets the ACL for a specific generation
of a versioned object. If not specified, the current version is
modified.
:type if_generation: int
:param if_generation: (optional) If set to a generation number, the acl
will only be updated if its current generation number is this value.
:type if_metageneration: int
:param if_metageneration: (optional) If set to a metageneration number,
the acl will only be updated if its current metageneration number is
this value.
"""
if self.bucket is not None:
return self.bucket.set_xml_acl(acl_str, self.name, headers=headers,
generation=generation,
if_generation=if_generation,
if_metageneration=if_metageneration)
def set_canned_acl(self, acl_str, headers=None, generation=None,
if_generation=None, if_metageneration=None):
"""Sets this objects's ACL using a predefined (canned) value.
:type acl_str: string
:param acl_str: A canned ACL string. See
:data:`~.gs.acl.CannedACLStrings`.
:type headers: dict
:param headers: Additional headers to set during the request.
:type generation: int
:param generation: If specified, sets the ACL for a specific generation
of a versioned object. If not specified, the current version is
modified.
:type if_generation: int
:param if_generation: (optional) If set to a generation number, the acl
will only be updated if its current generation number is this value.
:type if_metageneration: int
:param if_metageneration: (optional) If set to a metageneration number,
the acl will only be updated if its current metageneration number is
this value.
"""
if self.bucket is not None:
return self.bucket.set_canned_acl(
acl_str,
self.name,
headers=headers,
generation=generation,
if_generation=if_generation,
if_metageneration=if_metageneration
)
def compose(self, components, content_type=None, headers=None):
"""Create a new object from a sequence of existing objects.
The content of the object representing this Key will be the
concatenation of the given object sequence. For more detail, visit
https://developers.google.com/storage/docs/composite-objects
:type components list of Keys
:param components List of gs.Keys representing the component objects
:type content_type (optional) string
:param content_type Content type for the new composite object.
"""
compose_req = []
for key in components:
if key.bucket.name != self.bucket.name:
raise BotoClientError(
'GCS does not support inter-bucket composing')
generation_tag = ''
if key.generation:
generation_tag = ('<Generation>%s</Generation>'
% str(key.generation))
compose_req.append('<Component><Name>%s</Name>%s</Component>' %
(key.name, generation_tag))
compose_req_xml = ('<ComposeRequest>%s</ComposeRequest>' %
''.join(compose_req))
headers = headers or {}
if content_type:
headers['Content-Type'] = content_type
resp = self.bucket.connection.make_request(
'PUT', get_utf8_value(self.bucket.name), get_utf8_value(self.name),
headers=headers, query_args='compose',
data=get_utf8_value(compose_req_xml))
if resp.status < 200 or resp.status > 299:
raise self.bucket.connection.provider.storage_response_error(
resp.status, resp.reason, resp.read())
# Return the generation so that the result URI can be built with this
# for automatic parallel uploads.
return resp.getheader('x-goog-generation')
| {
"content_hash": "44f4f7a53ff94d41377817ab7628729a",
"timestamp": "",
"source": "github",
"line_count": 919,
"max_line_length": 91,
"avg_line_length": 45.05549510337323,
"alnum_prop": 0.597328889532918,
"repo_name": "ric03uec/boto",
"id": "277e7c715075e97fdba5bfbd6ea18387d00cea62",
"size": "42479",
"binary": false,
"copies": "4",
"ref": "refs/heads/develop",
"path": "boto/gs/key.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "5411612"
}
],
"symlink_target": ""
} |
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../sphinxext'))
sys.path.insert(0, os.path.abspath('../..'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'ipython_sphinxext.ipython_console_highlighting',
'ipython_sphinxext.ipython_directive',
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.intersphinx',
'numpydoc',
'plot_directive'
]
# Configuration parameters for plot_directive
plot_include_source = True
plot_html_show_formats = False
plot_html_show_source_link = False
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'sklearn-evaluation'
copyright = u'2016, Eduardo Blancas Reyes'
author = u'Eduardo Blancas Reyes'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
import re
import ast
_version_re = re.compile(r'__version__\s+=\s+(.*)')
with open('../../sklearn_evaluation/__init__.py', 'rb') as f:
VERSION = str(ast.literal_eval(_version_re.search(
f.read().decode('utf-8')).group(1)))
version = VERSION
# The full version, including alpha/beta/rc tags.
release = VERSION
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
#html_title = u'sklearn-evaluation v0.2'
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#html_last_updated_fmt = None
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'sklearn-evaluationdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'sklearn-evaluation.tex', u'sklearn-evaluation Documentation',
u'Eduardo Blancas Reyes', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'sklearn-evaluation', u'sklearn-evaluation Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'sklearn-evaluation', u'sklearn-evaluation Documentation',
author, 'sklearn-evaluation', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
intersphinx_mapping = {
'sklearn': ('http://scikit-learn.org/stable', None),
'matplotlib': ('http://matplotlib.org/', None),
}
numpydoc_show_class_members = False
| {
"content_hash": "174f4aa6843f119325d096958765c1ff",
"timestamp": "",
"source": "github",
"line_count": 305,
"max_line_length": 80,
"avg_line_length": 32.38032786885246,
"alnum_prop": 0.7055488051842851,
"repo_name": "edublancas/sklearn-model-evaluation",
"id": "fc05ad6a1c8b5dd190a45f7829f667db2379fd92",
"size": "10307",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/source/conf.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8484"
},
{
"name": "HTML",
"bytes": "364346"
},
{
"name": "Python",
"bytes": "48203"
}
],
"symlink_target": ""
} |
"""Simple diagnostic bandit environment.
Observation is a single pixel of 0 - this is an independent arm bandit problem!
Rewards are [0, 0.1, .. 1] assigned randomly to 11 arms and deterministic
"""
from typing import Optional
from bsuite.environments import base
from bsuite.experiments.bandit import sweep
import dm_env
from dm_env import specs
import numpy as np
class SimpleBandit(base.Environment):
"""SimpleBandit environment."""
def __init__(self, mapping_seed: Optional[int] = None, num_actions: int = 11):
"""Builds a simple bandit environment.
Args:
mapping_seed: Optional integer. Seed for action mapping.
num_actions: number of actions available, defaults to 11.
"""
super(SimpleBandit, self).__init__()
self._rng = np.random.RandomState(mapping_seed)
self._num_actions = num_actions
action_mask = self._rng.choice(
range(self._num_actions), size=self._num_actions, replace=False)
self._rewards = np.linspace(0, 1, self._num_actions)[action_mask]
self._total_regret = 0.
self._optimal_return = 1.
self.bsuite_num_episodes = sweep.NUM_EPISODES
def _get_observation(self):
return np.ones(shape=(1, 1), dtype=np.float32)
def _reset(self) -> dm_env.TimeStep:
observation = self._get_observation()
return dm_env.restart(observation)
def _step(self, action: int) -> dm_env.TimeStep:
reward = self._rewards[action]
self._total_regret += self._optimal_return - reward
observation = self._get_observation()
return dm_env.termination(reward=reward, observation=observation)
def observation_spec(self):
return specs.Array(shape=(1, 1), dtype=np.float32, name='observation')
def action_spec(self):
return specs.DiscreteArray(self._num_actions, name='action')
def bsuite_info(self):
return dict(total_regret=self._total_regret)
| {
"content_hash": "4e5bf4c8b96e0cffb9300f67257f803b",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 80,
"avg_line_length": 32.10344827586207,
"alnum_prop": 0.7019334049409237,
"repo_name": "deepmind/bsuite",
"id": "6365a9d1b3f47766d6e803498b5841b0b027a536",
"size": "2592",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "bsuite/environments/bandit.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "106470"
},
{
"name": "Python",
"bytes": "448602"
},
{
"name": "Shell",
"bytes": "2425"
},
{
"name": "TeX",
"bytes": "233184"
}
],
"symlink_target": ""
} |
from __future__ import print_function
from screenFlags import ScreenFlags
MANPAGE_HEADER = '''= fpp(1)
'''
MANPAGE_NAME_SECTION = '''
== NAME
fpp - Facebook PathPicker; a command line tool for selecting files out of bash output
'''
USAGE_INTRO_PRE = '''
Welcome to fpp, the Facebook PathPicker! We hope your stay
with us is enjoyable.
'''
MANPAGE_INTRO_PRE = '''
== INTRO
'''
INTRO = '''
To get started with fpp, pipe some kind of terminal output into the program.
Examples include:
* git status | fpp
* git show | fpp
* git diff HEAD master | fpp
* git diff HEAD~10 --numstat | fpp
* grep -r "Banana" . | fpp
* find . -iname "*.js" | fpp
Once fpp parses your input (and something that looks like a file matches), it
will put you inside a pager that will allow you to select files with the
following commands:
'''
USAGE_INTRO = USAGE_INTRO_PRE + INTRO
MANPAGE_SYNOPSIS = '''
== SYNOPSIS
'''
USAGE_PAGE_HEADER = '''
== Navigation ==
'''
USAGE_PAGE = '''
* [f] toggle the selection of a file
* [F] toggle and move downward by 1
* [A] toggle selection of all (unique) files
* [down arrow|j] move downward by 1
* [up arrow|k] move upward by 1
* [<space>] page down
* [b] page up
* [x] quick select mode
Once you have your files selected, you can
either open them in your favorite
text editor or execute commands with
them via command mode:
* [<Enter>] open all selected files
(or file under cursor if none selected)
in $EDITOR
* [c] enter command mode
'''
USAGE_COMMAND_HEADER = '''
== Command Mode ==
'''
USAGE_COMMAND = '''
Command mode is helpful when you want to
execute bash commands with the filenames
you have selected. By default the filenames
are appended automatically to command you
enter before it is executed, so all you have
to do is type the prefix. Some examples:
* git add
* git checkout HEAD~1 --
* rm -rf
These commands get formatted into:
* git add file1 file2 # etc
* git checkout HEAD~1 -- file1 file2
* rm -rf file1 file2 # etc
If your command needs filenames in the middle,
the token "$F" will be replaced with your
selected filenames if it is found in the command
string. Examples include:
* scp $F dev:~/backup
* mv $F ../over/here
Which format to:
* scp file1 file2 dev:~/backup
* mv file1 file2 ../over/here
'''
USAGE_CONFIGURATION = '''
== Configuration ==
PathPicker offers a bit of configuration currently with more to come
in the future.
~ Editor ~
The $FPP_EDITOR environment variable can be set to tell PathPicker
which editor to open the selected files with. If that variable
is not set, $VISUAL and then $EDITOR are used as fallbacks,
with "vim" as a last resort.
~ Colors ~
FPP will understand colors if the piped input uses them. In general, most
tools do not unless requested to do so.
For git, try `git config --global color.ui always` or use the command
line option --color.
For built in commands like `ls`, try `-G` (on Mac, additionally export
CLICOLOR_FORCE in your environment to anything.)
'''
USAGE_COMMAND_LINE = '''
== Command line arguments ==
PathPicker supports some command line arguments, as well.
'''
USAGE_TAIL = '''
That's a fairly in-depth overview of Facebook PathPicker.
We also provide help along the way as you
use the app, so don't worry and jump on in!
'''
USAGE_STR = USAGE_INTRO + \
USAGE_PAGE_HEADER + \
USAGE_PAGE + \
USAGE_COMMAND_HEADER + \
USAGE_COMMAND + \
USAGE_CONFIGURATION + \
USAGE_COMMAND_LINE + \
ScreenFlags.getArgParser().format_help() + \
USAGE_TAIL
decorator = '*' * 80
USAGE_STR = decorator + '\n' + USAGE_STR + '\n' + decorator
MANPAGE_STR = '\n\n'.join([
MANPAGE_HEADER,
MANPAGE_NAME_SECTION,
MANPAGE_SYNOPSIS,
# FIXME: asciidoc example block?
# http://www.methods.co.nz/asciidoc/userguide.html#X48
ScreenFlags.getArgParser().format_help(),
MANPAGE_INTRO_PRE,
INTRO,
USAGE_PAGE_HEADER,
USAGE_PAGE,
USAGE_COMMAND_HEADER,
USAGE_COMMAND,
USAGE_CONFIGURATION,
])
if __name__ == '__main__':
print(MANPAGE_STR)
| {
"content_hash": "e77635154448604e9eec03a4afd3686b",
"timestamp": "",
"source": "github",
"line_count": 178,
"max_line_length": 85,
"avg_line_length": 23.252808988764045,
"alnum_prop": 0.6764919062575502,
"repo_name": "slackorama/PathPicker",
"id": "cd6db3a861e1f7f5b4390965e01d99346909e9c7",
"size": "4436",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/usageStrings.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "5402"
},
{
"name": "HTML",
"bytes": "8026"
},
{
"name": "Python",
"bytes": "99464"
},
{
"name": "Ruby",
"bytes": "895"
},
{
"name": "Shell",
"bytes": "3623"
}
],
"symlink_target": ""
} |
from __future__ import print_function
import collections
import string
import sys
import threading
import time
import ddt
import mock
from six.moves import queue as Queue
import testtools
from rally.common import utils
from rally import exceptions
from tests.unit import test
class ImmutableMixinTestCase(test.TestCase):
def test_without_base_values(self):
im = utils.ImmutableMixin()
self.assertRaises(AttributeError,
im.__setattr__, "test", "test")
def test_with_base_values(self):
class A(utils.ImmutableMixin):
def __init__(self, test):
self.test = test
super(A, self).__init__()
a = A("test")
self.assertRaises(AttributeError,
a.__setattr__, "abc", "test")
self.assertEqual("test", a.test)
class EnumMixinTestCase(test.TestCase):
def test_enum_mix_in(self):
class Foo(utils.EnumMixin):
a = 10
b = 20
CC = "2000"
self.assertEqual(set([10, 20, "2000"]), set(list(Foo())))
def test_with_underscore(self):
class Foo(utils.EnumMixin):
a = 10
b = 20
_CC = "2000"
self.assertEqual(set([10, 20]), set(list(Foo())))
class StdIOCaptureTestCase(test.TestCase):
def test_stdout_capture(self):
stdout = sys.stdout
messages = ["abcdef", "defgaga"]
with utils.StdOutCapture() as out:
for msg in messages:
print(msg)
self.assertEqual(messages, out.getvalue().rstrip("\n").split("\n"))
self.assertEqual(sys.stdout, stdout)
def test_stderr_capture(self):
stderr = sys.stderr
messages = ["abcdef", "defgaga"]
with utils.StdErrCapture() as err:
for msg in messages:
print(msg, file=sys.stderr)
self.assertEqual(messages, err.getvalue().rstrip("\n").split("\n"))
self.assertEqual(sys.stderr, stderr)
class TimerTestCase(test.TestCase):
def test_timer_duration(self):
start_time = time.time()
end_time = time.time()
with mock.patch("rally.common.utils.time") as mock_time:
mock_time.time = mock.MagicMock(return_value=start_time)
with utils.Timer() as timer:
mock_time.time = mock.MagicMock(return_value=end_time)
self.assertIsNone(timer.error)
self.assertEqual(start_time, timer.timestamp())
self.assertEqual(end_time, timer.finish_timestamp())
self.assertEqual(end_time - start_time, timer.duration())
def test_timer_exception(self):
try:
with utils.Timer() as timer:
raise Exception()
except Exception:
pass
self.assertEqual(3, len(timer.error))
self.assertEqual(timer.error[0], type(Exception()))
def module_level_method():
pass
class MethodClassTestCase(test.TestCase):
@testtools.skipIf(sys.version_info > (2, 9), "Problems with access to "
"class from <locals>")
def test_method_class_for_class_level_method(self):
class A(object):
def m(self):
pass
self.assertEqual(A, utils.get_method_class(A.m))
def test_method_class_for_module_level_method(self):
self.assertIsNone(utils.get_method_class(module_level_method))
class FirstIndexTestCase(test.TestCase):
def test_list_with_existing_matching_element(self):
lst = [1, 3, 5, 7]
self.assertEqual(0, utils.first_index(lst, lambda e: e == 1))
self.assertEqual(2, utils.first_index(lst, lambda e: e == 5))
self.assertEqual(3, utils.first_index(lst, lambda e: e == 7))
def test_list_with_non_existing_matching_element(self):
lst = [1, 3, 5, 7]
self.assertIsNone(utils.first_index(lst, lambda e: e == 2))
class EditDistanceTestCase(test.TestCase):
def test_distance_empty_strings(self):
dist = utils.distance("", "")
self.assertEqual(0, dist)
def test_distance_equal_strings(self):
dist = utils.distance("abcde", "abcde")
self.assertEqual(0, dist)
def test_distance_replacement(self):
dist = utils.distance("abcde", "__cde")
self.assertEqual(2, dist)
def test_distance_insertion(self):
dist = utils.distance("abcde", "ab__cde")
self.assertEqual(2, dist)
def test_distance_deletion(self):
dist = utils.distance("abcde", "abc")
self.assertEqual(2, dist)
class TenantIteratorTestCase(test.TestCase):
def test_iterate_per_tenant(self):
users = []
tenants_count = 2
users_per_tenant = 5
for tenant_id in range(tenants_count):
for user_id in range(users_per_tenant):
users.append({"id": str(user_id),
"tenant_id": str(tenant_id)})
expected_result = [
({"id": "0", "tenant_id": str(i)}, str(i)) for i in range(
tenants_count)]
real_result = [i for i in utils.iterate_per_tenants(users)]
self.assertEqual(expected_result, real_result)
class RAMIntTestCase(test.TestCase):
def test__int__(self):
self.assertEqual(0, int(utils.RAMInt()))
self.assertEqual(10, int(utils.RAMInt(10)))
def test__str__(self):
self.assertEqual("0", str(utils.RAMInt()))
self.assertEqual("20", str(utils.RAMInt(20)))
def test__next__(self):
ri = utils.RAMInt()
for i in range(0, 3):
self.assertEqual(i, next(ri))
def test_next(self):
ri = utils.RAMInt()
for i in range(0, 3):
self.assertEqual(i, ri.next())
def test_reset(self):
ri = utils.RAMInt()
ri.next()
ri.reset()
self.assertEqual(0, int(ri))
@ddt.ddt
class RandomNameTestCase(test.TestCase):
@ddt.data(
{},
{"task_id": "fake-task"},
{"task_id": "2short", "expected": "s_rally_blargles_dweebled"},
{"task_id": "fake!task",
"expected": "s_rally_blargles_dweebled"},
{"fmt": "XXXX-test-XXX-test",
"expected": "fake-test-bla-test"})
@ddt.unpack
@mock.patch("random.choice")
def test_generate_random_name(self, mock_choice, task_id="faketask",
expected="s_rally_faketask_blargles",
fmt="s_rally_XXXXXXXX_XXXXXXXX"):
class FakeNameGenerator(utils.RandomNameGeneratorMixin):
RESOURCE_NAME_FORMAT = fmt
task = {"uuid": task_id}
generator = FakeNameGenerator()
mock_choice.side_effect = iter("blarglesdweebled")
self.assertEqual(expected, generator.generate_random_name())
class FakeNameGenerator(utils.RandomNameGeneratorMixin):
RESOURCE_NAME_FORMAT = fmt
verification = {"uuid": task_id}
generator = FakeNameGenerator()
mock_choice.side_effect = iter("blarglesdweebled")
self.assertEqual(expected, generator.generate_random_name())
def test_generate_random_name_bogus_name_format(self):
class FakeNameGenerator(utils.RandomNameGeneratorMixin):
RESOURCE_NAME_FORMAT = "invalid_XXX_format"
task = {"uuid": "fake-task-id"}
generator = FakeNameGenerator()
self.assertRaises(ValueError,
generator.generate_random_name)
@ddt.data(
{"good": ("rally_abcdefgh_abcdefgh", "rally_12345678_abcdefgh",
"rally_ABCdef12_ABCdef12"),
"bad": ("rally_abcd_efgh", "rally_abcd!efg_12345678",
"rally_", "rally__", "rally_abcdefgh_",
"rally_abcdefghi_12345678", "foo", "foo_abcdefgh_abcdefgh")},
{"task_id": "abcd1234",
"good": ("rally_abcd1234_abcdefgh", "rally_abcd1234_abcd1234",
"rally_abcd1234_AbCdEf12"),
"bad": ("rally_12345678_abcdefgh", "rally_12345678_abcd1234",
"rally_abcd1234_", "rally_abcd1234_!!!!!!!!",
"rally_ABCD1234_abcdefgh")},
{"task_id": "abcd1234",
"exact": False,
"good": ("rally_abcd1234_abcdefghfoo", "rally_abcd1234_abcdefgh",
"rally_abcd1234_abcdefgh-bar",
"rally_abcd1234_abcdefgh+!@$"),
"bad": ("rally_abcd1234_", "rally_abcd1234_!!!!!!!!",
"rally_abcd1234_abcdefg")},
{"fmt": "][*_XXX_XXX",
"chars": "abc(.*)",
"good": ("][*_abc_abc", "][*_abc_((("),
"bad": ("rally_ab_cd", "rally_ab!_abc", "rally_", "rally__",
"rally_abc_", "rally_abcd_abc", "foo", "foo_abc_abc")},
{"fmt": "XXXX-test-XXX-test",
"good": ("abcd-test-abc-test",),
"bad": ("rally-abcdefgh-abcdefgh", "abc-test-abc-test",
"abcd_test_abc_test", "abc-test-abcd-test")})
@ddt.unpack
def test_cls_name_matches_object(
self, good=(), bad=(), fmt="rally_XXXXXXXX_XXXXXXXX",
chars=string.ascii_letters + string.digits, task_id=None,
exact=True):
class FakeNameGenerator(utils.RandomNameGeneratorMixin):
RESOURCE_NAME_FORMAT = fmt
RESOURCE_NAME_ALLOWED_CHARACTERS = chars
task = {"uuid": task_id or "fakeuuid"}
for name in good:
self.assertTrue(
FakeNameGenerator.name_matches_object(name, task_id, exact),
"%(name)s unexpectedly didn't match RESOURCE_NAME_FORMAT "
"%(fmt)s with exact=%(exact)s" %
{"name": name, "fmt": fmt, "exact": exact})
for name in bad:
self.assertFalse(
FakeNameGenerator.name_matches_object(name, task_id, exact),
"%(name)s unexpectedly matched RESOURCE_NAME_FORMAT %(fmt)s "
"with exact=%(exact)s" %
{"name": name, "fmt": fmt, "exact": exact})
def test_name_matches_object(self):
name = "foo"
obj = mock.Mock()
self.assertTrue(utils.name_matches_object(name, obj))
obj.name_matches_object.assert_called_once_with(name)
def test_name_matches_object_kwargs(self):
name = "foo"
obj = mock.Mock()
self.assertTrue(utils.name_matches_object(name, obj, task_id="taskid",
exact=False))
obj.name_matches_object.assert_called_once_with(name, task_id="taskid",
exact=False)
def test_name_matches_object_identical_list(self):
class One(utils.RandomNameGeneratorMixin):
name_matches_object = mock.Mock(return_value=False)
class Two(utils.RandomNameGeneratorMixin):
name_matches_object = mock.Mock(return_value=False)
name = "foo"
self.assertFalse(utils.name_matches_object(name, One, Two))
# ensure that exactly one of the two objects is checked
self.assertItemsEqual(
One.name_matches_object.call_args_list +
Two.name_matches_object.call_args_list,
[mock.call(name)])
def test_name_matches_object_differing_list(self):
class One(utils.RandomNameGeneratorMixin):
name_matches_object = mock.Mock(return_value=False)
class Two(utils.RandomNameGeneratorMixin):
RESOURCE_NAME_FORMAT = "foo_XXX_XXX"
name_matches_object = mock.Mock(return_value=False)
class Three(utils.RandomNameGeneratorMixin):
RESOURCE_NAME_ALLOWED_CHARACTERS = "12345"
name_matches_object = mock.Mock(return_value=False)
class Four(utils.RandomNameGeneratorMixin):
RESOURCE_NAME_FORMAT = "bar_XXX_XXX"
RESOURCE_NAME_ALLOWED_CHARACTERS = "abcdef"
name_matches_object = mock.Mock(return_value=False)
classes = (One, Two, Three, Four)
name = "foo"
self.assertFalse(utils.name_matches_object(name, *classes))
for cls in classes:
cls.name_matches_object.assert_called_once_with(name)
def test_cls_name_matches_object_identity(self):
generator = utils.RandomNameGeneratorMixin()
generator.task = {"uuid": "faketask"}
self.assertTrue(generator.name_matches_object(
generator.generate_random_name()))
self.assertTrue(utils.RandomNameGeneratorMixin.name_matches_object(
generator.generate_random_name()))
def test_name_matches_object_identity(self):
generator = utils.RandomNameGeneratorMixin()
generator.task = {"uuid": "faketask"}
self.assertTrue(utils.name_matches_object(
generator.generate_random_name(), generator))
self.assertTrue(utils.name_matches_object(
generator.generate_random_name(), utils.RandomNameGeneratorMixin))
def test_consistent_task_id_part(self):
class FakeNameGenerator(utils.RandomNameGeneratorMixin):
RESOURCE_NAME_FORMAT = "XXXXXXXX_XXXXXXXX"
generator = FakeNameGenerator()
generator.task = {"uuid": "good-task-id"}
names = [generator.generate_random_name() for i in range(100)]
task_id_parts = set([n.split("_")[0] for n in names])
self.assertEqual(1, len(task_id_parts))
generator.task = {"uuid": "bogus! task! id!"}
names = [generator.generate_random_name() for i in range(100)]
task_id_parts = set([n.split("_")[0] for n in names])
self.assertEqual(1, len(task_id_parts))
def test_make_name_matcher(self):
matcher = utils.make_name_matcher("foo", "bar")
self.assertTrue(matcher.name_matches_object("foo", task_id="task"))
self.assertTrue(matcher.name_matches_object("bar", task_id="task"))
self.assertFalse(matcher.name_matches_object("foo1", task_id="task"))
@ddt.ddt
class MergeTestCase(test.TestCase):
@ddt.data(
# regular data
{"sources": [[[1, 3, 5], [5, 7, 9, 14], [17, 21, 36, 41]],
[[2, 2, 4], [9, 10], [16, 19, 23, 26, 91]],
[[5], [5, 7, 11, 14, 14, 19, 23]]],
"expected_output": [[1, 2, 2, 3, 4, 5, 5, 5, 5, 7],
[7, 9, 9, 10, 11, 14, 14, 14, 16, 17],
[19, 19, 21, 23, 23, 26, 36, 41, 91]]},
# with one empty source
{"sources": [[[1, 3, 5], [5, 7, 9, 14], [17, 21, 36, 41]],
[[2, 2, 4], [9, 10], [16, 19, 23, 26, 91]],
[[5], [5, 7, 11, 14, 14, 19, 23]],
[]],
"expected_output": [[1, 2, 2, 3, 4, 5, 5, 5, 5, 7],
[7, 9, 9, 10, 11, 14, 14, 14, 16, 17],
[19, 19, 21, 23, 23, 26, 36, 41, 91]]},
# with one source that produces an empty list
{"sources": [[[1, 3, 5], [5, 7, 9, 14], [17, 21, 36, 41]],
[[2, 2, 4], [9, 10], [16, 19, 23, 26, 91]],
[[5], [5, 7, 11, 14, 14, 19, 23]],
[[]]],
"expected_output": [[1, 2, 2, 3, 4, 5, 5, 5, 5, 7],
[7, 9, 9, 10, 11, 14, 14, 14, 16, 17],
[19, 19, 21, 23, 23, 26, 36, 41, 91]]},
# with empty lists appered in sources
{"sources": [[[1, 3, 5], [], [], [5, 7, 9, 14], [17, 21, 36, 41]],
[[], [2, 2, 4], [9, 10], [16, 19, 23, 26, 91]],
[[5], [5, 7, 11, 14, 14, 19, 23], []]],
"expected_output": [[1, 2, 2, 3, 4, 5, 5, 5, 5, 7],
[7, 9, 9, 10, 11, 14, 14, 14, 16, 17],
[19, 19, 21, 23, 23, 26, 36, 41, 91]]},
# only one source
{"sources": [[[1, 3, 5], [5, 7, 9, 14], [17, 21, 36, 41]]],
"expected_output": [[1, 3, 5, 5, 7, 9, 14, 17, 21, 36], [41]]},
# no sources passed in
{"sources": [],
"expected_output": []},
# several sources, all empty
{"sources": [[], [], [], []],
"expected_output": []}
)
@ddt.unpack
def test_merge(self, sources, expected_output):
in_iters = [iter(src) for src in sources]
out = list(utils.merge(10, *in_iters))
self.assertEqual(expected_output, out)
class TimeoutThreadTestCase(test.TestCase):
def test_timeout_thread(self):
"""Create and kill thread by timeout.
This single test covers 3 methods: terminate_thread, timeout_thread,
and interruptable_sleep.
This test is more like integrated then unit, but it is much better
then unreadable 500 lines of mocking and checking.
"""
queue = Queue.Queue()
killer_thread = threading.Thread(
target=utils.timeout_thread,
args=(queue,),
)
test_thread = threading.Thread(
target=utils.interruptable_sleep,
args=(30, 0.01),
)
test_thread.start()
start_time = time.time()
queue.put((test_thread, start_time + 1))
killer_thread.start()
test_thread.join()
end_time = time.time()
queue.put((None, None))
killer_thread.join()
time_elapsed = end_time - start_time
# NOTE(sskripnick): Killing thread with PyThreadState_SetAsyncExc
# works with sinificant delay. Make sure this delay is less
# than 10 seconds.
self.assertLess(time_elapsed, 11,
"Thread killed too late (%s seconds)" % time_elapsed)
class LockedDictTestCase(test.TestCase):
def test_init_unlock_and_update(self):
def setitem(obj, key, value):
obj[key] = value
def delitem(obj, key):
del obj[key]
d = utils.LockedDict()
self.assertIsInstance(d, dict)
self.assertEqual({}, d)
d = utils.LockedDict(foo="bar", spam={"a": ["b", {"c": "d"}]})
self.assertEqual({"foo": "bar", "spam": {"a": ("b", {"c": "d"})}}, d)
self.assertIsInstance(d["spam"], utils.LockedDict)
self.assertIsInstance(d["spam"]["a"][1], utils.LockedDict)
self.assertRaises(RuntimeError, setitem, d, 123, 456)
self.assertRaises(RuntimeError, delitem, d, "foo")
self.assertRaises(RuntimeError, setitem, d["spam"]["a"][1], 123, 456)
self.assertRaises(RuntimeError, delitem, d["spam"]["a"][1], "c")
self.assertRaises(RuntimeError, d.update, {123: 456})
self.assertRaises(RuntimeError, d.setdefault, 123, 456)
self.assertRaises(RuntimeError, d.pop, "foo")
self.assertRaises(RuntimeError, d.popitem)
self.assertRaises(RuntimeError, d.clear)
self.assertEqual({"foo": "bar", "spam": {"a": ("b", {"c": "d"})}}, d)
with d.unlocked():
d["spam"] = 42
self.assertEqual({"foo": "bar", "spam": 42}, d)
d.clear()
self.assertEqual({}, d)
d.setdefault("foo", 42)
d.update({"bar": 24})
self.assertEqual({"foo": 42, "bar": 24}, d)
self.assertEqual(24, d.pop("bar"))
self.assertEqual(("foo", 42), d.popitem())
d[123] = 456
self.assertEqual({123: 456}, d)
self.assertRaises(RuntimeError, setitem, d, 123, 456)
self.assertRaises(RuntimeError, delitem, d, "foo")
@mock.patch("rally.common.utils.copy.deepcopy")
def test___deepcopy__(self, mock_deepcopy):
mock_deepcopy.side_effect = lambda *args, **kw: (args, kw)
d = utils.LockedDict(foo="bar", spam={"a": ["b", {"c": "d"}]})
args, kw = d.__deepcopy__()
self.assertEqual({"memo": None}, kw)
self.assertEqual(({"foo": "bar", "spam": {"a": ("b", {"c": "d"})}},),
args)
self.assertEqual(dict, type(args[0]))
self.assertEqual(dict, type(args[0]["spam"]))
self.assertEqual(dict, type(args[0]["spam"]["a"][1]))
mock_deepcopy.reset_mock()
args, kw = d.__deepcopy__("foo_memo")
self.assertEqual(({"foo": "bar", "spam": {"a": ("b", {"c": "d"})}},),
args)
self.assertEqual({"memo": "foo_memo"}, kw)
@ddt.ddt
class FloatFormatterTestCase(test.TestCase):
@ddt.data(
{
"num_float": 0,
"num_str": "0.0"
},
{
"num_float": 37,
"num_str": "37.0"
},
{
"num_float": 0.0000001,
"num_str": "0.0"
},
{
"num_float": 0.000000,
"num_str": "0.0"
},
{
"num_float": 1.0000001,
"num_str": "1.0"
},
{
"num_float": 1.0000011,
"num_str": "1.000001"
},
{
"num_float": 1.0000019,
"num_str": "1.000002"
}
)
@ddt.unpack
def test_format_float_to_str(self, num_float, num_str):
self.assertEqual(num_str, utils.format_float_to_str(num_float))
class DequeAsQueueTestCase(test.TestCase):
def setUp(self):
super(DequeAsQueueTestCase, self).setUp()
self.deque = collections.deque()
self.deque_as_queue = utils.DequeAsQueue(self.deque)
def test_qsize(self):
self.assertEqual(0, self.deque_as_queue.qsize())
self.deque.append(10)
self.assertEqual(1, self.deque_as_queue.qsize())
def test_put(self):
self.deque_as_queue.put(10)
self.assertEqual(10, self.deque.popleft())
def test_get(self):
self.deque.append(33)
self.assertEqual(33, self.deque_as_queue.get())
def test_empty(self):
self.assertFalse(self.deque_as_queue.empty())
self.deque.append(10)
self.assertTrue(self.deque_as_queue.empty())
class StopwatchTestCase(test.TestCase):
@mock.patch("rally.common.utils.interruptable_sleep")
@mock.patch("rally.common.utils.time")
def test_stopwatch(self, mock_time, mock_interruptable_sleep):
mock_time.time.side_effect = [0, 0, 1, 2, 3]
sw = utils.Stopwatch()
sw.start()
sw.sleep(1)
sw.sleep(2)
sw.sleep(3)
mock_interruptable_sleep.assert_has_calls([
mock.call(1),
mock.call(1),
mock.call(1),
])
@mock.patch("rally.common.utils.interruptable_sleep")
@mock.patch("rally.common.utils.time")
def test_no_sleep(self, mock_time, mock_interruptable_sleep):
mock_time.time.side_effect = [0, 1]
sw = utils.Stopwatch()
sw.start()
sw.sleep(1)
self.assertFalse(mock_interruptable_sleep.called)
@mock.patch("rally.common.utils.time")
def test_stopwatch_with_event(self, mock_time):
mock_time.time.side_effect = [0, 0, 1, 2, 3]
event = mock.Mock(spec=threading.Event)()
sw = utils.Stopwatch(stop_event=event)
sw.start()
sw.sleep(1)
sw.sleep(2)
sw.sleep(3)
event.wait.assert_has_calls([
mock.call(1),
mock.call(1),
mock.call(1),
])
class BackupTestCase(test.TestCase):
def setUp(self):
super(BackupTestCase, self).setUp()
p = mock.patch("rally.common.utils.os.mkdir")
self.mock_mkdir = p.start()
self.addCleanup(p.stop)
@mock.patch("rally.common.utils.os.path.exists")
@mock.patch("rally.common.utils.uuid")
def test_generate_random_path(self, mock_uuid, mock_exists):
mock_exists.side_effect = lambda a: "exist" in a
mock_uuid.uuid4.side_effect = ("exist", "foo")
self.assertEqual("/some/foo", utils.generate_random_path("/some"))
mock_exists.assert_has_calls((
mock.call("/some/exist"),
mock.call("/some/foo"),
))
@mock.patch("rally.common.utils.generate_random_path")
def test___init__(self, mock_generate_random_path):
utils.BackupHelper()
mock_generate_random_path.assert_called_once_with()
self.mock_mkdir.assert_called_once_with(
mock_generate_random_path.return_value)
@mock.patch("rally.common.utils.generate_random_path")
@mock.patch("rally.common.utils.shutil.copytree")
def test_backup(self, mock_copytree, mock_generate_random_path):
backup_dir = "another_dir"
mock_generate_random_path.side_effect = ("base_tmp_dir", backup_dir)
bh = utils.BackupHelper()
path = "some_path"
bh.backup(path)
mock_copytree.assert_called_once_with(path, backup_dir, symlinks=True)
self.assertEqual(backup_dir, bh._stored_data[path])
mock_copytree.reset_mock()
self.assertRaises(exceptions.RallyException, bh.backup, path)
self.assertFalse(mock_copytree.called)
@mock.patch("rally.common.utils.BackupHelper.rollback")
@mock.patch("rally.common.utils.generate_random_path")
@mock.patch("rally.common.utils.shutil.copytree")
def test_backup_failed_while_copy(self, mock_copytree,
mock_generate_random_path,
mock_backup_helper_rollback):
backup_dir = "another_dir"
mock_generate_random_path.side_effect = ("base_tmp_dir", backup_dir)
mock_copytree.side_effect = RuntimeError
bh = utils.BackupHelper()
path = "some_path"
self.assertRaises(RuntimeError, bh.backup, path)
mock_copytree.assert_called_once_with(path, backup_dir, symlinks=True)
self.assertTrue(not bh._stored_data)
mock_backup_helper_rollback.assert_called_once_with()
@mock.patch("rally.common.utils.BackupHelper.backup")
def test_call(self, mock_backup_helper_backup):
path = "/some/path"
bh = utils.BackupHelper()
self.assertEqual(bh, bh(path))
mock_backup_helper_backup.assert_called_once_with(path)
@mock.patch("rally.common.utils."
"os.path.exists", side_effect=(False, True, True))
@mock.patch("rally.common.utils.shutil.rmtree")
def test___del__(self, mock_rmtree, mock_exists):
paths = {"original_path": "/tmp/backup_of_something",
"another_path": "/tmp/backup_of_another_thing"}
bh = utils.BackupHelper()
bh._stored_data = paths
del bh
self.assertEqual([mock.call(p) for p in paths.values()],
mock_rmtree.call_args_list)
@mock.patch("rally.common.utils.os.path.exists", side_effect=(False, True))
@mock.patch("rally.common.utils.shutil.rmtree")
@mock.patch("rally.common.utils.shutil.copytree")
def test_rollback(self, mock_copytree, mock_rmtree, mock_exists):
bh = utils.BackupHelper()
original_path = "/some/original/path"
tmp_path = "/temporary/location/for/backup"
path = {original_path: tmp_path}
bh._stored_data = path
rollback_method = mock.MagicMock()
args = (1, 2, 3)
kwargs = {"arg1": "value"}
bh.add_rollback_action(rollback_method, *args, **kwargs)
bh.rollback()
mock_rmtree.assert_called_once_with(original_path)
mock_copytree.assert_called_once_with(tmp_path, original_path,
symlinks=True)
self.assertTrue(not bh._stored_data)
rollback_method.assert_called_once_with(*args, **kwargs)
@mock.patch("rally.common.utils.BackupHelper.rollback")
def test_context_manager(self, mock_backup_helper_rollback):
bh = utils.BackupHelper()
with bh:
pass
self.assertFalse(mock_backup_helper_rollback.called)
bh = utils.BackupHelper()
try:
with bh:
raise RuntimeError()
except RuntimeError:
# it is expected behaviour
pass
else:
self.fail("BackupHelper context manager should not hide "
"an exception")
self.assertTrue(mock_backup_helper_rollback.called)
| {
"content_hash": "f36461d6a4a82abbd279c51258520942",
"timestamp": "",
"source": "github",
"line_count": 790,
"max_line_length": 79,
"avg_line_length": 35.562025316455696,
"alnum_prop": 0.5621840962483092,
"repo_name": "yeming233/rally",
"id": "e21fa50f83b8bfc3c45594a839fae8d7ff0acf23",
"size": "28723",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/unit/common/test_utils.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Mako",
"bytes": "46940"
},
{
"name": "Python",
"bytes": "2561223"
},
{
"name": "Shell",
"bytes": "43366"
}
],
"symlink_target": ""
} |
c.NotebookApp.open_browser = False
# Hashed password to use for web authentication.
#
# To generate, type in a python/IPython shell:
#
# from notebook.auth import passwd; passwd()
#
# The string should be of the form type:salt:hashed-password.
# c.NotebookApp.password = u''
# extra paths to look for Javascript notebook extensions
# c.NotebookApp.extra_nbextensions_path = traitlets.Undefined
# Set the Access-Control-Allow-Credentials: true header
# c.NotebookApp.allow_credentials = False
# Extra paths to search for serving static files.
#
# This allows adding javascript/css to be available from the notebook server
# machine, or overriding individual files in the IPython
# c.NotebookApp.extra_static_paths = traitlets.Undefined
# The login handler class to use.
# c.NotebookApp.login_handler_class = <class 'notebook.auth.login.LoginHandler'>
# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy. Necessary if the proxy handles
# SSL
# c.NotebookApp.trust_xheaders = False
# Extra paths to search for serving jinja templates.
#
# Can be used to override templates from notebook.templates.
# c.NotebookApp.extra_template_paths = traitlets.Undefined
# The config manager class to use
# c.NotebookApp.config_manager_class = <class 'notebook.services.config.manager.ConfigManager'>
# The full path to a private key file for usage with SSL/TLS.
# c.NotebookApp.keyfile = u''
# DEPRECATED, use tornado_settings
# c.NotebookApp.webapp_settings = traitlets.Undefined
# Specify what command to use to invoke a web browser when opening the notebook.
# If not specified, the default browser will be determined by the `webbrowser`
# standard library module, which allows setting of the BROWSER environment
# variable to override it.
# c.NotebookApp.browser = u''
#------------------------------------------------------------------------------
# LoggingConfigurable configuration
#------------------------------------------------------------------------------
# A parent class for Configurables that log.
#
# Subclasses have a log trait, and the default behavior is to get the logger
# from the currently running Application.
#------------------------------------------------------------------------------
# ConnectionFileMixin configuration
#------------------------------------------------------------------------------
# Mixin for configurable classes that work with connection files
# set the stdin (ROUTER) port [default: random]
# c.ConnectionFileMixin.stdin_port = 0
# Set the kernel's IP address [default localhost]. If the IP address is
# something other than localhost, then Consoles on other machines will be able
# to connect to the Kernel, so be careful!
# c.ConnectionFileMixin.ip = u''
# JSON file in which to store connection info [default: kernel-<pid>.json]
#
# This file will contain the IP, ports, and authentication key needed to connect
# clients to this kernel. By default, this file will be created in the security
# dir of the current profile, but can be specified by absolute path.
# c.ConnectionFileMixin.connection_file = ''
# set the control (ROUTER) port [default: random]
# c.ConnectionFileMixin.control_port = 0
# set the heartbeat port [default: random]
# c.ConnectionFileMixin.hb_port = 0
# set the shell (ROUTER) port [default: random]
# c.ConnectionFileMixin.shell_port = 0
#
# c.ConnectionFileMixin.transport = 'tcp'
# set the iopub (PUB) port [default: random]
# c.ConnectionFileMixin.iopub_port = 0
#------------------------------------------------------------------------------
# KernelManager configuration
#------------------------------------------------------------------------------
# Manages a single kernel in a subprocess on this host.
#
# This version starts kernels with Popen.
# DEPRECATED: Use kernel_name instead.
#
# The Popen Command to launch the kernel. Override this if you have a custom
# kernel. If kernel_cmd is specified in a configuration file, Jupyter does not
# pass any arguments to the kernel, because it cannot make any assumptions about
# the arguments that the kernel understands. In particular, this means that the
# kernel does not receive the option --debug if it given on the Jupyter command
# line.
# c.KernelManager.kernel_cmd = traitlets.Undefined
# Should we autorestart the kernel if it dies.
# c.KernelManager.autorestart = False
#------------------------------------------------------------------------------
# Session configuration
#------------------------------------------------------------------------------
# Object for handling serialization and sending of messages.
#
# The Session object handles building messages and sending them with ZMQ sockets
# or ZMQStream objects. Objects can communicate with each other over the
# network via Session objects, and only need to work with the dict-based IPython
# message spec. The Session will handle serialization/deserialization, security,
# and metadata.
#
# Sessions support configurable serialization via packer/unpacker traits, and
# signing with HMAC digests via the key/keyfile traits.
#
# Parameters ----------
#
# debug : bool
# whether to trigger extra debugging statements
# packer/unpacker : str : 'json', 'pickle' or import_string
# importstrings for methods to serialize message parts. If just
# 'json' or 'pickle', predefined JSON and pickle packers will be used.
# Otherwise, the entire importstring must be used.
#
# The functions must accept at least valid JSON input, and output *bytes*.
#
# For example, to use msgpack:
# packer = 'msgpack.packb', unpacker='msgpack.unpackb'
# pack/unpack : callables
# You can also set the pack/unpack callables for serialization directly.
# session : bytes
# the ID of this Session object. The default is to generate a new UUID.
# username : unicode
# username added to message headers. The default is to ask the OS.
# key : bytes
# The key used to initialize an HMAC signature. If unset, messages
# will not be signed or checked.
# keyfile : filepath
# The file containing a key. If this is set, `key` will be initialized
# to the contents of the file.
# Username for the Session. Default is your system username.
# c.Session.username = u'philippjfr'
# Threshold (in bytes) beyond which a buffer should be sent without copying.
# c.Session.copy_threshold = 65536
# The name of the packer for serializing messages. Should be one of 'json',
# 'pickle', or an import name for a custom callable serializer.
# c.Session.packer = 'json'
# Metadata dictionary, which serves as the default top-level metadata dict for
# each message.
# c.Session.metadata = traitlets.Undefined
# The maximum number of digests to remember.
#
# The digest history will be culled when it exceeds this value.
# c.Session.digest_history_size = 65536
# The UUID identifying this session.
# c.Session.session = u''
# The digest scheme used to construct the message signatures. Must have the form
# 'hmac-HASH'.
# c.Session.signature_scheme = 'hmac-sha256'
# execution key, for signing messages.
# c.Session.key = ''
# Debug output in the Session
# c.Session.debug = False
# The name of the unpacker for unserializing messages. Only used with custom
# functions for `packer`.
# c.Session.unpacker = 'json'
# path to file containing execution key.
# c.Session.keyfile = ''
# Threshold (in bytes) beyond which an object's buffer should be extracted to
# avoid pickling.
# c.Session.buffer_threshold = 1024
# The maximum number of items for a container to be introspected for custom
# serialization. Containers larger than this are pickled outright.
# c.Session.item_threshold = 64
#------------------------------------------------------------------------------
# MultiKernelManager configuration
#------------------------------------------------------------------------------
# A class for managing multiple kernels.
# The name of the default kernel to start
# c.MultiKernelManager.default_kernel_name = 'python2'
# The kernel manager class. This is configurable to allow subclassing of the
# KernelManager for customized behavior.
# c.MultiKernelManager.kernel_manager_class = 'jupyter_client.ioloop.IOLoopKernelManager'
#------------------------------------------------------------------------------
# MappingKernelManager configuration
#------------------------------------------------------------------------------
# A KernelManager that handles notebook mapping and HTTP error handling
#
# c.MappingKernelManager.root_dir = u''
#------------------------------------------------------------------------------
# ContentsManager configuration
#------------------------------------------------------------------------------
# Base class for serving files and directories.
#
# This serves any text or binary file, as well as directories, with special
# handling for JSON notebook documents.
#
# Most APIs take a path argument, which is always an API-style unicode path, and
# always refers to a directory.
#
# - unicode, not url-escaped
# - '/'-separated
# - leading and trailing '/' will be stripped
# - if unspecified, path defaults to '',
# indicating the root path.
# The base name used when creating untitled files.
# c.ContentsManager.untitled_file = 'untitled'
# Python callable or importstring thereof
#
# To be called on a contents model prior to save.
#
# This can be used to process the structure, such as removing notebook outputs
# or other side effects that should not be saved.
#
# It will be called as (all arguments passed by keyword)::
#
# hook(path=path, model=model, contents_manager=self)
#
# - model: the model to be saved. Includes file contents.
# Modifying this dict will affect the file that is stored.
# - path: the API path of the save destination
# - contents_manager: this ContentsManager instance
# c.ContentsManager.pre_save_hook = None
#
# c.ContentsManager.checkpoints_class = <class 'notebook.services.contents.checkpoints.Checkpoints'>
# Glob patterns to hide in file and directory listings.
# c.ContentsManager.hide_globs = traitlets.Undefined
# The base name used when creating untitled notebooks.
# c.ContentsManager.untitled_notebook = 'Untitled'
# The base name used when creating untitled directories.
# c.ContentsManager.untitled_directory = 'Untitled Folder'
#
# c.ContentsManager.checkpoints = traitlets.Undefined
#
# c.ContentsManager.checkpoints_kwargs = traitlets.Undefined
#------------------------------------------------------------------------------
# FileContentsManager configuration
#------------------------------------------------------------------------------
# DEPRECATED, use post_save_hook
# c.FileContentsManager.save_script = False
#
# c.FileContentsManager.root_dir = u''
# Python callable or importstring thereof
#
# to be called on the path of a file just saved.
#
# This can be used to process the file on disk, such as converting the notebook
# to a script or HTML via nbconvert.
#
# It will be called as (all arguments passed by keyword)::
#
# hook(os_path=os_path, model=model, contents_manager=instance)
#
# - path: the filesystem path to the file just written - model: the model
# representing the file - contents_manager: this ContentsManager instance
# c.FileContentsManager.post_save_hook = None
#------------------------------------------------------------------------------
# NotebookNotary configuration
#------------------------------------------------------------------------------
# A class for computing and verifying notebook signatures.
# The number of notebook signatures to cache. When the number of signatures
# exceeds this value, the oldest 25% of signatures will be culled.
# c.NotebookNotary.cache_size = 65535
# The secret key with which notebooks are signed.
# c.NotebookNotary.secret = ''
# The sqlite file in which to store notebook signatures. By default, this will
# be in your Jupyter runtime directory. You can set it to ':memory:' to disable
# sqlite writing to the filesystem.
# c.NotebookNotary.db_file = u''
# The hashing algorithm used to sign notebooks.
# c.NotebookNotary.algorithm = 'sha256'
# The file where the secret key is stored.
# c.NotebookNotary.secret_file = u''
#------------------------------------------------------------------------------
# KernelSpecManager configuration
#------------------------------------------------------------------------------
# Whitelist of allowed kernel names.
#
# By default, all installed kernels are allowed.
# c.KernelSpecManager.whitelist = traitlets.Undefined
c.InteractiveShellApp.extra_extension = 'topo.misc.ipython'
| {
"content_hash": "6405594e2c5acb2336961eb257ce725d",
"timestamp": "",
"source": "github",
"line_count": 342,
"max_line_length": 100,
"avg_line_length": 37.08479532163743,
"alnum_prop": 0.6610423401403454,
"repo_name": "ioam/topographica",
"id": "7c4b4c848d08b6796e7fae973360d60f5ae82c46",
"size": "19062",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "platform/jupyter/jupyter_notebook_config.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "14889"
},
{
"name": "C++",
"bytes": "5714"
},
{
"name": "Elixir",
"bytes": "202"
},
{
"name": "JavaScript",
"bytes": "122"
},
{
"name": "Jupyter Notebook",
"bytes": "7580101"
},
{
"name": "Makefile",
"bytes": "15490"
},
{
"name": "Python",
"bytes": "1681956"
},
{
"name": "Shell",
"bytes": "1577"
},
{
"name": "TeX",
"bytes": "253834"
}
],
"symlink_target": ""
} |
"""
.. module:: parser_mp
:synopsis: Definition of the command line options
.. moduleauthor:: Benjamin Audren <benjamin.audren@epfl.ch>
.. moduleauthor:: Francesco Montesano <franz.bergesund@gmail.com>
Defines the command line options and their help messages in
:func:`create_parser` and read the input command line in :func:`parse`, dealing
with different possible configurations.
The fancy short/long help formatting, as well as the automatic help creation
from docstrings is entirely due to Francesco Montesano.
"""
import os
import sys
import textwrap as tw
import re
import argparse as ap # Python module to handle command line arguments
import warnings
import io_mp
# -- custom Argument Parser that throws an io_mp.ConfigurationError
# -- for unified look within montepython
class MpArgumentParser(ap.ArgumentParser):
"""Extension of the default ArgumentParser"""
def error(self, message):
"""Override method to raise error
Parameters
----------
message: string
error message
"""
raise io_mp.ConfigurationError(message)
def safe_parse_args(self, args=None):
"""
Allows to set a default subparser
This trick is there to maintain the previous way of calling
MontePython.py
"""
args = self.set_default_subparser('run', args)
return self.parse_args(args)
def set_default_subparser(self, default, args=None):
"""
If no subparser option is found, add the default one
.. note::
This function relies on the fact that all calls to MontePython will
start with a `-`. If this came to change, this function should be
revisited
"""
if not args:
args = sys.argv[1:]
if args[0] not in ['-h', '--help', '--version', '-info']:
if args[0].find('-') != -1:
msg = "Defaulting to the 'run' command. Please update the"
msg += " call of MontePython. For more info, see the help"
msg += " string and/or the documentation "
warnings.warn(msg)
args.insert(0, default)
elif args[0] == '-info':
msg = "The info option has been turned into a command. "
msg += "Please substitute '-info' with 'info' when running "
msg += "MontePython"
warnings.warn(msg)
args[0] = 'info'
return args
# -- custom argparse types
# -- check that the argument is a positive integer
def positive_int(string):
"""
Check if the input is integer positive
Parameters
----------
string: string
string to parse
output: int
return the integer
"""
try:
value = int(string)
if value <= 0:
raise ValueError
return value
except ValueError:
raise ap.ArgumentTypeError(
"You asked for a non-positive number of steps. "
"I am not sure what to do, so I will exit. Sorry.")
# -- check that the argument is an existing file
def existing_file(fname):
"""
Check if the file exists. If not raise an error
Parameters
----------
fname: string
file name to parse
Returns
-------
fname : string
"""
if os.path.isfile(fname):
return fname
else:
msg = "The file '{}' does not exist".format(fname)
raise ap.ArgumentTypeError(msg)
def parse_docstring(docstring, key_symbol="<**>", description_symbol="<++>"):
"""
Extract from the docstring the keys and description, return it as a dict
Parameters
----------
docstring : str
key_symbol : str
identifies the key of an argument/option
description_symbol : str
identify the description of an argument/option
output
------
helpdic : dict
help strings for the parser
"""
# remove new lines and multiple whitespaces
whitespaces = re.compile(r"\s+")
docstring = whitespaces.sub(" ", docstring)
# escape special characters
key_symbol = re.escape(key_symbol)
description_symbol = re.escape(description_symbol)
# define the regular expressions to match the key and the description
key_match = r'{0}-{{0,2}}(.+?){0}'
re_key = re.compile(key_match.format(key_symbol))
desc_match = r'({0}.+?{0}.+?{0})'
re_desc = re.compile(desc_match.format(description_symbol))
# get all and check that the keys and descriptions have the same lenghts
keys = re_key.findall(docstring)
descriptions = re_desc.findall(docstring)
if len(keys) != len(descriptions):
msg = "The option keys and their descriptions have different lenghts.\n"
msg += "Make sure that there are as many string surrounded by '{0}'"
msg += " as there are surrounded by '{1}"
raise ValueError(msg.format(key_symbol, description_symbol))
helpdict = dict(zip(keys, descriptions))
return helpdict
def custom_help(split_string="<++>"):
"""
Create a custom help action.
It expects *split_string* to appear in groups of three.
If the option string is '-h', then uses the short description
between the first two *split_string*.
If the option string is '-h', then uses all that is between
the first and the third *split_string*, stripping the first one.
Parameters
----------
split_string: str
string to use to select the help string and how to select them.
They must appear in groups of *3*
output
------
CustomHelp: class definition
"""
class CustomHelp(ap._HelpAction):
def __call__(self, parser, namespace, values, option_string=None):
# create the help string and store it into a string
from StringIO import StringIO
fstr = StringIO()
try:
parser.print_help(file=fstr)
help_str = fstr.getvalue()
finally:
fstr.close()
# create the regular expression to match the desciption
descmatch = r'{0}(.+?){0}(.+?){0}'
# escape possible dangerous characters
esplit_string = re.escape(split_string)
re_desc = re.compile(descmatch.format(esplit_string),
flags=re.DOTALL)
# select the case according to which option_string is selected
if option_string == '-h':
to_sub = r'\1'
elif option_string == '--help':
to_sub = r'\1\2'
print(re_desc.sub(to_sub, help_str))
parser.exit()
return CustomHelp
def add_subparser(sp, name, **kwargs):
"""
Add a parser to the subparser *sp* with *name*.
All the logic common to all subparsers should go here
Parameters
----------
sp: subparser instance
name: str
name of the subparser
kwargs: dict
keywords to pass to the subparser
output
------
sparser: Argparse instance
new subparser
"""
kwargs["add_help"] = False
kwargs['formatter_class'] = ap.ArgumentDefaultsHelpFormatter
sparser = sp.add_parser(name, **kwargs)
sparser.add_argument("-h", "--help", action=custom_help(),
help="print the short or long help")
return sparser
def get_dict_from_docstring(key_symbol="<**>", description_symbol="<++>"):
"""
Create the decorator
Parameters
----------
key_symbol : str
identifies the key of a argument/option
description_symbol: str
identify the description of a argument/option
Returns
------
wrapper: function
"""
def wrapper(func):
"""
Decorator that wraps the function that implement the parser, parses the
`__doc__` and construct a dictionary with the help strings. The
dictionary is added as an attribute of `func` and can be accessed in
the function
Parameters
----------
func: function
function with the docs to be parsed
Returns
------
func: function
function with the dictionary added. *key_symbol* and
*description_symbol* strings are removed
"""
docstring = func.__doc__
helpdict = parse_docstring(
docstring, key_symbol=key_symbol,
description_symbol=description_symbol)
func.helpdict = helpdict
# remove markers
docstring = docstring.replace(key_symbol, '')
func.__doc__ = docstring.replace(description_symbol, '')
return func
return wrapper
def initialise_parser(**kwargs):
"""
Create the argument parser and returns it
Parameters
----------
kwargs: dictionary
keyword to pass to the parser
output
------
p: MpArgumentParser instance
parser with some keyword added
"""
kwargs['formatter_class'] = ap.ArgumentDefaultsHelpFormatter
p = MpArgumentParser(**kwargs)
# -- version
path_file = os.path.sep.join(
os.path.abspath(__file__).split(os.path.sep)[:-2])
with open(os.path.join(path_file, 'VERSION'), 'r') as version_file:
version = version_file.readline()
p.add_argument('--version', action='version', version=version)
p.add_argument("-v", "--verbose", action="store_true", help="Verbose mode")
return p
@get_dict_from_docstring()
def create_parser():
"""
Definition of the parser command line options
The main parser has so far two subparsers, corresponding to the two main
modes of operating the code, namely `run` and `info`. If you simply call
:code:`python montepython/MontePython.py -h`, you will find only this piece
of information. To go further, and find the command line options specific
to these two submodes, one should then do: :code:`python
montepython/MontePython.py run -h`, or :code:`info -h`.
All command line arguments are defined below, for each of the two
subparsers. This function create the automatic help command.
Each flag outputs the following argument to a destination variable,
specified by the `dest` keyword argument in the source code. Please check
there to understand the variable names associated with each option.
Options
-------
**run**
<**>-N<**> : int
<++>number of steps in the chain<++> (**OBL**). Note that when
running on a cluster, your run might be stopped before reaching
this number.<++>
<**>-o<**> : str
<++>output folder<++> (**OBL**). For instance :code:`-o
chains/myexperiments/mymodel`. Note that in this example, the
folder :code:`chains/myexperiments` must already exist.<++>
<**>-p<**> : str
<++>input parameter file<++> (**OBL**). For example :code:`-p
input/exoticmodel.param`.<++>
<**>-c<**> : str
<++>input covariance matrix<++> (*OPT*). A covariance matrix is
created when analyzing previous runs.
Note that the list of parameters in the input covariance matrix and
in the run do not necessarily coincide.<++>
<**>-j<**> : str
<++>jumping method<++> (`global` (default), `sequential` or `fast`)
(*OPT*).
With the `global` method the code generates a new random direction
at each step, with the `sequential` one it cycles over the
eigenvectors of the proposal density (= input covariance matrix).
The `global` method the acceptance rate is usually lower but the
points in the chains are less correlated. We recommend using the
sequential method to get started in difficult cases, when the
proposal density is very bad, in order to accumulate points and
generate a covariance matrix to be used later with the `default`
jumping method.
The `fast` method implements the Cholesky decomposition presented
in http://arxiv.org/abs/1304.4473 by Antony Lewis.<++>
<**>-m<**> : str
<++>sampling method<++>, by default 'MH' for Metropolis-Hastings,
can be set to 'NS' for Nested Sampling (using Multinest wrapper
PyMultiNest), 'CH' for Cosmo Hammer (using the Cosmo Hammer wrapper
to emcee algorithm), and finally 'IS' for importance sampling.
Note that when running with Importance sampling, you need to
specify a folder to start from.<++>
<**>--update<**> : int
<++>update frequency for Metropolis Hastings.<++>
If greater than zero, number of steps after which the proposal covariance
matrix is updated automatically (*OPT*).<++>
<**>-f<**> : float
<++>jumping factor<++> (>= 0, default to 2.4) (*OPT*).
The proposal density is given by the input covariance matrix (or a
diagonal matrix with elements given by the square of the input
sigma's) multiplied by the square of this factor. In other words, a
typical jump will have an amplitude given by sigma times this
factor.
The default is the famous factor 2.4, advertised by Dunkley
et al. to be an optimal trade-off between high acceptance rate and
high correlation of chain elements, at least for multivariate
gaussian posterior probabilities. It can be a good idea to reduce
this factor for very non-gaussian posteriors.
Using :code:`-f 0 -N 1` is a convenient way to get the likelihood
exactly at the starting point passed in input.<++>
<**>--conf<**> : str
<++>configuration file<++> (default to `default.conf`) (*OPT*).
This file contains the path to your cosmological module
directory.<++>
<**>--chain-number<**> : str
arbitrary <++>number of the output chain<++>, to overcome the
automatic one (*OPT*).
By default, the chains are named :code:`yyyy-mm-dd_N__i.txt` with
year, month and day being extracted, :code:`N` being the number of
steps, and :code:`i` an automatically updated index.
This means that running several times the code with the same
command will create different chains automatically.
This option is a way to enforce a particular number :code:`i`.
This can be useful when running on a cluster: for instance you may
ask your script to use the job number as :code:`i`.<++>
<**>-r<**> : str
<++>restart from last point in chain<++>, to avoid the burn-in
stage (*OPT*).
At the beginning of the run, the previous chain will be deleted,
and its content transfered to the beginning of the new chain.<++>
<**>-b<**> : str
<++>start a new chain from the bestfit file<++> computed with
analyze. (*OPT*)<++>
<**>--fisher<**> : None
<++>Calculates the inverse of the fisher matrix<++> to use as
proposal distribution<++>
<**>--silent<**> : None
<++>silence the standard output<++> (useful when running on
clusters)<++>
<**>--Der-target-folder<**> : str
<++>Add additional derived params to this folder<++>. It has to be
used in conjunction with `Der-param-list`, and the method set to
Der: :code:`-m Der`. (*OPT*)<++>
<**>--Der-param-list<**> : str
<++>Specify a number of derived parameters to be added<++>. A
complete example would be to add Omega_Lambda as a derived
parameter:
:code:`python montepython/MontePython.py run -o existing_folder
-m Der --Der-target-folder non_existing_folder --Der-param-list
Omega_Lambda`<++>
<**>--IS-starting-folder<**> : str
<++>Perform Importance Sampling from this folder or set of
chains<++> (*OPT*)<++>
<**>--stop-after-update<**> : bool
<++>When using update mode, stop run after updating the covariant matrix.<++>
Useful if you want to change settings after the first guess (*OPT*) (flag)<++>
<**>--display-each-chi2<**> : bool
<++>Shows the effective chi2 from each likelihood and the total.<++>
Useful e.g. if you run at the bestfit point with -f 0 (flag)<++>
For Nested Sampling and Cosmo Hammer arguments, see
:mod:`nested_sampling` and :mod:`cosmo_hammer`.
**info**
Replaces the old **-info** command, which is deprecated but still
available.
<**>files<**> : string/list of strings
<++>you can specify either single files, or a complete folder<++>,
for example :code:`info chains/my-run/2012-10-26*`, or :code:`info
chains/my-run`.
If you specify several folders (or set of files), a comparison
will be performed.<++>
<**>--minimal<**> : None
<++>use this flag to avoid computing the posterior
distribution.<++> This will decrease the time needed for the
analysis, especially when analyzing big folders.<++>
<**>--bins<**> : int
<++>number of bins in the histograms<++> used to derive posterior
probabilities and credible intervals (default to 20). Decrease this
number for smoother plots at the expense of masking details.<++>
<**>--no-mean<**> : None
<++>remove the mean likelihood from the plot<++>. By default, when
plotting marginalised 1D posteriors, the code also shows the mean
likelihood per bin with dashed lines; this flag switches off the
dashed lines.<++>
<**>--short-title-1d<**> : None
<++>short 1D plot titles<++>. Remove mean and confidence limits above each 1D plots.<++>
<**>--extra<**> : str
<++>extra file to customize the output plots<++>. You can actually
set all the possible options in this file, including line-width,
ticknumber, ticksize, etc... You can specify four fields,
`info.redefine` (dict with keys set to the previous variable, and
the value set to a numerical computation that should replace this
variable), `info.to_change` (dict with keys set to the old variable
name, and value set to the new variable name), `info.to_plot` (list
of variables with new names to plot), and `info.new_scales` (dict
with keys set to the new variable names, and values set to the
number by which it should be multiplied in the graph).<++> For
instance,
.. code::
info.to_change={'oldname1':'newname1','oldname2':'newname2',...}
info.to_plot=['name1','name2','newname3',...]
info.new_scales={'name1':number1,'name2':number2,...}
<**>--noplot<**> : bool
<++>do not produce any plot, simply compute the posterior<++>
(*OPT*) (flag)<++>
<**>--noplot-2d<**> : bool
<++>produce only the 1d posterior plot<++> (*OPT*) (flag)<++>
<**>--contours-only<**> : bool
<++>do not fill the contours on the 2d plots<++> (*OPT*) (flag)<++>
<**>--all<**> : None
<++>output every subplot and data in separate files<++> (*OPT*)
(flag)<++>
<**>--ext<**> : str
<++>change the extension for the output file. Any extension handled
by :code:`matplotlib` can be used<++>. (`pdf` (default), `png`
(faster))<++>
<**>--num-columns-1d<**> : int
<++>for 1d plot, number of plots per horizontal raw; if 'None' this is set automatically<++> (trying to approach a square plot).<++>
<**>--fontsize<**> : int
<++>desired fontsize<++> (default to 16)<++>
<**>--ticksize<**> : int
<++>desired ticksize<++> (default to 14)<++>
<**>--line-width<**> : int
<++>set line width<++> (default to 4)<++>
<**>--decimal<**> : int
<++>number of decimal places on ticks<++> (default to 3)<++>
<**>--ticknumber<**> : int
<++>number of ticks on each axis<++> (default to 3)<++>
<**>--legend-style<**> : str
<++>specify the style of the legend<++>, to choose from `sides` or
`top`.<++>
<**>--keep-non-markovian<**> : bool
<++>Use this flag to keep the non-markovian part of the chains produced
at the beginning of runs with --update mode<++>
This option is only relevant when the chains were produced with --update (*OPT*) (flag)<++>
<**>--keep-fraction<**> : float
<++>after burn-in removal, analyze only last fraction of each chain.<++>
(between 0 and 1). Normally one would not use this for runs with --update mode,
unless --keep-non-markovian is switched on (*OPT*)<++>
<**>--want-covmat<**> : bool
<++>calculate the covariant matrix when analyzing the chains.<++>
Warning: this will interfere with ongoing runs utilizing update mode (*OPT*) (flag)<++>
<**>--gaussian-smoothing<**> : float
<++>width of gaussian smoothing for plotting posteriors<++>,
in units of bin size, increase for smoother data<++>
<**>--interpolation-smoothing<**> : float
<++>interpolation factor for plotting posteriors<++>,
1 means no interpolation, increase for smoother curves<++>
<**>--posterior-smoothing<**> : int
<++>smoothing scheme for 1d posteriors<++>,
0 means no smoothing, 1 means cubic interpolation, higher means fitting ln(L) with polynomial of order n<++>
Returns
-------
args : NameSpace
parsed input arguments
"""
helpdict = create_parser.helpdict
# Customized usage, for more verbosity concerning these subparsers options.
usage = """%(prog)s [-h] [--version] {run,info} ... """
usage += tw.dedent("""\n
From more help on each of the subcommands, type:
%(prog)s run -h
%(prog)s info -h\n\n""")
# parser = ap.ArgumentParser(
#parser = MpArgumentParser(
#formatter_class=ap.ArgumentDefaultsHelpFormatter,
#description='Monte Python, a Monte Carlo code in Python',
#usage=usage)
parser = initialise_parser(
description='Monte Python, a Monte Carlo code in Python', usage=usage)
# -- add the subparsers
subparser = parser.add_subparsers(dest='subparser_name')
###############
# run the MCMC
runparser = add_subparser(subparser, 'run', help="run the MCMC chains")
# -- number of steps (OPTIONAL)
runparser.add_argument('-N', help=helpdict['N'], type=positive_int,
dest='N')
# -- output folder (OBLIGATORY)
runparser.add_argument('-o', '--output', help=helpdict['o'], type=str,
dest='folder')
# -- parameter file (OBLIGATORY)
runparser.add_argument('-p', '--param', help=helpdict['p'],
type=existing_file, dest='param')
# -- covariance matrix (OPTIONAL)
runparser.add_argument('-c', '--covmat', help=helpdict['c'],
type=existing_file, dest='cov')
# -- jumping method (OPTIONAL)
runparser.add_argument('-j', '--jumping', help=helpdict['j'],
dest='jumping', default='fast',
choices=['global', 'sequential', 'fast'])
# -- sampling method (OPTIONAL)
runparser.add_argument('-m', '--method', help=helpdict['m'],
dest='method', default='MH',
choices=['MH', 'NS', 'CH', 'IS', 'Der'])
# -- update Metropolis Hastings (OPTIONAL)
runparser.add_argument('--update', help=helpdict['update'], type=int,
default=0)
# -- jumping factor (OPTIONAL)
runparser.add_argument('-f', help=helpdict['f'], type=float,
dest='jumping_factor', default=2.4)
# -- fisher (EXPERIMENTAL)
runparser.add_argument('--fisher', help=helpdict['fisher'],
action='store_true')
# -- configuration file (OPTIONAL)
runparser.add_argument('--conf', help=helpdict['conf'],
type=str, dest='config_file',
default='default.conf')
# -- arbitrary numbering of an output chain (OPTIONAL)
runparser.add_argument('--chain-number', help=helpdict['chain-number'])
# -- stop run after first successful update using --update (EXPERIMENTAL)
runparser.add_argument('--stop-after-update', help=helpdict['stop-after-update'],
dest='stop_after_update', action='store_true')
# display option
runparser.add_argument('--display-each-chi2', help=helpdict['display-each-chi2'],
dest='display_each_chi2', action='store_true')
###############
# MCMC restart from chain or best fit file
runparser.add_argument('-r', help=helpdict['r'],
type=existing_file, dest='restart')
runparser.add_argument('-b', '--bestfit', dest='bf', help=helpdict['b'],
type=existing_file)
###############
# Silence the output (no print on the console)
runparser.add_argument('--silent', help=helpdict['silent'],
action='store_true')
###############
# Adding new derived parameters to a run
runparser.add_argument(
'--Der-target-folder', dest="Der_target_folder",
help=helpdict['Der-target-folder'], type=str, default='')
runparser.add_argument(
'--Der-param-list', dest='derived_parameters',
help=helpdict['Der-param-list'], type=str, default='', nargs='+')
###############
# Importance Sampling Arguments
runparser.add_argument(
'--IS-starting-folder', dest='IS_starting_folder',
help=helpdict['IS-starting-folder'], type=str, default='', nargs='+')
###############
# MultiNest arguments (all OPTIONAL and ignored if not "-m=NS")
# The default values of -1 mean to take the PyMultiNest default values
try:
from nested_sampling import NS_prefix, NS_user_arguments
NSparser = runparser.add_argument_group(
title="MultiNest",
description="Run the MCMC chains using MultiNest"
)
for arg in NS_user_arguments:
NSparser.add_argument('--'+NS_prefix+arg,
default=-1,
**NS_user_arguments[arg])
except ImportError:
# Not defined if not installed
pass
###############
# CosmoHammer arguments (all OPTIONAL and ignored if not "-m=CH")
# The default values of -1 mean to take the CosmoHammer default values
try:
from cosmo_hammer import CH_prefix, CH_user_arguments
CHparser = runparser.add_argument_group(
title="CosmoHammer",
description="Run the MCMC chains using the CosmoHammer framework")
for arg in CH_user_arguments:
CHparser.add_argument('--'+CH_prefix+arg,
default=-1,
**CH_user_arguments[arg])
except ImportError:
# Not defined if not installed
pass
###############
# Information
infoparser = add_subparser(subparser, 'info',
help="analyze the MCMC chains")
# -- folder to analyze
infoparser.add_argument('files', help=helpdict['files'],
nargs='+')
# Silence the output (no print on the console)
infoparser.add_argument('--silent', help=helpdict['silent'],
action='store_true')
# -- to only write the covmat and bestfit, without computing the posterior
infoparser.add_argument('--minimal', help=helpdict['minimal'],
action='store_true')
# -- number of bins (defaulting to 20)
infoparser.add_argument('--bins', help=helpdict['bins'],
type=int, default=20)
# -- to remove the mean-likelihood line
infoparser.add_argument('--no-mean', help=helpdict['no-mean'],
dest='mean_likelihood', action='store_false')
# -- to remove the mean and 68% limits on top of each 1D plot
infoparser.add_argument('--short-title-1d', help=helpdict['short-title-1d'],
dest='short_title_1d', action='store_true')
# -- possible plot file describing custom commands
infoparser.add_argument('--extra', help=helpdict['extra'],
dest='optional_plot_file', default='')
# -- if you just want the covariance matrix, use this option
infoparser.add_argument('--noplot', help=helpdict['noplot'],
dest='plot', action='store_false')
# -- if you just want to output 1d posterior distributions (faster)
infoparser.add_argument('--noplot-2d', help=helpdict['noplot-2d'],
dest='plot_2d', action='store_false')
# -- when plotting 2d posterior distribution, use contours and not contours
# filled (might be useful when comparing several folders)
infoparser.add_argument('--contours-only', help=helpdict['contours-only'],
dest='contours_only', action='store_true')
# -- if you want to output every single subplots
infoparser.add_argument('--all', help=helpdict['all'], dest='subplot',
action='store_true')
# -- to change the extension used to output files (pdf is the default one,
# but takes long, valid options are png and eps)
infoparser.add_argument('--ext', help=helpdict['ext'],
type=str, dest='extension', default='pdf')
# -- to set manually the number of plots per hoorizontal raw in 1d plot
infoparser.add_argument('--num-columns-1d', help=helpdict['num-columns-1d'],
type=int, dest='num_columns_1d')
# -- only analyze the markovian part of the chains
infoparser.add_argument('--keep-non-markovian', help=helpdict['keep-non-markovian'],
dest='markovian', action='store_false')
# -- fraction of chains to be analyzed after burn-in removal (defaulting to 1.0)
infoparser.add_argument('--keep-fraction', help=helpdict['keep-fraction'],
type=float, dest='keep_fraction', default=1.0)
# -- calculate the covariant matrix when analyzing the chains
infoparser.add_argument('--want-covmat', help=helpdict['want-covmat'],
dest='want_covmat', action='store_true')
# -------------------------------------
# Further customization
# -- fontsize of plots (defaulting to 16)
infoparser.add_argument('--fontsize', help=helpdict['fontsize'],
type=int, default=16)
# -- ticksize of plots (defaulting to 14)
infoparser.add_argument('--ticksize', help=helpdict['ticksize'],
type=int, default=14)
# -- linewidth of 1d plots (defaulting to 4, 2 being a bare minimum for
# legible graphs
infoparser.add_argument('--line-width', help=helpdict['line-width'],
type=int, default=4)
# -- number of decimal places that appear on the tick legend. If you want
# to increase the number of ticks, you should reduce this number
infoparser.add_argument('--decimal', help=helpdict['decimal'], type=int,
default=3)
# -- number of ticks that appear on the graph.
infoparser.add_argument('--ticknumber', help=helpdict['ticknumber'],
type=int, default=3)
# -- legend type, to choose between top (previous style) to sides (new
# style). It modifies the place where the name of the variable appear.
infoparser.add_argument('--legend-style', help=helpdict['legend-style'],
type=str, choices=['sides', 'top'],
default='sides')
# -- width of gaussian smoothing for plotting posteriors,
# in units of bin size, increase for smoother data.
infoparser.add_argument('--gaussian-smoothing', help=helpdict['gaussian-smoothing'],
type=float, default=0.5)
# interpolation factor for plotting posteriors, 1 means no interpolation,
# increase for smoother curves (it means that extra bins are created
# and interpolated between computed bins)
infoparser.add_argument('--interpolation-smoothing', help=helpdict['interpolation-smoothing'],
type=int, default=4)
infoparser.add_argument('--posterior-smoothing', help=helpdict['posterior-smoothing'],
type=int, default=5)
return parser
def parse(custom_command=''):
"""
Check some basic organization of the folder, and exit the program in case
something goes wrong.
Keyword Arguments
-----------------
custom_command : str
For testing purposes, instead of reading the command line argument,
read instead the given string. It should ommit the start of the
command, so e.g.: '-N 10 -o toto/'
"""
# Create the parser
parser = create_parser()
# Recover all command line arguments in the args dictionary, except for a
# test, where the custom_command string is read.
# Note that the function safe_parse_args is read instead of parse_args. It
# is a function defined in this file to allow for a default subparser.
if not custom_command:
args = parser.safe_parse_args()
else:
args = parser.safe_parse_args(custom_command.split(' '))
# check for MPI
try:
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
except ImportError:
# set all chains to master if no MPI
rank = 0
# Some check to perform when running the MCMC chains is requested
if args.subparser_name == "run":
# If the user wants to start over from an existing chain, the program
# will use automatically the same folder, and the log.param in it
if args.restart is not None:
args.folder = os.path.sep.join(
args.restart.split(os.path.sep)[:-1])
args.param = os.path.join(args.folder, 'log.param')
if not args.silent:
warnings.warn(
"Restarting from %s." % args.restart +
" Using associated log.param.")
# Else, the user should provide an output folder
else:
if args.folder is None:
raise io_mp.ConfigurationError(
"You must provide an output folder, because you do not " +
"want your main folder to look dirty, do you ?")
# and if the folder already exists, and that no parameter file was
# provided, use the log.param
if os.path.isdir(args.folder):
if os.path.exists(
os.path.join(args.folder, 'log.param')):
# if the log.param exists, and that a parameter file was
# provided, take instead the log.param, and notify the
# user.
old_param = args.param
args.param = os.path.join(
args.folder, 'log.param')
if old_param is not None:
if not args.silent and not rank:
warnings.warn(
"Appending to an existing folder: using the "
"log.param instead of %s" % old_param)
else:
if args.param is None:
raise io_mp.ConfigurationError(
"The requested output folder seems empty. "
"You must then provide a parameter file (command"
" line option -p any.param)")
else:
if args.param is None:
raise io_mp.ConfigurationError(
"The requested output folder appears to be non "
"existent. You must then provide a parameter file "
"(command line option -p any.param)")
return args
| {
"content_hash": "a677b46d1e884c3ff49600497488aae3",
"timestamp": "",
"source": "github",
"line_count": 869,
"max_line_length": 144,
"avg_line_length": 42.45454545454545,
"alnum_prop": 0.5804082075190415,
"repo_name": "miguelzuma/montepython_zuma",
"id": "e56c9850b9b826f757fd8ccbbac00a13ed173cf4",
"size": "36893",
"binary": false,
"copies": "2",
"ref": "refs/heads/2.2",
"path": "montepython/parser_mp.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "5106"
},
{
"name": "C",
"bytes": "83026"
},
{
"name": "Fortran",
"bytes": "2316"
},
{
"name": "Gnuplot",
"bytes": "3263"
},
{
"name": "Makefile",
"bytes": "6379"
},
{
"name": "Python",
"bytes": "648953"
}
],
"symlink_target": ""
} |
from django.contrib import admin
from website.models import Project, Result, ExperimentConf, DBConf
class ExperimentConfAdmin(admin.ModelAdmin):
list_display = [ 'name', 'project', 'benchmark_type', 'creation_time' ]
list_filter = [ 'creation_time' ]
class ProjectAdmin(admin.ModelAdmin):
fields = ['user', 'name', 'description', 'creation_time',
'last_update', 'upload_code']
list_display = ('user', 'name', 'last_update', 'creation_time')
list_display_links = ('name', 'last_update', 'creation_time')
admin.site.register(Project, ProjectAdmin)
admin.site.register(ExperimentConf, ExperimentConfAdmin)
admin.site.register(Result)
| {
"content_hash": "f7a3a60dbbfbff5385b6aa69ca4ed636",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 75,
"avg_line_length": 37.22222222222222,
"alnum_prop": 0.7059701492537314,
"repo_name": "oltpbenchmark/website",
"id": "cc6833a26b494b075e2acb69fd6d8f165b7bb2a0",
"size": "670",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "website/admin.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "5161"
},
{
"name": "HTML",
"bytes": "26039"
},
{
"name": "JavaScript",
"bytes": "27639"
},
{
"name": "Python",
"bytes": "28185"
},
{
"name": "Shell",
"bytes": "314"
}
],
"symlink_target": ""
} |
import examples.connect
"""
Find a resource from the Compute service.
For a full guide see
https://docs.openstack.org/openstacksdk/latest/user/guides/compute.html
"""
def find_image(conn):
print("Find Image:")
image = conn.compute.find_image(examples.connect.IMAGE_NAME)
print(image)
return image
def find_flavor(conn):
print("Find Flavor:")
flavor = conn.compute.find_flavor(examples.connect.FLAVOR_NAME)
print(flavor)
return flavor
def find_keypair(conn):
print("Find Keypair:")
keypair = conn.compute.find_keypair(examples.connect.KEYPAIR_NAME)
print(keypair)
return keypair
| {
"content_hash": "e8be212c0fb01b2c31015d886485a12b",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 71,
"avg_line_length": 16.92105263157895,
"alnum_prop": 0.702954898911353,
"repo_name": "openstack/python-openstacksdk",
"id": "64ca9e3559d0f9bdcf0886a3fe528f554e6feca0",
"size": "1189",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "examples/compute/find.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "3804005"
},
{
"name": "Shell",
"bytes": "9027"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.