repo_name stringlengths 5 100 | ref stringlengths 12 67 | path stringlengths 4 244 | copies stringlengths 1 8 | content stringlengths 0 1.05M ⌀ |
|---|---|---|---|---|
dcorio/l10n-italy | refs/heads/8.0 | l10n_it_fatturapa_out/models/__init__.py | 7 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 Davide Corio
# Copyright 2015 Agile Business Group <http://www.agilebg.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from . import attachment
from . import account
|
dagothar/gripperz | refs/heads/master | cluster/easy_landscape_collect.py | 1 | #!/usr/bin/python
# Example:
# ../scripts/easy_landscape_start.py --dir /home/awolniakowski/test/ --dwc /home/awolniakowski/grippers_acat/scenes/rotorcap/Scene.dwc.xml --td /home/awolniakowski/grippers_acat/scenes/rotorcap/task.td.xml --gripper /home/awolniakowski/grippers_acat/grippers/standard_gripper.grp.xml --grasps /home/awolniakowski/grippers_acat/grasps/rotorcap100_p10_a15.rwtask.xml -p cutdepth -b 0 0.025 --res 100 --threads 2 --alir 0.001
import argparse
import numpy
import signal
import os
import sys
import xml.etree.ElementTree as ET
CMD = 'qsub /home/awolniakowski/scripts/evaluate_landscape.sh -V -v DIRECTORY={dir},DWC={dwc},TD={td},GRIPPER={gripper},GRASPS={grasps},SAVE={save},PARAM={param},VALUE={value},THREADS={threads},NGRASPS={ngrasps},RESULT={result},ALIR={alir},SEED={seed},FILTERS={filters}'
def signal_handler(signal, frame):
print('Stopping')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
def main():
parser = argparse.ArgumentParser(description="Generates gripper landscape data")
parser.add_argument("--parameter", "-p", metavar='PARAMETER', required=True, help="which parameter to landscape")
parser.add_argument("--res", metavar='RES', default=100, help="landscape resolution")
parser.set_defaults(save_grasps=False)
args = parser.parse_args()
PARAM = args.parameter
RES = int(args.res)
data = open(PARAM + '.csv', 'w')
data.write(PARAM + ", success, alignment, coverage, wrench, stress, volume, qsum, qlog\n");
for i in range(0, RES+1):
print "Collecting " + PARAM + " = " + str(i)
result = PARAM + '_' + str(i) + '.grp.xml'
try:
tree = ET.parse(result)
root = tree.getroot()
v = float(root.find('.//parameter[@name="{name}"]'.format(name = PARAM)).text)
success = float(root.find('.//index[@name="success"]').text)
alignment = float(root.find('.//index[@name="alignment"]').text)
coverage = float(root.find('.//index[@name="coverage"]').text)
wrench = float(root.find('.//index[@name="wrench"]').text)
stress = float(root.find('.//index[@name="stress"]').text)
volume = float(root.find('.//index[@name="volume"]').text)
qlog = float(root.find('.//index[@name="Q"]').text)
qsum = (success + alignment + coverage + wrench + stress + volume) / 6.0
record = [v, success, alignment, coverage, wrench, stress, volume, qsum, qlog]
print record
data.write(", ".join(str(x) for x in record) + "\n")
data.flush()
except (RuntimeError, IOError):
continue
data.close()
if __name__ == "__main__":
main()
|
endolith/scipy | refs/heads/master | scipy/ndimage/setup.py | 18 | import os
from numpy.distutils.core import setup
from numpy.distutils.misc_util import Configuration
from numpy import get_include
from scipy._build_utils import numpy_nodepr_api
def configuration(parent_package='', top_path=None):
config = Configuration('ndimage', parent_package, top_path)
include_dirs = ['src',
get_include(),
os.path.join(os.path.dirname(__file__), '..', '_lib', 'src')]
config.add_extension("_nd_image",
sources=["src/nd_image.c",
"src/ni_filters.c",
"src/ni_fourier.c",
"src/ni_interpolation.c",
"src/ni_measure.c",
"src/ni_morphology.c",
"src/ni_splines.c",
"src/ni_support.c"],
include_dirs=include_dirs,
**numpy_nodepr_api)
# Cython wants the .c and .pyx to have the underscore.
config.add_extension("_ni_label",
sources=["src/_ni_label.c",],
include_dirs=['src']+[get_include()])
config.add_extension("_ctest",
sources=["src/_ctest.c"],
include_dirs=[get_include()],
**numpy_nodepr_api)
config.add_extension("_cytest",
sources=["src/_cytest.c"])
config.add_data_dir('tests')
return config
if __name__ == '__main__':
setup(**configuration(top_path='').todict())
|
h3biomed/ansible | refs/heads/h3 | test/units/module_utils/test_known_hosts.py | 52 | # -*- coding: utf-8 -*-
# (c) 2015, Michael Scherer <mscherer@redhat.com>
# Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import os.path
import pytest
from ansible.module_utils import known_hosts
URLS = {
'ssh://one.example.org/example.git': {
'is_ssh_url': True,
'get_fqdn': 'one.example.org',
'add_host_key_cmd': " -t rsa one.example.org",
'port': None,
},
'ssh+git://two.example.org/example.git': {
'is_ssh_url': True,
'get_fqdn': 'two.example.org',
'add_host_key_cmd': " -t rsa two.example.org",
'port': None,
},
'rsync://three.example.org/user/example.git': {
'is_ssh_url': False,
'get_fqdn': 'three.example.org',
'add_host_key_cmd': None, # not called for non-ssh urls
'port': None,
},
'git@four.example.org:user/example.git': {
'is_ssh_url': True,
'get_fqdn': 'four.example.org',
'add_host_key_cmd': " -t rsa four.example.org",
'port': None,
},
'git+ssh://five.example.org/example.git': {
'is_ssh_url': True,
'get_fqdn': 'five.example.org',
'add_host_key_cmd': " -t rsa five.example.org",
'port': None,
},
'ssh://six.example.org:21/example.org': {
# ssh on FTP Port?
'is_ssh_url': True,
'get_fqdn': 'six.example.org',
'add_host_key_cmd': " -t rsa -p 21 six.example.org",
'port': '21',
},
'ssh://[2001:DB8::abcd:abcd]/example.git': {
'is_ssh_url': True,
'get_fqdn': '[2001:DB8::abcd:abcd]',
'add_host_key_cmd': " -t rsa [2001:DB8::abcd:abcd]",
'port': None,
},
'ssh://[2001:DB8::abcd:abcd]:22/example.git': {
'is_ssh_url': True,
'get_fqdn': '[2001:DB8::abcd:abcd]',
'add_host_key_cmd': " -t rsa -p 22 [2001:DB8::abcd:abcd]",
'port': '22',
},
'username@[2001:DB8::abcd:abcd]/example.git': {
'is_ssh_url': True,
'get_fqdn': '[2001:DB8::abcd:abcd]',
'add_host_key_cmd': " -t rsa [2001:DB8::abcd:abcd]",
'port': None,
},
'username@[2001:DB8::abcd:abcd]:path/example.git': {
'is_ssh_url': True,
'get_fqdn': '[2001:DB8::abcd:abcd]',
'add_host_key_cmd': " -t rsa [2001:DB8::abcd:abcd]",
'port': None,
},
'ssh://internal.git.server:7999/repos/repo.git': {
'is_ssh_url': True,
'get_fqdn': 'internal.git.server',
'add_host_key_cmd': " -t rsa -p 7999 internal.git.server",
'port': '7999',
},
}
@pytest.mark.parametrize('url, is_ssh_url', ((k, URLS[k]['is_ssh_url']) for k in sorted(URLS)))
def test_is_ssh_url(url, is_ssh_url):
assert known_hosts.is_ssh_url(url) == is_ssh_url
@pytest.mark.parametrize('url, fqdn, port', ((k, URLS[k]['get_fqdn'], URLS[k]['port']) for k in sorted(URLS)))
def test_get_fqdn_and_port(url, fqdn, port):
assert known_hosts.get_fqdn_and_port(url) == (fqdn, port)
@pytest.mark.parametrize('fqdn, port, add_host_key_cmd, stdin',
((URLS[k]['get_fqdn'], URLS[k]['port'], URLS[k]['add_host_key_cmd'], {})
for k in sorted(URLS) if URLS[k]['is_ssh_url']),
indirect=['stdin'])
def test_add_host_key(am, mocker, fqdn, port, add_host_key_cmd):
get_bin_path = mocker.MagicMock()
get_bin_path.return_value = keyscan_cmd = "/custom/path/ssh-keyscan"
am.get_bin_path = get_bin_path
run_command = mocker.MagicMock()
run_command.return_value = (0, "Needs output, otherwise thinks ssh-keyscan timed out'", "")
am.run_command = run_command
append_to_file = mocker.MagicMock()
append_to_file.return_value = (None,)
am.append_to_file = append_to_file
mocker.patch('os.path.isdir', return_value=True)
mocker.patch('os.path.exists', return_value=True)
known_hosts.add_host_key(am, fqdn, port=port)
run_command.assert_called_with(keyscan_cmd + add_host_key_cmd)
|
caotianwei/django | refs/heads/master | tests/admin_inlines/models.py | 276 | """
Testing of admin inline formsets.
"""
from __future__ import unicode_literals
import random
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Parent(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Teacher(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Child(models.Model):
name = models.CharField(max_length=50)
teacher = models.ForeignKey(Teacher, models.CASCADE)
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
parent = GenericForeignKey()
def __str__(self):
return 'I am %s, a child of %s' % (self.name, self.parent)
class Book(models.Model):
name = models.CharField(max_length=50)
class Author(models.Model):
name = models.CharField(max_length=50)
books = models.ManyToManyField(Book)
class NonAutoPKBook(models.Model):
rand_pk = models.IntegerField(primary_key=True, editable=False)
author = models.ForeignKey(Author, models.CASCADE)
title = models.CharField(max_length=50)
def save(self, *args, **kwargs):
while not self.rand_pk:
test_pk = random.randint(1, 99999)
if not NonAutoPKBook.objects.filter(rand_pk=test_pk).exists():
self.rand_pk = test_pk
super(NonAutoPKBook, self).save(*args, **kwargs)
class EditablePKBook(models.Model):
manual_pk = models.IntegerField(primary_key=True)
author = models.ForeignKey(Author, models.CASCADE)
title = models.CharField(max_length=50)
class Holder(models.Model):
dummy = models.IntegerField()
class Inner(models.Model):
dummy = models.IntegerField()
holder = models.ForeignKey(Holder, models.CASCADE)
readonly = models.CharField("Inner readonly label", max_length=1)
def get_absolute_url(self):
return '/inner/'
class Holder2(models.Model):
dummy = models.IntegerField()
class Inner2(models.Model):
dummy = models.IntegerField()
holder = models.ForeignKey(Holder2, models.CASCADE)
class Holder3(models.Model):
dummy = models.IntegerField()
class Inner3(models.Model):
dummy = models.IntegerField()
holder = models.ForeignKey(Holder3, models.CASCADE)
# Models for ticket #8190
class Holder4(models.Model):
dummy = models.IntegerField()
class Inner4Stacked(models.Model):
dummy = models.IntegerField(help_text="Awesome stacked help text is awesome.")
holder = models.ForeignKey(Holder4, models.CASCADE)
class Inner4Tabular(models.Model):
dummy = models.IntegerField(help_text="Awesome tabular help text is awesome.")
holder = models.ForeignKey(Holder4, models.CASCADE)
# Models for #12749
class Person(models.Model):
firstname = models.CharField(max_length=15)
class OutfitItem(models.Model):
name = models.CharField(max_length=15)
class Fashionista(models.Model):
person = models.OneToOneField(Person, models.CASCADE, primary_key=True)
weaknesses = models.ManyToManyField(OutfitItem, through='ShoppingWeakness', blank=True)
class ShoppingWeakness(models.Model):
fashionista = models.ForeignKey(Fashionista, models.CASCADE)
item = models.ForeignKey(OutfitItem, models.CASCADE)
# Models for #13510
class TitleCollection(models.Model):
pass
class Title(models.Model):
collection = models.ForeignKey(TitleCollection, models.SET_NULL, blank=True, null=True)
title1 = models.CharField(max_length=100)
title2 = models.CharField(max_length=100)
# Models for #15424
class Poll(models.Model):
name = models.CharField(max_length=40)
class Question(models.Model):
poll = models.ForeignKey(Poll, models.CASCADE)
class Novel(models.Model):
name = models.CharField(max_length=40)
class Chapter(models.Model):
name = models.CharField(max_length=40)
novel = models.ForeignKey(Novel, models.CASCADE)
class FootNote(models.Model):
"""
Model added for ticket 19838
"""
chapter = models.ForeignKey(Chapter, models.PROTECT)
note = models.CharField(max_length=40)
# Models for #16838
class CapoFamiglia(models.Model):
name = models.CharField(max_length=100)
class Consigliere(models.Model):
name = models.CharField(max_length=100, help_text='Help text for Consigliere')
capo_famiglia = models.ForeignKey(CapoFamiglia, models.CASCADE, related_name='+')
class SottoCapo(models.Model):
name = models.CharField(max_length=100)
capo_famiglia = models.ForeignKey(CapoFamiglia, models.CASCADE, related_name='+')
class ReadOnlyInline(models.Model):
name = models.CharField(max_length=100, help_text='Help text for ReadOnlyInline')
capo_famiglia = models.ForeignKey(CapoFamiglia, models.CASCADE)
# Models for #18433
class ParentModelWithCustomPk(models.Model):
my_own_pk = models.CharField(max_length=100, primary_key=True)
name = models.CharField(max_length=100)
class ChildModel1(models.Model):
my_own_pk = models.CharField(max_length=100, primary_key=True)
name = models.CharField(max_length=100)
parent = models.ForeignKey(ParentModelWithCustomPk, models.CASCADE)
def get_absolute_url(self):
return '/child_model1/'
class ChildModel2(models.Model):
my_own_pk = models.CharField(max_length=100, primary_key=True)
name = models.CharField(max_length=100)
parent = models.ForeignKey(ParentModelWithCustomPk, models.CASCADE)
def get_absolute_url(self):
return '/child_model2/'
# Models for #19425
class BinaryTree(models.Model):
name = models.CharField(max_length=100)
parent = models.ForeignKey('self', models.SET_NULL, null=True, blank=True)
# Models for #19524
class LifeForm(models.Model):
pass
class ExtraTerrestrial(LifeForm):
name = models.CharField(max_length=100)
class Sighting(models.Model):
et = models.ForeignKey(ExtraTerrestrial, models.CASCADE)
place = models.CharField(max_length=100)
# Models for #18263
class SomeParentModel(models.Model):
name = models.CharField(max_length=1)
class SomeChildModel(models.Model):
name = models.CharField(max_length=1)
position = models.PositiveIntegerField()
parent = models.ForeignKey(SomeParentModel, models.CASCADE)
# Other models
class ProfileCollection(models.Model):
pass
class Profile(models.Model):
collection = models.ForeignKey(ProfileCollection, models.SET_NULL, blank=True, null=True)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
|
CitizenB/ansible | refs/heads/devel | lib/ansible/plugins/cache/redis.py | 112 | # (c) 2014, Brian Coca, Josh Drake, et al
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import time
import json
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.plugins.cache.base import BaseCacheModule
try:
from redis import StrictRedis
except ImportError:
raise AnsibleError("The 'redis' python module is required for the redis fact cache, 'pip install redis'")
class CacheModule(BaseCacheModule):
"""
A caching module backed by redis.
Keys are maintained in a zset with their score being the timestamp
when they are inserted. This allows for the usage of 'zremrangebyscore'
to expire keys. This mechanism is used or a pattern matched 'scan' for
performance.
"""
def __init__(self, *args, **kwargs):
if C.CACHE_PLUGIN_CONNECTION:
connection = C.CACHE_PLUGIN_CONNECTION.split(':')
else:
connection = []
self._timeout = float(C.CACHE_PLUGIN_TIMEOUT)
self._prefix = C.CACHE_PLUGIN_PREFIX
self._cache = StrictRedis(*connection)
self._keys_set = 'ansible_cache_keys'
def _make_key(self, key):
return self._prefix + key
def get(self, key):
value = self._cache.get(self._make_key(key))
# guard against the key not being removed from the zset;
# this could happen in cases where the timeout value is changed
# between invocations
if value is None:
self.delete(key)
raise KeyError
return json.loads(value)
def set(self, key, value):
value2 = json.dumps(value)
if self._timeout > 0: # a timeout of 0 is handled as meaning 'never expire'
self._cache.setex(self._make_key(key), int(self._timeout), value2)
else:
self._cache.set(self._make_key(key), value2)
self._cache.zadd(self._keys_set, time.time(), key)
def _expire_keys(self):
if self._timeout > 0:
expiry_age = time.time() - self._timeout
self._cache.zremrangebyscore(self._keys_set, 0, expiry_age)
def keys(self):
self._expire_keys()
return self._cache.zrange(self._keys_set, 0, -1)
def contains(self, key):
self._expire_keys()
return (self._cache.zrank(self._keys_set, key) >= 0)
def delete(self, key):
self._cache.delete(self._make_key(key))
self._cache.zrem(self._keys_set, key)
def flush(self):
for key in self.keys():
self.delete(key)
def copy(self):
# TODO: there is probably a better way to do this in redis
ret = dict()
for key in self.keys():
ret[key] = self.get(key)
return ret
def __getstate__(self):
return dict()
def __setstate__(self, data):
self.__init__()
|
jdobes/spacewalk | refs/heads/master | client/debian/packages-already-in-debian/rhn-client-tools/test/testConfig.py | 19 | #!/usr/bin/python
import settestpath
# lots of useful util methods for building/tearing down
# test enviroments...
import testutils
from up2date_client import config
import unittest
test_up2date = "etc-sysconfig-rhn/up2date"
class TestConfig(unittest.TestCase):
def setUp(self):
# in this stuff, we get weird stuff existing, so restore
# a config first, then change anything test specifc
testutils.restoreConfig()
self.__setupData()
def __setupData(self):
pass
def tearDown(self):
config.cfg == None
testutils.restoreConfig()
def testEmptyInit(self):
"Verify that the class can be created with no arguments"
cfg = config.initUp2dateConfig(test_up2date)
def testConfigString(self):
"Verify that Config loads a string as a string"
cfg = config.initUp2dateConfig(test_up2date)
assert isinstance(cfg['systemIdPath'], basestring)
def testConfigListSingleItem(self):
"Verify that Config loads a list of one as a list"
cfg = config.initUp2dateConfig(test_up2date)
assert type(cfg['pkgSkipList']) == type([])
def testConfigList(self):
"Verify that Config loads a list as a list"
cfg = config.initUp2dateConfig(test_up2date)
assert type(cfg['disallowConfChanges']) == type([])
def testConfigBool(self):
"Verify that Config loads a bool int as a bool"
cfg = config.initUp2dateConfig(test_up2date)
assert type(cfg['enableProxy']) == type(1)
def testConfigSave(self):
"Verify that Config saves a file without error"
cfg = config.initUp2dateConfig(test_up2date)
cfg.save()
def testConfigSetItem(self):
"Verify that Config.__setitem__ works"
cfg = config.initUp2dateConfig(test_up2date)
cfg['blippyfoobarbazblargh'] = 1
assert cfg['blippyfoobarbazblargh'] == 1
def testConfigInfo(self):
"Verify that Config.into() runs without error"
cfg = config.initUp2dateConfig(test_up2date)
blargh = cfg.info('enableProxy')
def testConfigRuntimeStore(self):
"Verify that values Config['value'] are set for runtime only and not saved"
cfg = config.initUp2dateConfig(test_up2date)
cfg['blippy12345'] = "wantafreehat?"
cfg.save()
# cfg is a fairly persistent singleton, blow it awy to get a new referece
del config.cfg
cfg2 = config.initUp2dateConfig(test_up2date)
# if this returns a value, it means we saved the config file...
assert cfg2['blippy12345'] == None
def testConfigRuntimeStoreNoDir(self):
"Verify that saving a file into a non existent dir works"
# bugzilla: 125179
cfg = config.initUp2dateConfig(test_up2date)
cfg['blippy321'] = "blumblim"
cfg.save()
def testConfigKeysReturnsAList(self):
"Verify that Config.keys() returns a list"
cfg = config.initUp2dateConfig(test_up2date)
blip = cfg.keys()
assert type(blip) == type([])
def testConfigKeys(self):
"Verify that Config.keys() returns a list with the right stuff"
cfg = config.initUp2dateConfig(test_up2date)
blip = cfg.keys()
assert "enableProxy" in blip
def testConfigHasKeyDoesntExist(self):
"Verify that Config.has_key() is correct on non existent keys"
cfg = config.initUp2dateConfig(test_up2date)
assert cfg.has_key("234wfj34ruafho34rhkfe") == 0
def testConfigHasKeyDoesExist(self):
"Verify that Config.has_key() is correct on existing keys"
cfg = config.initUp2dateConfig(test_up2date)
assert cfg.has_key("enableProxy") == 1
def testConfigHasKeyRuntime(self):
"Verify that Config.has_key() is correct for runtime keys"
cfg = config.initUp2dateConfig(test_up2date)
cfg['runtimekey'] = "blippy"
assert cfg.has_key('runtimekey') == 1
def testConfigValues(self):
"Verify that Config.values() runs without error"
cfg = config.initUp2dateConfig(test_up2date)
ret = cfg.values()
assert type(ret) == type([])
def testConfigItems(self):
"Verify that Config.items() runs without error"
cfg = config.initUp2dateConfig(test_up2date)
ret = cfg.items()
assert type(ret) == type([])
def testConfigSet(self):
"Verify that Config.set() sets items into the persistent layer"
cfg = config.initUp2dateConfig(test_up2date)
cfg.set("permItem", 1)
assert cfg.stored["permItem"] == 1
def testConfigSetOverride(self):
"Verify that Config.set() sets items in the persitent layer, overriding runtime"
cfg = config.initUp2dateConfig(test_up2date)
cfg['semiPermItem'] = 1
cfg.set('semiPermItem',0)
assert cfg.stored['semiPermItem'] == 0
def testConfigLoad(self):
"Verify that Config.load() works without exception"
cfg = config.initUp2dateConfig(test_up2date)
cfg.load("/etc/sysconfig/rhn/up2date")
def testNetworkConfig(self):
"Verify that the NetworkConfig class can be created"
nc = config.NetworkConfig()
def testNetworkConfigLoad(self):
"Verify that NetworkConfig.load() runs without error"
nc = config.NetworkConfig()
nc.load()
def testNetworkConfigLoadCorrectness(self):
"Verify that NetworkConfig.load() runs and gets the right info"
testutils.setupConfig("fc2-rpmmd-sources-1")
nc = config.NetworkConfig()
nc.load()
assert nc['blargh'] == "blippyfoo"
def testNetworkConfigLoadCorrectnessOverrides(self):
"Verify that NetworkConfig.load() runs and overrides the default value"
testutils.setupConfig("fc2-rpmmd-sources-1")
nc = config.NetworkConfig()
nc.load()
assert nc['serverURL'] == "http://www.hokeypokeyland.com/XMLRPC"
class TestGetProxySetting(unittest.TestCase):
def setUp(self):
self.cfg = config.initUp2dateConfig(test_up2date)
self.proxy1 = "http://proxy.company.com:8080"
self.proxy2 = "proxy.company.com:8080"
def testHttpSpecified(self):
"Verify that http:// gets stripped from proxy settings"
self.cfg['httpProxy'] = self.proxy1
res = up2dateUtils.getProxySetting()
assert res == "proxy.company.com:8080"
def testHttpUnSpecified(self):
"Verify that proxies with no http:// work correctly"
self.cfg['httpProxy'] = self.proxy2
res = up2dateUtils.getProxySetting()
assert res == "proxy.company.com:8080"
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestConfig))
suite.addTest(unittest.makeSuite(TestGetProxySetting))
return suite
if __name__ == "__main__":
unittest.main(defaultTest="suite")
|
gensmusic/test | refs/heads/master | l/python/book/learning-python/c24/mydir.py | 1 | #!/usr/bin/python
#coding:utf-8
"""
mydir.py a module that lists the namespaces of other modules
"""
seplen = 60
sepchr = '-'
def listing(module, verbose=True):
sepline = sepchr * seplen
if verbose:
print sepline
print 'name:',module.__name__,'file:',module.__file__
print sepline
count = 0
for attr in module.__dict__:
print '%02d %s' % (count,attr),
if attr.startswith('__'):
print '<built-in name>'
else:
print getattr(module, attr)
count += 1
if verbose:
print sepline
print module.__name__,'has %d names' % count
print sepline
if __name__ == '__main__':
import mydir
listing(mydir) # list myself |
ljhljh235/AutoRest | refs/heads/master | src/generator/AutoRest.Python.Azure.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/fixtures/acceptancetestssubscriptionidapiversion/credentials.py | 336 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.authentication import (
BasicAuthentication,
BasicTokenAuthentication,
OAuthTokenAuthentication)
from msrestazure.azure_active_directory import (
InteractiveCredentials,
ServicePrincipalCredentials,
UserPassCredentials)
|
qdqmedia/django-templation | refs/heads/master | templation/context_processor.py | 1 | def templation_info(request):
return {
'templation_view': getattr(request, '_templation_view', None),
'templation_template': getattr(request, '_templation_template', None),
}
|
lyft/incubator-airflow | refs/heads/master | tests/providers/mongo/sensors/test_mongo.py | 4 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
import unittest
import pytest
from airflow import DAG
from airflow.models import Connection
from airflow.providers.mongo.hooks.mongo import MongoHook
from airflow.providers.mongo.sensors.mongo import MongoSensor
from airflow.utils import db, timezone
DEFAULT_DATE = timezone.datetime(2017, 1, 1)
@pytest.mark.integration("mongo")
class TestMongoSensor(unittest.TestCase):
def setUp(self):
db.merge_conn(
Connection(
conn_id='mongo_test', conn_type='mongo',
host='mongo', port='27017', schema='test'))
args = {
'owner': 'airflow',
'start_date': DEFAULT_DATE
}
self.dag = DAG('test_dag_id', default_args=args)
hook = MongoHook('mongo_test')
hook.insert_one('foo', {'bar': 'baz'})
self.sensor = MongoSensor(
task_id='test_task',
mongo_conn_id='mongo_test',
dag=self.dag,
collection='foo',
query={'bar': 'baz'}
)
def test_poke(self):
self.assertTrue(self.sensor.poke(None))
if __name__ == '__main__':
unittest.main()
|
techlib/wifinator | refs/heads/master | wifinator/bin/__init__.py | 4 | #!/usr/bin/python3 -tt
# -*- coding: utf-8 -*-
pass
# vim:set sw=4 ts=4 et:
|
AlexXQJ/learn-python3 | refs/heads/master | samples/io/use_json.py | 21 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
d = dict(name='Bob', age=20, score=88)
data = json.dumps(d)
print('JSON Data is a str:', data)
reborn = json.loads(data)
print(reborn)
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
def __str__(self):
return 'Student object (%s, %s, %s)' % (self.name, self.age, self.score)
s = Student('Bob', 20, 88)
std_data = json.dumps(s, default=lambda obj: obj.__dict__)
print('Dump Student:', std_data)
rebuild = json.loads(std_data, object_hook=lambda d: Student(d['name'], d['age'], d['score']))
print(rebuild)
|
jdf76/plugin.video.youtube | refs/heads/master | resources/lib/youtube_plugin/kodion/constants/const_paths.py | 2 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2014-2016 bromix (plugin.video.youtube)
Copyright (C) 2016-2018 plugin.video.youtube
SPDX-License-Identifier: GPL-2.0-only
See LICENSES/GPL-2.0-only for more information.
"""
SEARCH = 'kodion/search'
FAVORITES = 'kodion/favorites'
WATCH_LATER = 'kodion/watch_later'
|
thinker3197/zeroclickinfo-fathead | refs/heads/jquery-fathead-issue319 | lib/fathead/bower/parse.py | 7 | #!/usr/bin/env python3
import sys
import re
URL_BASE = 'https://bower.io/docs/api/#'
CODE_PATTERN = re.compile(
r'{% highlight sh %}(.*){% endhighlight %}',
re.DOTALL
)
items = []
def add_item(ops):
# Write articles
items.append(
'\t'.join([
ops['name'],
'A',
'',
'',
'',
'',
'',
'',
'',
'',
'',
ops['abstract'],
URL_BASE + ops['URL']
]))
# Write 'command' redirect for each article
items.append(
'\t'.join([
'%s command' % ops['name'],
'R',
ops['name'],
'',
'',
'',
'',
'',
'',
'',
'',
'',
''
]))
def parse_item(text):
# remove all child block
text = text.split('\n####')[0]
name = text.split('\n')[0].strip()
code = re.search(CODE_PATTERN, text)
code = '<pre><code>%s</code></pre>' % (code.group(1).strip()) if code else ''
desc = "".join(text.split(r'{% endhighlight %}')[1:]).strip()
abstract = ('<section class="prog__container"><p>' + desc + '</p>' + code + '</section>').replace('\n', '\\n',).replace('\t', ' ')
return {
'name': name,
'abstract': abstract,
'URL': name
}
api_doc = ""
with open('download/api.md', 'r') as f:
api_doc = f.read()
if not api_doc:
sys.exit(-1)
api_doc_blocks = []
# only parse `Command` and `Options` block
for h2_block in api_doc.split('\n## ')[1:3]:
api_doc_blocks.extend(h2_block.split('\n### ')[1:])
for block in api_doc_blocks:
add_item(parse_item(block))
with open('output.txt', 'w') as f:
f.write("\n".join(items))
|
lmazuel/azure-sdk-for-python | refs/heads/master | azure-mgmt-network/azure/mgmt/network/v2018_01_01/models/effective_network_security_group_py3.py | 1 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class EffectiveNetworkSecurityGroup(Model):
"""Effective network security group.
:param network_security_group: The ID of network security group that is
applied.
:type network_security_group:
~azure.mgmt.network.v2018_01_01.models.SubResource
:param association: Associated resources.
:type association:
~azure.mgmt.network.v2018_01_01.models.EffectiveNetworkSecurityGroupAssociation
:param effective_security_rules: A collection of effective security rules.
:type effective_security_rules:
list[~azure.mgmt.network.v2018_01_01.models.EffectiveNetworkSecurityRule]
:param tag_map: Mapping of tags to list of IP Addresses included within
the tag.
:type tag_map: dict[str, list[str]]
"""
_attribute_map = {
'network_security_group': {'key': 'networkSecurityGroup', 'type': 'SubResource'},
'association': {'key': 'association', 'type': 'EffectiveNetworkSecurityGroupAssociation'},
'effective_security_rules': {'key': 'effectiveSecurityRules', 'type': '[EffectiveNetworkSecurityRule]'},
'tag_map': {'key': 'tagMap', 'type': '{[str]}'},
}
def __init__(self, *, network_security_group=None, association=None, effective_security_rules=None, tag_map=None, **kwargs) -> None:
super(EffectiveNetworkSecurityGroup, self).__init__(**kwargs)
self.network_security_group = network_security_group
self.association = association
self.effective_security_rules = effective_security_rules
self.tag_map = tag_map
|
michaelnt/doorstop | refs/heads/develop | doorstop/core/tests/test_importer.py | 1 | # -*- coding: utf-8 -*-
# SPDX-License-Identifier: LGPL-3.0-only
"""Unit tests for the doorstop.core.importer module."""
# pylint: disable=no-self-use,protected-access
import logging
import os
import unittest
from unittest.mock import MagicMock, Mock, patch
from warnings import catch_warnings
from doorstop.common import DoorstopError
from doorstop.core import importer
from doorstop.core.builder import _set_tree
from doorstop.core.tests.test_document import FILES, MockItem
from doorstop.core.tree import Tree
LOREM_IPSUM = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.'''
LATEX_MATH = '''Test Math Expressions in Latex Style:
Inline Style 1: $a \\ne 0$
Inline Style 2: \\(ax^2 + bx + c = 0\\)
Multiline: $$x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}.$$'''
PLANTUML_TXT = '''```plantuml format="svg_inline" alt="Use Cases of Doorstop" title="Use Cases of Doorstop"
@startuml
Author --> (Create Document)
Author --> (Create Item)
Author --> (Link Item to Document)
Author --> (Link Item to other Item)
Author --> (Edit Item)
Author --> (Review Item)
Author -> (Delete Item)
Author -> (Delete Document)
(Export) <- (Author)
(Import) <- (Author)
Reviewer --> (Review Item)
System --> (Suspect Changes)
System --> (Integrity)
@enduml
```'''
class TestModule(unittest.TestCase):
"""Unit tests for the doorstop.core.importer module."""
maxDiff = None
def test_import_file_unknown(self):
"""Verify an exception is raised when importing unknown formats."""
mock_document = Mock()
self.assertRaises(DoorstopError, importer.import_file, 'a.a', mock_document)
self.assertRaises(
DoorstopError, importer.import_file, 'a.csv', mock_document, '.a'
)
@patch('doorstop.core.importer._file_csv')
def test_import_file(self, mock_file_csv):
"""Verify an extension is parsed from the import path."""
mock_path = 'path/to/file.csv'
mock_document = Mock()
importer.FORMAT_FILE['.csv'] = mock_file_csv
importer.import_file(mock_path, mock_document)
mock_file_csv.assert_called_once_with(mock_path, mock_document, mapping=None)
@patch('doorstop.core.importer.check')
def test_import_file_custom_ext(self, mock_check):
"""Verify a custom extension can be specified for import."""
mock_path = 'path/to/file.ext'
mock_document = Mock()
importer.import_file(mock_path, mock_document, ext='.custom')
mock_check.assert_called_once_with('.custom')
@patch('doorstop.core.importer.add_item')
def test_file_yml(self, mock_add_item):
"""Verify a YAML file can be imported."""
path = os.path.join(FILES, 'exported.yml')
mock_document = Mock()
mock_document.find_item = Mock(side_effect=DoorstopError)
# Act
importer._file_yml(path, mock_document)
# Assert
self.assertEqual(5, mock_add_item.call_count)
@patch('doorstop.core.importer.add_item')
def test_file_yml_duplicates(self, mock_add_item):
"""Verify a YAML file can be imported (over existing items)."""
path = os.path.join(FILES, 'exported.yml')
mock_document = Mock()
# Act
importer._file_yml(path, mock_document)
# Assert
self.assertEqual(5, mock_add_item.call_count)
def test_file_yml_bad_format(self):
"""Verify YAML file import can handle bad data."""
path = os.path.join(FILES, 'exported.csv')
self.assertRaises(DoorstopError, importer._file_yml, path, None)
@patch('doorstop.core.importer._itemize')
def test_file_csv(self, mock_itemize):
"""Verify a CSV file can be imported."""
path = os.path.join(FILES, 'exported.csv')
mock_document = Mock()
# Act
importer._file_csv(path, mock_document)
# Assert
args, kwargs = mock_itemize.call_args
logging.debug("args: {}".format(args))
logging.debug("kwargs: {}".format(kwargs))
header, data, document = args
expected_header = [
'uid',
'level',
'text',
'ref',
'links',
'active',
'derived',
'header',
'normative',
'reviewed',
]
self.assertEqual(expected_header, header)
expected_data = [
[
'REQ001',
'1.2.3',
LOREM_IPSUM,
'',
'SYS001\nSYS002:abc123',
True,
False,
'',
True,
'',
],
# pylint: disable=implicit-str-concat-in-sequence
# 'REF''123' is intentional to avoid matching the reference in this test file
[
'REQ003',
'1.4',
'Unicode: -40° ±1%',
'REF' '123',
'REQ001',
True,
False,
'',
True,
'',
],
['REQ004', '1.6', 'Hello, world!', '', '', True, False, '', True, ''],
[
'REQ002',
'2.1',
'Hello, world!\n\n' + PLANTUML_TXT,
'',
'',
True,
False,
'Plantuml',
True,
'50ae164a198e612dee696cc80942dc29',
],
[
'REQ2-001',
'2.1',
'Hello, world!\n\n' + LATEX_MATH,
'',
'REQ001',
True,
False,
'',
True,
'',
],
]
self.assertEqual(expected_data, data)
self.assertIs(mock_document, document)
@patch('doorstop.core.importer._itemize')
def test_file_csv_modified(self, mock_itemize):
"""Verify a CSV file (with modifications) can be imported."""
path = os.path.join(FILES, 'exported-modified.csv')
mock_document = Mock()
# Act
importer._file_csv(path, mock_document)
# Assert
args, kwargs = mock_itemize.call_args
logging.debug("args: {}".format(args))
logging.debug("kwargs: {}".format(kwargs))
header, data, document = args
expected_header = [
'id',
'level',
'text',
'ref',
'links',
'active',
'derived',
'normative',
'additional',
]
self.assertEqual(expected_header, header)
expected_data = [
[
'REQ0555',
'1.2.3',
'Hello, world!\n',
'',
'SYS001,\nSYS002',
True,
False,
False,
'',
],
# pylint: disable=implicit-str-concat-in-sequence
# 'REF''123' is intentional to avoid matching the reference in this test file
[
'REQ003',
'1.4',
'Hello, world!\n',
'REF' '123',
'REQ001',
False,
False,
True,
'Some "quoted" text \'here\'.',
],
['REQ004', '1.6', 'Hello, world!\n', '', '', False, True, True, ''],
['REQ002', '2.1', 'Hello, world!\n', '', '', True, False, True, ''],
['REQ2-001', '2.1', 'Hello, world!\n', '', 'REQ001', True, False, True, ''],
]
self.assertEqual(expected_data, data)
self.assertIs(mock_document, document)
@patch('doorstop.core.importer._file_csv')
def test_file_tsv(self, mock_file_csv):
"""Verify a TSV file can be imported."""
mock_path = 'path/to/file.tsv'
mock_document = Mock()
# Act
importer._file_tsv(mock_path, mock_document)
# Assert
mock_file_csv.assert_called_once_with(
mock_path, mock_document, delimiter='\t', mapping=None
)
@patch('doorstop.core.importer._itemize')
def test_file_xlsx(self, mock_itemize):
"""Verify a XLSX file can be imported."""
path = os.path.join(FILES, 'exported.xlsx')
mock_document = Mock()
# Act
with catch_warnings():
importer._file_xlsx(path, mock_document)
# Assert
args, kwargs = mock_itemize.call_args
logging.debug("args: {}".format(args))
logging.debug("kwargs: {}".format(kwargs))
header, data, document = args
expected_header = [
'uid',
'level',
'text',
'ref',
'links',
'active',
'derived',
'header',
'normative',
'reviewed',
]
self.assertEqual(expected_header, header)
expected_data = [
[
'REQ001',
'1.2.3',
LOREM_IPSUM,
None,
'SYS001\nSYS002:abc123',
True,
False,
None,
True,
None,
],
# pylint: disable=implicit-str-concat-in-sequence
# 'REF''123' is intentional to avoid matching the reference in this test file
[
'REQ003',
'1.4',
'Unicode: -40° ±1%',
'REF' '123',
'REQ001',
True,
False,
None,
True,
None,
],
[
'REQ004',
'1.6',
'Hello, world!',
None,
None,
True,
False,
None,
True,
None,
],
[
'REQ002',
'2.1',
'Hello, world!\n\n```plantuml format="svg_inline" alt="Use Cases of Doorstop" title="Use Cases of Doorstop"\n@startuml\nAuthor --> (Create Document)\nAuthor --> (Create Item)\nAuthor --> (Link Item to Document)\nAuthor --> (Link Item to other Item)\nAuthor --> (Edit Item)\nAuthor --> (Review Item)\nAuthor -> (Delete Item)\nAuthor -> (Delete Document)\n(Export) <- (Author)\n(Import) <- (Author)\nReviewer --> (Review Item)\nSystem --> (Suspect Changes)\nSystem --> (Integrity)\n@enduml\n```',
None,
None,
True,
False,
'Plantuml',
True,
'50ae164a198e612dee696cc80942dc29',
],
[
'REQ2-001',
'2.1',
'Hello, world!\n\nTest Math Expressions in Latex Style:\n\nInline Style 1: $a \\ne 0$\nInline Style 2: \\(ax^2 + bx + c = 0\\)\nMultiline: $$x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}.$$',
None,
'REQ001',
True,
False,
None,
True,
None,
],
]
self.assertEqual(expected_data, data)
self.assertIs(mock_document, document)
@patch('doorstop.core.importer.add_item')
def test_itemize(self, mock_add_item):
"""Verify item data can be converted to items."""
header = ['uid', 'text', 'links', 'ext1']
data = [['req1', 'text1', '', 'val1'], ['req2', '', 'sys1,sys2', False]]
mock_document = Mock()
mock_document.prefix = 'PREFIX'
# Act
importer._itemize(header, data, mock_document)
# Assert
self.assertEqual(2, mock_add_item.call_count)
args, kwargs = mock_add_item.call_args
self.assertEqual('PREFIX', args[0])
self.assertEqual('req2', args[1])
expected_attrs = {'ext1': False, 'links': ['sys1', 'sys2'], 'text': ''}
self.assertEqual(expected_attrs, kwargs['attrs'])
self.assertIs(mock_document, kwargs['document'])
@patch('doorstop.core.importer.add_item')
def test_itemize_implicit_active(self, mock_add_item):
"""Verify item data can be converted to items (implicit active)."""
header = ['uid', 'text', 'links', 'ext1', 'active']
data = [['req2', '', '', False, '']]
mock_document = Mock()
mock_document.prefix = 'PREFIX'
# Act
importer._itemize(header, data, mock_document)
# Assert
args, kwargs = mock_add_item.call_args
self.assertEqual('PREFIX', args[0])
self.assertEqual('req2', args[1])
expected_attrs = {'active': True, 'ext1': False, 'links': [], 'text': ''}
self.assertEqual(expected_attrs, kwargs['attrs'])
@patch('doorstop.core.importer.add_item')
def test_itemize_explicit_inactive(self, mock_add_item):
"""Verify item data can be converted to items (explicit inactive)."""
header = ['uid', 'text', 'links', 'ext1', 'active']
data = [['req2', '', '', False, False]]
mock_document = Mock()
mock_document.prefix = 'PREFIX'
# Act
importer._itemize(header, data, mock_document)
# Assert
args, kwargs = mock_add_item.call_args
self.assertEqual('PREFIX', args[0])
self.assertEqual('req2', args[1])
expected_attrs = {'active': False, 'ext1': False, 'links': [], 'text': ''}
self.assertEqual(expected_attrs, kwargs['attrs'])
@patch('doorstop.core.importer.add_item')
def test_itemize_with_mapping(self, mock_add_item):
"""Verify item data can be converted to items with mapping."""
header = ['myid', 'text', 'links', 'ext1']
data = [['req1', 'text1', '', 'val1'], ['req2', 'text2', 'sys1,sys2', None]]
mock_document = Mock()
mapping = {'MyID': 'uid'}
# Act
importer._itemize(header, data, mock_document, mapping=mapping)
# Assert
self.assertEqual(2, mock_add_item.call_count)
@patch('doorstop.core.importer.add_item')
def test_itemize_replace_existing(self, mock_add_item):
"""Verify item data can replace existing items."""
header = ['uid', 'text', 'links', 'ext1']
data = [['req1', 'text1', '', 'val1'], ['req2', 'text2', 'sys1,sys2', None]]
mock_document = Mock()
mock_document.find_item = Mock(side_effect=DoorstopError)
# Act
importer._itemize(header, data, mock_document)
# Assert
self.assertEqual(2, mock_add_item.call_count)
@patch('doorstop.core.importer.add_item')
def test_itemize_blank_column(self, mock_add_item):
"""Verify item data can include invalid values."""
header = ['id', 'text', None, 'links', 'ext1'] # test 'id' is accepted
data = [['req1', 'text1', 'blank', '', 'val1']]
mock_document = Mock()
mock_document.prefix = 'prefix'
importer._itemize(header, data, mock_document)
expected_attrs = {'links': [], 'ext1': 'val1', 'text': 'text1'}
mock_add_item.assert_called_once_with(
mock_document.prefix, 'req1', attrs=expected_attrs, document=mock_document
)
@patch('doorstop.core.importer.add_item')
def test_itemize_new_rows(self, mock_add_item):
"""Verify items can be added from item data blank UIDs."""
header = ['uid', 'text', 'links', 'ext1']
data = [
['req1', 'text1', '', 'val1'],
['req2', '', 'sys1,sys2', False],
[None, 'A new item.', '', ''], # blank UID: None
['', 'A new item.', '', ''], # blank UID: empty
[' ', 'A new item.', '', ''], # blank UID: whitespace
['', '', '', ''], # skipped
['...', 'Another new item.', '', ''], # placeholder UID
]
mock_document = Mock()
mock_document.prefix = 'PREFIX'
mock_document.next_number = 3
mock_document.digits = 3
# Act
importer._itemize(header, data, mock_document)
# Assert
self.assertEqual(6, mock_add_item.call_count)
@patch('doorstop.core.importer.add_item', Mock(side_effect=DoorstopError))
def test_itemize_invalid(self):
"""Verify item data can include invalid values."""
header = ['uid', 'text', 'links', 'ext1']
data = [['req1', 'text1', '', 'val1'], ['invalid']]
mock_document = Mock()
importer._itemize(header, data, mock_document)
class TestModuleCreateDocument(unittest.TestCase):
"""Unit tests for the doorstop.core.importer:create_document function."""
def setUp(self):
# Create default document options
self.prefix = 'PREFIX'
self.root = 'ROOT'
self.path = os.path.join(self.root, 'DIRECTORY')
self.parent = 'PARENT_PREFIX'
# Ensure the tree is reloaded
mock_document = Mock()
mock_document.root = self.root
self.mock_tree = Tree(mock_document)
_set_tree(self.mock_tree)
@patch('doorstop.core.tree.Tree.create_document')
def test_create_document(self, mock_new):
"""Verify a new document can be created for import."""
importer.create_document(self.prefix, self.path)
mock_new.assert_called_once_with(self.path, self.prefix, parent=None)
@patch('doorstop.core.builder._get_tree')
@patch('doorstop.core.tree.Tree.create_document')
def test_create_document_explicit_tree(self, mock_new, mock_get_tree):
"""Verify a new document can be created for import (explicit tree)."""
mock_document = Mock()
mock_document.root = None
tree = Tree(document=mock_document)
importer.create_document(self.prefix, self.path, tree=tree)
self.assertFalse(mock_get_tree.called)
mock_new.assert_called_once_with(self.path, self.prefix, parent=None)
self.assertIn(mock_document, tree)
@patch('doorstop.core.tree.Tree.create_document')
def test_create_document_with_parent(self, mock_new):
"""Verify a new document can be created for import with a parent."""
importer.create_document(self.prefix, self.path, parent=self.parent)
mock_new.assert_called_once_with(self.path, self.prefix, parent=self.parent)
@patch('doorstop.core.tree.Tree.create_document', Mock(side_effect=DoorstopError))
def test_create_document_already_exists(self):
"""Verify non-parent import exceptions are re-raised."""
self.assertRaises(
DoorstopError, importer.create_document, self.prefix, self.path
)
@patch('doorstop.core.tree.Tree.create_document', Mock(side_effect=DoorstopError))
@patch('doorstop.core.document.Document.new')
def test_create_document_unknown_parent(self, mock_new):
"""Verify documents can be created for import with unknown parents."""
importer.create_document(self.prefix, self.path, parent=self.parent)
mock_new.assert_called_once_with(
self.mock_tree, self.path, self.root, self.prefix, parent=self.parent
)
@patch('doorstop.core.item.Item', MockItem)
class TestModuleAddItem(unittest.TestCase):
"""Unit tests for the doorstop.core.importer:add_item function."""
prefix = 'PREFIX'
root = 'ROOT'
path = os.path.join(root, 'DIRECTORY')
parent = 'PARENT_PREFIX'
mock_document = Mock()
mock_document._items = []
def setUp(self):
# Create default item attributes
self.uid = 'PREFIX-00042'
# Ensure the tree is reloaded
mock_document = Mock()
mock_document.root = self.root
mock_document.prefix = self.prefix
self.mock_tree = Tree(mock_document)
_set_tree(self.mock_tree)
def mock_find_document(self, prefix):
"""Mock `Tree.find_document()` to return a mock document."""
assert isinstance(self, Tree)
assert prefix == TestModuleAddItem.prefix
TestModuleAddItem.mock_document.prefix = prefix
TestModuleAddItem.mock_document.path = TestModuleAddItem.path
TestModuleAddItem.mock_document.root = TestModuleAddItem.root
return TestModuleAddItem.mock_document
@patch('doorstop.core.tree.Tree.find_document', mock_find_document)
@patch('doorstop.core.item.Item.new')
def test_add_item(self, mock_new):
"""Verify an item can be imported into an existing document."""
importer.add_item(self.prefix, self.uid)
mock_new.assert_called_once_with(
self.mock_tree,
self.mock_document,
self.path,
self.root,
self.uid,
auto=False,
)
@patch('doorstop.core.builder._get_tree')
@patch('doorstop.core.tree.Tree.find_document', mock_find_document)
@patch('doorstop.core.item.Item.new')
def test_add_item_explicit_document(self, mock_new, mock_get_tree):
"""Verify an item can be imported into an explicit document."""
mock_document = self.mock_document
mock_tree = mock_document.tree
mock_document.tree._item_cache = MagicMock()
importer.add_item(self.prefix, self.uid, document=mock_document)
self.assertFalse(mock_get_tree.called)
mock_new.assert_called_once_with(
mock_tree, mock_document, self.path, self.root, self.uid, auto=False
)
@patch('doorstop.settings.ADDREMOVE_FILES', False)
@patch('doorstop.core.tree.Tree.find_document', mock_find_document)
def test_add_item_with_attrs(self):
"""Verify an item can be imported with attributes."""
attrs = {'text': "The item text.", 'ext': "External attrubte."}
item = importer.add_item(self.prefix, self.uid, attrs=attrs)
self.assertEqual(self.uid, item.uid)
self.assertEqual(attrs['text'], item.text)
self.assertEqual(attrs['ext'], item.get('ext'))
|
romain-dartigues/ansible-modules-core | refs/heads/rdartigues | cloud/openstack/_quantum_subnet.py | 41 | #!/usr/bin/python
#coding: utf-8 -*-
# (c) 2013, Benno Joy <benno@ansible.com>
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software. If not, see <http://www.gnu.org/licenses/>.
try:
try:
from neutronclient.neutron import client
except ImportError:
from quantumclient.quantum import client
from keystoneclient.v2_0 import client as ksclient
HAVE_DEPS = True
except ImportError:
HAVE_DEPS = False
DOCUMENTATION = '''
---
module: quantum_subnet
deprecated: Deprecated in 2.0. Use os_subnet instead
version_added: "1.2"
short_description: Add/remove subnet from a network
description:
- Add/remove subnet from a network
options:
login_username:
description:
- login username to authenticate to keystone
required: true
default: admin
login_password:
description:
- Password of login user
required: true
default: True
login_tenant_name:
description:
- The tenant name of the login user
required: true
default: True
auth_url:
description:
- The keystone URL for authentication
required: false
default: 'http://127.0.0.1:35357/v2.0/'
region_name:
description:
- Name of the region
required: false
default: None
state:
description:
- Indicate desired state of the resource
choices: ['present', 'absent']
default: present
network_name:
description:
- Name of the network to which the subnet should be attached
required: true
default: None
name:
description:
- The name of the subnet that should be created
required: true
default: None
cidr:
description:
- The CIDR representation of the subnet that should be assigned to the subnet
required: true
default: None
tenant_name:
description:
- The name of the tenant for whom the subnet should be created
required: false
default: None
ip_version:
description:
- The IP version of the subnet 4 or 6
required: false
default: 4
enable_dhcp:
description:
- Whether DHCP should be enabled for this subnet.
required: false
default: true
gateway_ip:
description:
- The ip that would be assigned to the gateway for this subnet
required: false
default: None
dns_nameservers:
description:
- DNS nameservers for this subnet, comma-separated
required: false
default: None
version_added: "1.4"
allocation_pool_start:
description:
- From the subnet pool the starting address from which the IP should be allocated
required: false
default: None
allocation_pool_end:
description:
- From the subnet pool the last IP that should be assigned to the virtual machines
required: false
default: None
requirements:
- "python >= 2.6"
- "python-neutronclient or python-quantumclient"
- "python-keystoneclient"
'''
EXAMPLES = '''
# Create a subnet for a tenant with the specified subnet
- quantum_subnet: state=present login_username=admin login_password=admin
login_tenant_name=admin tenant_name=tenant1
network_name=network1 name=net1subnet cidr=192.168.0.0/24"
'''
_os_keystone = None
_os_tenant_id = None
_os_network_id = None
def _get_ksclient(module, kwargs):
try:
kclient = ksclient.Client(username=kwargs.get('login_username'),
password=kwargs.get('login_password'),
tenant_name=kwargs.get('login_tenant_name'),
auth_url=kwargs.get('auth_url'))
except Exception as e:
module.fail_json(msg = "Error authenticating to the keystone: %s" %e.message)
global _os_keystone
_os_keystone = kclient
return kclient
def _get_endpoint(module, ksclient):
try:
endpoint = ksclient.service_catalog.url_for(service_type='network', endpoint_type='publicURL')
except Exception as e:
module.fail_json(msg = "Error getting network endpoint: %s" % e.message)
return endpoint
def _get_neutron_client(module, kwargs):
_ksclient = _get_ksclient(module, kwargs)
token = _ksclient.auth_token
endpoint = _get_endpoint(module, _ksclient)
kwargs = {
'token': token,
'endpoint_url': endpoint
}
try:
neutron = client.Client('2.0', **kwargs)
except Exception as e:
module.fail_json(msg = " Error in connecting to neutron: %s" % e.message)
return neutron
def _set_tenant_id(module):
global _os_tenant_id
if not module.params['tenant_name']:
_os_tenant_id = _os_keystone.tenant_id
else:
tenant_name = module.params['tenant_name']
for tenant in _os_keystone.tenants.list():
if tenant.name == tenant_name:
_os_tenant_id = tenant.id
break
if not _os_tenant_id:
module.fail_json(msg = "The tenant id cannot be found, please check the parameters")
def _get_net_id(neutron, module):
kwargs = {
'tenant_id': _os_tenant_id,
'name': module.params['network_name'],
}
try:
networks = neutron.list_networks(**kwargs)
except Exception as e:
module.fail_json("Error in listing neutron networks: %s" % e.message)
if not networks['networks']:
return None
return networks['networks'][0]['id']
def _get_subnet_id(module, neutron):
global _os_network_id
subnet_id = None
_os_network_id = _get_net_id(neutron, module)
if not _os_network_id:
module.fail_json(msg = "network id of network not found.")
else:
kwargs = {
'tenant_id': _os_tenant_id,
'name': module.params['name'],
}
try:
subnets = neutron.list_subnets(**kwargs)
except Exception as e:
module.fail_json( msg = " Error in getting the subnet list:%s " % e.message)
if not subnets['subnets']:
return None
return subnets['subnets'][0]['id']
def _create_subnet(module, neutron):
neutron.format = 'json'
subnet = {
'name': module.params['name'],
'ip_version': module.params['ip_version'],
'enable_dhcp': module.params['enable_dhcp'],
'tenant_id': _os_tenant_id,
'gateway_ip': module.params['gateway_ip'],
'dns_nameservers': module.params['dns_nameservers'],
'network_id': _os_network_id,
'cidr': module.params['cidr'],
}
if module.params['allocation_pool_start'] and module.params['allocation_pool_end']:
allocation_pools = [
{
'start' : module.params['allocation_pool_start'],
'end' : module.params['allocation_pool_end']
}
]
subnet.update({'allocation_pools': allocation_pools})
if not module.params['gateway_ip']:
subnet.pop('gateway_ip')
if module.params['dns_nameservers']:
subnet['dns_nameservers'] = module.params['dns_nameservers'].split(',')
else:
subnet.pop('dns_nameservers')
try:
new_subnet = neutron.create_subnet(dict(subnet=subnet))
except Exception as e:
module.fail_json(msg = "Failure in creating subnet: %s" % e.message)
return new_subnet['subnet']['id']
def _delete_subnet(module, neutron, subnet_id):
try:
neutron.delete_subnet(subnet_id)
except Exception as e:
module.fail_json( msg = "Error in deleting subnet: %s" % e.message)
return True
def main():
argument_spec = openstack_argument_spec()
argument_spec.update(dict(
name = dict(required=True),
network_name = dict(required=True),
cidr = dict(required=True),
tenant_name = dict(default=None),
state = dict(default='present', choices=['absent', 'present']),
ip_version = dict(default='4', choices=['4', '6']),
enable_dhcp = dict(default='true', type='bool'),
gateway_ip = dict(default=None),
dns_nameservers = dict(default=None),
allocation_pool_start = dict(default=None),
allocation_pool_end = dict(default=None),
))
module = AnsibleModule(argument_spec=argument_spec)
if not HAVE_DEPS:
module.fail_json(msg='python-keystoneclient and either python-neutronclient or python-quantumclient are required')
neutron = _get_neutron_client(module, module.params)
_set_tenant_id(module)
if module.params['state'] == 'present':
subnet_id = _get_subnet_id(module, neutron)
if not subnet_id:
subnet_id = _create_subnet(module, neutron)
module.exit_json(changed = True, result = "Created" , id = subnet_id)
else:
module.exit_json(changed = False, result = "success" , id = subnet_id)
else:
subnet_id = _get_subnet_id(module, neutron)
if not subnet_id:
module.exit_json(changed = False, result = "success")
else:
_delete_subnet(module, neutron, subnet_id)
module.exit_json(changed = True, result = "deleted")
# this is magic, see lib/ansible/module.params['common.py
from ansible.module_utils.basic import *
from ansible.module_utils.openstack import *
if __name__ == '__main__':
main()
|
chronossc/openpyxl | refs/heads/master | openpyxl/reader/worksheet.py | 2 | # file openpyxl/reader/worksheet.py
# Copyright (c) 2010 openpyxl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# @license: http://www.opensource.org/licenses/mit-license.php
# @author: Eric Gazoni
"""Reader for a single worksheet."""
# Python stdlib imports
try:
from xml.etree.cElementTree import iterparse
except ImportError:
from xml.etree.ElementTree import iterparse
from itertools import ifilter
from StringIO import StringIO
# package imports
from openpyxl.cell import Cell, coordinate_from_string
from openpyxl.worksheet import Worksheet
def _get_xml_iter(xml_source):
if not hasattr(xml_source, 'name'):
return StringIO(xml_source)
else:
xml_source.seek(0)
return xml_source
def read_dimension(xml_source):
source = _get_xml_iter(xml_source)
it = iterparse(source)
for event, element in it:
if element.tag == '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}dimension':
ref = element.get('ref')
if ':' in ref:
min_range, max_range = ref.split(':')
else:
min_range = max_range = ref
min_col, min_row = coordinate_from_string(min_range)
max_col, max_row = coordinate_from_string(max_range)
return min_col, min_row, max_col, max_row
else:
element.clear()
return None
def filter_cells((event, element)):
return element.tag == '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}c'
def fast_parse(ws, xml_source, string_table, style_table):
source = _get_xml_iter(xml_source)
it = iterparse(source)
for event, element in ifilter(filter_cells, it):
value = element.findtext('{http://schemas.openxmlformats.org/spreadsheetml/2006/main}v')
if value is not None:
coordinate = element.get('r')
data_type = element.get('t', 'n')
style_id = element.get('s')
if data_type == Cell.TYPE_STRING:
value = string_table.get(int(value))
ws.cell(coordinate).value = value
if style_id is not None:
ws._styles[coordinate] = style_table.get(int(style_id))
# to avoid memory exhaustion, clear the item after use
element.clear()
from openpyxl.reader.iter_worksheet import IterableWorksheet
def read_worksheet(xml_source, parent, preset_title, string_table,
style_table, workbook_name = None, sheet_codename = None):
"""Read an xml worksheet"""
if workbook_name and sheet_codename:
ws = IterableWorksheet(parent, preset_title, workbook_name,
sheet_codename, xml_source)
else:
ws = Worksheet(parent, preset_title)
fast_parse(ws, xml_source, string_table, style_table)
return ws
|
jieyu/maple | refs/heads/master | script/maple/benchmark/mysql_169_extract.py | 1 | """Copyright 2011 The University of Michigan
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.
Authors - Jie Yu (jieyu@umich.edu)
"""
from maple.core import config
from maple.core import testing
class Test(testing.CmdlineTest):
def __init__(self, input_idx):
testing.CmdlineTest.__init__(self, input_idx)
self.add_input(([self.bin()], [None, None, None]))
def bin(self):
return config.pkg_home() + '/example/mysql_169_extract/main'
def get_test(input_idx='default'):
return Test(input_idx)
|
pjg101/SickRage | refs/heads/master | lib/github/Repository.py | 7 | # -*- coding: utf-8 -*-
# ########################## Copyrights and license ############################
# #
# Copyright 2012 Christopher Gilbert <christopher.john.gilbert@gmail.com> #
# Copyright 2012 Steve English <steve.english@navetas.com> #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Adrian Petrescu <adrian.petrescu@maluuba.com> #
# Copyright 2013 Mark Roddy <markroddy@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2013 martinqt <m.ki2@laposte.net> #
# Copyright 2015 Jannis Gebauer <ja.geb@me.com> #
# #
# This file is part of PyGithub. #
# http://pygithub.github.io/PyGithub/v1/index.html #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
# ##############################################################################
import sys
import urllib
import datetime
from base64 import b64encode
import github.GithubObject
import github.PaginatedList
import github.Branch
import github.IssueEvent
import github.ContentFile
import github.Label
import github.GitBlob
import github.Organization
import github.GitRef
import github.GitRelease
import github.GitReleaseAsset
import github.Issue
import github.Repository
import github.PullRequest
import github.RepositoryKey
import github.NamedUser
import github.Milestone
import github.Comparison
import github.CommitComment
import github.GitCommit
import github.Team
import github.Commit
import github.GitTree
import github.Hook
import github.Tag
import github.GitTag
import github.Download
import github.Permissions
import github.Event
import github.Legacy
import github.StatsContributor
import github.StatsCommitActivity
import github.StatsCodeFrequency
import github.StatsParticipation
import github.StatsPunchCard
import github.Stargazer
atLeastPython3 = sys.hexversion >= 0x03000000
class Repository(github.GithubObject.CompletableGithubObject):
"""
This class represents Repositories. The reference can be found here http://developer.github.com/v3/repos/
"""
def __repr__(self):
return self.get__repr__({"full_name": self._full_name.value})
@property
def archived(self):
"""
:type: bool
"""
self._completeIfNotSet(self._archived)
return self._archived.value
@property
def archive_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._archive_url)
return self._archive_url.value
@property
def assignees_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._assignees_url)
return self._assignees_url.value
@property
def blobs_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._blobs_url)
return self._blobs_url.value
@property
def branches_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._branches_url)
return self._branches_url.value
@property
def clone_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._clone_url)
return self._clone_url.value
@property
def collaborators_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._collaborators_url)
return self._collaborators_url.value
@property
def comments_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._comments_url)
return self._comments_url.value
@property
def commits_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._commits_url)
return self._commits_url.value
@property
def compare_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._compare_url)
return self._compare_url.value
@property
def contents_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._contents_url)
return self._contents_url.value
@property
def contributors_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._contributors_url)
return self._contributors_url.value
@property
def created_at(self):
"""
:type: datetime.datetime
"""
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def default_branch(self):
"""
:type: string
"""
self._completeIfNotSet(self._default_branch)
return self._default_branch.value
@property
def description(self):
"""
:type: string
"""
self._completeIfNotSet(self._description)
return self._description.value
@property
def downloads_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._downloads_url)
return self._downloads_url.value
@property
def events_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._events_url)
return self._events_url.value
@property
def fork(self):
"""
:type: bool
"""
self._completeIfNotSet(self._fork)
return self._fork.value
@property
def forks(self):
"""
:type: integer
"""
self._completeIfNotSet(self._forks)
return self._forks.value
@property
def forks_count(self):
"""
:type: integer
"""
self._completeIfNotSet(self._forks_count)
return self._forks_count.value
@property
def forks_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._forks_url)
return self._forks_url.value
@property
def full_name(self):
"""
:type: string
"""
self._completeIfNotSet(self._full_name)
return self._full_name.value
@property
def git_commits_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._git_commits_url)
return self._git_commits_url.value
@property
def git_refs_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._git_refs_url)
return self._git_refs_url.value
@property
def git_tags_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._git_tags_url)
return self._git_tags_url.value
@property
def git_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._git_url)
return self._git_url.value
@property
def has_downloads(self):
"""
:type: bool
"""
self._completeIfNotSet(self._has_downloads)
return self._has_downloads.value
@property
def has_issues(self):
"""
:type: bool
"""
self._completeIfNotSet(self._has_issues)
return self._has_issues.value
@property
def has_wiki(self):
"""
:type: bool
"""
self._completeIfNotSet(self._has_wiki)
return self._has_wiki.value
@property
def homepage(self):
"""
:type: string
"""
self._completeIfNotSet(self._homepage)
return self._homepage.value
@property
def hooks_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._hooks_url)
return self._hooks_url.value
@property
def html_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._html_url)
return self._html_url.value
@property
def id(self):
"""
:type: integer
"""
self._completeIfNotSet(self._id)
return self._id.value
@property
def issue_comment_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._issue_comment_url)
return self._issue_comment_url.value
@property
def issue_events_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._issue_events_url)
return self._issue_events_url.value
@property
def issues_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._issues_url)
return self._issues_url.value
@property
def keys_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._keys_url)
return self._keys_url.value
@property
def labels_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._labels_url)
return self._labels_url.value
@property
def language(self):
"""
:type: string
"""
self._completeIfNotSet(self._language)
return self._language.value
@property
def languages_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._languages_url)
return self._languages_url.value
@property
def master_branch(self):
"""
:type: string
"""
self._completeIfNotSet(self._master_branch)
return self._master_branch.value
@property
def merges_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._merges_url)
return self._merges_url.value
@property
def milestones_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._milestones_url)
return self._milestones_url.value
@property
def mirror_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._mirror_url)
return self._mirror_url.value
@property
def name(self):
"""
:type: string
"""
self._completeIfNotSet(self._name)
return self._name.value
@property
def network_count(self):
"""
:type: integer
"""
self._completeIfNotSet(self._network_count)
return self._network_count.value
@property
def notifications_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._notifications_url)
return self._notifications_url.value
@property
def open_issues(self):
"""
:type: integer
"""
self._completeIfNotSet(self._open_issues)
return self._open_issues.value
@property
def open_issues_count(self):
"""
:type: integer
"""
self._completeIfNotSet(self._open_issues_count)
return self._open_issues_count.value
@property
def organization(self):
"""
:type: :class:`github.Organization.Organization`
"""
self._completeIfNotSet(self._organization)
return self._organization.value
@property
def owner(self):
"""
:type: :class:`github.NamedUser.NamedUser`
"""
self._completeIfNotSet(self._owner)
return self._owner.value
@property
def parent(self):
"""
:type: :class:`github.Repository.Repository`
"""
self._completeIfNotSet(self._parent)
return self._parent.value
@property
def permissions(self):
"""
:type: :class:`github.Permissions.Permissions`
"""
self._completeIfNotSet(self._permissions)
return self._permissions.value
@property
def private(self):
"""
:type: bool
"""
self._completeIfNotSet(self._private)
return self._private.value
@property
def pulls_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._pulls_url)
return self._pulls_url.value
@property
def pushed_at(self):
"""
:type: datetime.datetime
"""
self._completeIfNotSet(self._pushed_at)
return self._pushed_at.value
@property
def size(self):
"""
:type: integer
"""
self._completeIfNotSet(self._size)
return self._size.value
@property
def source(self):
"""
:type: :class:`github.Repository.Repository`
"""
self._completeIfNotSet(self._source)
return self._source.value
@property
def ssh_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._ssh_url)
return self._ssh_url.value
@property
def stargazers_count(self):
"""
:type: integer
"""
self._completeIfNotSet(self._stargazers_count) # pragma no cover (Should be covered)
return self._stargazers_count.value # pragma no cover (Should be covered)
@property
def stargazers_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._stargazers_url)
return self._stargazers_url.value
@property
def statuses_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._statuses_url)
return self._statuses_url.value
@property
def subscribers_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._subscribers_url)
return self._subscribers_url.value
@property
def subscribers_count(self):
"""
:type: integer
"""
self._completeIfNotSet(self._subscribers_count)
return self._subscribers_count.value
@property
def subscription_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._subscription_url)
return self._subscription_url.value
@property
def svn_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._svn_url)
return self._svn_url.value
@property
def tags_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._tags_url)
return self._tags_url.value
@property
def teams_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._teams_url)
return self._teams_url.value
@property
def trees_url(self):
"""
:type: string
"""
self._completeIfNotSet(self._trees_url)
return self._trees_url.value
@property
def updated_at(self):
"""
:type: datetime.datetime
"""
self._completeIfNotSet(self._updated_at)
return self._updated_at.value
@property
def url(self):
"""
:type: string
"""
self._completeIfNotSet(self._url)
return self._url.value
@property
def watchers(self):
"""
:type: integer
"""
self._completeIfNotSet(self._watchers)
return self._watchers.value
@property
def watchers_count(self):
"""
:type: integer
"""
self._completeIfNotSet(self._watchers_count)
return self._watchers_count.value
def add_to_collaborators(self, collaborator, permission=github.GithubObject.NotSet):
"""
:calls: `PUT /repos/:owner/:repo/collaborators/:user <http://developer.github.com/v3/repos/collaborators>`_
:param collaborator: string or :class:`github.NamedUser.NamedUser`
:param permission: string 'pull', 'push' or 'admin'
:rtype: None
"""
assert isinstance(collaborator, github.NamedUser.NamedUser) or isinstance(collaborator, (str, unicode)), collaborator
assert permission is github.GithubObject.NotSet or isinstance(permission, (str, unicode)), permission
if isinstance(collaborator, github.NamedUser.NamedUser):
collaborator = collaborator._identity
if permission is not github.GithubObject.NotSet:
put_parameters = {'permission': permission}
else:
put_parameters = None
headers, data = self._requester.requestJsonAndCheck(
"PUT",
self.url + "/collaborators/" + collaborator,
headers={'Accept': 'application/vnd.github.swamp-thing-preview+json'},
input=put_parameters
)
# return an invitation object if there's data returned by the API. If data is empty
# there's a pending invitation for the given user.
return github.Invitation.Invitation(self._requester, headers, data, completed=True) if \
data is not None else None
def compare(self, base, head):
"""
:calls: `GET /repos/:owner/:repo/compare/:base...:head <http://developer.github.com/v3/repos/commits>`_
:param base: string
:param head: string
:rtype: :class:`github.Comparison.Comparison`
"""
assert isinstance(base, (str, unicode)), base
assert isinstance(head, (str, unicode)), head
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/compare/" + base + "..." + head
)
return github.Comparison.Comparison(self._requester, headers, data, completed=True)
def create_git_blob(self, content, encoding):
"""
:calls: `POST /repos/:owner/:repo/git/blobs <http://developer.github.com/v3/git/blobs>`_
:param content: string
:param encoding: string
:rtype: :class:`github.GitBlob.GitBlob`
"""
assert isinstance(content, (str, unicode)), content
assert isinstance(encoding, (str, unicode)), encoding
post_parameters = {
"content": content,
"encoding": encoding,
}
headers, data = self._requester.requestJsonAndCheck(
"POST",
self.url + "/git/blobs",
input=post_parameters
)
return github.GitBlob.GitBlob(self._requester, headers, data, completed=True)
def create_git_commit(self, message, tree, parents, author=github.GithubObject.NotSet, committer=github.GithubObject.NotSet):
"""
:calls: `POST /repos/:owner/:repo/git/commits <http://developer.github.com/v3/git/commits>`_
:param message: string
:param tree: :class:`github.GitTree.GitTree`
:param parents: list of :class:`github.GitCommit.GitCommit`
:param author: :class:`github.InputGitAuthor.InputGitAuthor`
:param committer: :class:`github.InputGitAuthor.InputGitAuthor`
:rtype: :class:`github.GitCommit.GitCommit`
"""
assert isinstance(message, (str, unicode)), message
assert isinstance(tree, github.GitTree.GitTree), tree
assert all(isinstance(element, github.GitCommit.GitCommit) for element in parents), parents
assert author is github.GithubObject.NotSet or isinstance(author, github.InputGitAuthor), author
assert committer is github.GithubObject.NotSet or isinstance(committer, github.InputGitAuthor), committer
post_parameters = {
"message": message,
"tree": tree._identity,
"parents": [element._identity for element in parents],
}
if author is not github.GithubObject.NotSet:
post_parameters["author"] = author._identity
if committer is not github.GithubObject.NotSet:
post_parameters["committer"] = committer._identity
headers, data = self._requester.requestJsonAndCheck(
"POST",
self.url + "/git/commits",
input=post_parameters
)
return github.GitCommit.GitCommit(self._requester, headers, data, completed=True)
def create_git_ref(self, ref, sha):
"""
:calls: `POST /repos/:owner/:repo/git/refs <http://developer.github.com/v3/git/refs>`_
:param ref: string
:param sha: string
:rtype: :class:`github.GitRef.GitRef`
"""
assert isinstance(ref, (str, unicode)), ref
assert isinstance(sha, (str, unicode)), sha
post_parameters = {
"ref": ref,
"sha": sha,
}
headers, data = self._requester.requestJsonAndCheck(
"POST",
self.url + "/git/refs",
input=post_parameters
)
return github.GitRef.GitRef(self._requester, headers, data, completed=True)
def create_git_tag_and_release(self, tag, tag_message, release_name, release_message, object, type, tagger=github.GithubObject.NotSet, draft=False, prerelease=False):
self.create_git_tag(tag, tag_message, object, type, tagger)
return self.create_git_release(tag, release_name, release_message, draft, prerelease)
def create_git_release(self, tag, name, message, draft=False, prerelease=False):
assert isinstance(tag, (str, unicode)), tag
assert isinstance(name, (str, unicode)), name
assert isinstance(message, (str, unicode)), message
assert isinstance(draft, bool), draft
assert isinstance(prerelease, bool), prerelease
post_parameters = {
"tag_name": tag,
"name": name,
"body": message,
"draft": draft,
"prerelease": prerelease,
}
headers, data = self._requester.requestJsonAndCheck(
"POST",
self.url + "/releases",
input=post_parameters
)
return github.GitRelease.GitRelease(self._requester, headers, data, completed=True)
def create_git_tag(self, tag, message, object, type, tagger=github.GithubObject.NotSet):
"""
:calls: `POST /repos/:owner/:repo/git/tags <http://developer.github.com/v3/git/tags>`_
:param tag: string
:param message: string
:param object: string
:param type: string
:param tagger: :class:`github.InputGitAuthor.InputGitAuthor`
:rtype: :class:`github.GitTag.GitTag`
"""
assert isinstance(tag, (str, unicode)), tag
assert isinstance(message, (str, unicode)), message
assert isinstance(object, (str, unicode)), object
assert isinstance(type, (str, unicode)), type
assert tagger is github.GithubObject.NotSet or isinstance(tagger, github.InputGitAuthor), tagger
post_parameters = {
"tag": tag,
"message": message,
"object": object,
"type": type,
}
if tagger is not github.GithubObject.NotSet:
post_parameters["tagger"] = tagger._identity
headers, data = self._requester.requestJsonAndCheck(
"POST",
self.url + "/git/tags",
input=post_parameters
)
return github.GitTag.GitTag(self._requester, headers, data, completed=True)
def create_git_tree(self, tree, base_tree=github.GithubObject.NotSet):
"""
:calls: `POST /repos/:owner/:repo/git/trees <http://developer.github.com/v3/git/trees>`_
:param tree: list of :class:`github.InputGitTreeElement.InputGitTreeElement`
:param base_tree: :class:`github.GitTree.GitTree`
:rtype: :class:`github.GitTree.GitTree`
"""
assert all(isinstance(element, github.InputGitTreeElement) for element in tree), tree
assert base_tree is github.GithubObject.NotSet or isinstance(base_tree, github.GitTree.GitTree), base_tree
post_parameters = {
"tree": [element._identity for element in tree],
}
if base_tree is not github.GithubObject.NotSet:
post_parameters["base_tree"] = base_tree._identity
headers, data = self._requester.requestJsonAndCheck(
"POST",
self.url + "/git/trees",
input=post_parameters
)
return github.GitTree.GitTree(self._requester, headers, data, completed=True)
def create_hook(self, name, config, events=github.GithubObject.NotSet, active=github.GithubObject.NotSet):
"""
:calls: `POST /repos/:owner/:repo/hooks <http://developer.github.com/v3/repos/hooks>`_
:param name: string
:param config: dict
:param events: list of string
:param active: bool
:rtype: :class:`github.Hook.Hook`
"""
assert isinstance(name, (str, unicode)), name
assert isinstance(config, dict), config
assert events is github.GithubObject.NotSet or all(isinstance(element, (str, unicode)) for element in events), events
assert active is github.GithubObject.NotSet or isinstance(active, bool), active
post_parameters = {
"name": name,
"config": config,
}
if events is not github.GithubObject.NotSet:
post_parameters["events"] = events
if active is not github.GithubObject.NotSet:
post_parameters["active"] = active
headers, data = self._requester.requestJsonAndCheck(
"POST",
self.url + "/hooks",
input=post_parameters
)
return github.Hook.Hook(self._requester, headers, data, completed=True)
def create_issue(self, title, body=github.GithubObject.NotSet, assignee=github.GithubObject.NotSet, milestone=github.GithubObject.NotSet, labels=github.GithubObject.NotSet, assignees=github.GithubObject.NotSet):
"""
:calls: `POST /repos/:owner/:repo/issues <http://developer.github.com/v3/issues>`_
:param title: string
:param body: string
:param assignee: string or :class:`github.NamedUser.NamedUser`
:param assignees: list (of string or :class:`github.NamedUser.NamedUser`)
:param milestone: :class:`github.Milestone.Milestone`
:param labels: list of :class:`github.Label.Label`
:rtype: :class:`github.Issue.Issue`
"""
assert isinstance(title, (str, unicode)), title
assert body is github.GithubObject.NotSet or isinstance(body, (str, unicode)), body
assert assignee is github.GithubObject.NotSet or isinstance(assignee, github.NamedUser.NamedUser) or isinstance(assignee, (str, unicode)), assignee
assert assignees is github.GithubObject.NotSet or all(isinstance(element, github.NamedUser.NamedUser) or isinstance(element, (str, unicode)) for element in assignees), assignees
assert milestone is github.GithubObject.NotSet or isinstance(milestone, github.Milestone.Milestone), milestone
assert labels is github.GithubObject.NotSet or all(isinstance(element, github.Label.Label) or isinstance(element, (str, unicode)) for element in labels), labels
post_parameters = {
"title": title,
}
if body is not github.GithubObject.NotSet:
post_parameters["body"] = body
if assignee is not github.GithubObject.NotSet:
if isinstance(assignee, (str, unicode)):
post_parameters["assignee"] = assignee
else:
post_parameters["assignee"] = assignee._identity
if assignees is not github.GithubObject.NotSet:
post_parameters["assignees"] = [element._identity if isinstance(element, github.NamedUser.NamedUser) else element for element in assignees]
if milestone is not github.GithubObject.NotSet:
post_parameters["milestone"] = milestone._identity
if labels is not github.GithubObject.NotSet:
post_parameters["labels"] = [element.name if isinstance(element, github.Label.Label) else element for element in labels]
headers, data = self._requester.requestJsonAndCheck(
"POST",
self.url + "/issues",
input=post_parameters
)
return github.Issue.Issue(self._requester, headers, data, completed=True)
def create_key(self, title, key, read_only=False):
"""
:calls: `POST /repos/:owner/:repo/keys <http://developer.github.com/v3/repos/keys>`_
:param title: string
:param key: string
:param read_only: bool
:rtype: :class:`github.RepositoryKey.RepositoryKey`
"""
assert isinstance(title, (str, unicode)), title
assert isinstance(key, (str, unicode)), key
assert isinstance(read_only, bool), read_only
post_parameters = {
"title": title,
"key": key,
"read_only": read_only,
}
headers, data = self._requester.requestJsonAndCheck(
"POST",
self.url + "/keys",
input=post_parameters
)
return github.RepositoryKey.RepositoryKey(self._requester, headers, data, completed=True, repoUrl=self.url)
def create_label(self, name, color):
"""
:calls: `POST /repos/:owner/:repo/labels <http://developer.github.com/v3/issues/labels>`_
:param name: string
:param color: string
:rtype: :class:`github.Label.Label`
"""
assert isinstance(name, (str, unicode)), name
assert isinstance(color, (str, unicode)), color
post_parameters = {
"name": name,
"color": color,
}
headers, data = self._requester.requestJsonAndCheck(
"POST",
self.url + "/labels",
input=post_parameters
)
return github.Label.Label(self._requester, headers, data, completed=True)
def create_milestone(self, title, state=github.GithubObject.NotSet, description=github.GithubObject.NotSet, due_on=github.GithubObject.NotSet):
"""
:calls: `POST /repos/:owner/:repo/milestones <http://developer.github.com/v3/issues/milestones>`_
:param title: string
:param state: string
:param description: string
:param due_on: datetime
:rtype: :class:`github.Milestone.Milestone`
"""
assert isinstance(title, (str, unicode)), title
assert state is github.GithubObject.NotSet or isinstance(state, (str, unicode)), state
assert description is github.GithubObject.NotSet or isinstance(description, (str, unicode)), description
assert due_on is github.GithubObject.NotSet or isinstance(due_on, (datetime.datetime, datetime.date)), due_on
post_parameters = {
"title": title,
}
if state is not github.GithubObject.NotSet:
post_parameters["state"] = state
if description is not github.GithubObject.NotSet:
post_parameters["description"] = description
if due_on is not github.GithubObject.NotSet:
if isinstance(due_on, datetime.date):
post_parameters["due_on"] = due_on.strftime("%Y-%m-%dT%H:%M:%SZ")
else:
post_parameters["due_on"] = due_on.isoformat()
headers, data = self._requester.requestJsonAndCheck(
"POST",
self.url + "/milestones",
input=post_parameters
)
return github.Milestone.Milestone(self._requester, headers, data, completed=True)
def create_pull(self, *args, **kwds):
"""
:calls: `POST /repos/:owner/:repo/pulls <http://developer.github.com/v3/pulls>`_
:param title: string
:param body: string
:param issue: :class:`github.Issue.Issue`
:param base: string
:param head: string
:param maintainer_can_modify: bool
:rtype: :class:`github.PullRequest.PullRequest`
"""
if len(args) + len(kwds) >= 4:
return self.__create_pull_1(*args, **kwds)
else:
return self.__create_pull_2(*args, **kwds)
def __create_pull_1(self, title, body, base, head, maintainer_can_modify=github.GithubObject.NotSet):
assert isinstance(title, (str, unicode)), title
assert isinstance(body, (str, unicode)), body
assert isinstance(base, (str, unicode)), base
assert isinstance(head, (str, unicode)), head
assert maintainer_can_modify is github.GithubObject.NotSet or isinstance(maintainer_can_modify, bool), maintainer_can_modify
if maintainer_can_modify is not github.GithubObject.NotSet:
return self.__create_pull(title=title, body=body, base=base, head=head, maintainer_can_modify=maintainer_can_modify)
else:
return self.__create_pull(title=title, body=body, base=base, head=head)
def __create_pull_2(self, issue, base, head):
assert isinstance(issue, github.Issue.Issue), issue
assert isinstance(base, (str, unicode)), base
assert isinstance(head, (str, unicode)), head
return self.__create_pull(issue=issue._identity, base=base, head=head)
def __create_pull(self, **kwds):
post_parameters = kwds
headers, data = self._requester.requestJsonAndCheck(
"POST",
self.url + "/pulls",
input=post_parameters
)
return github.PullRequest.PullRequest(self._requester, headers, data, completed=True)
def delete(self):
"""
:calls: `DELETE /repos/:owner/:repo <http://developer.github.com/v3/repos>`_
:rtype: None
"""
headers, data = self._requester.requestJsonAndCheck(
"DELETE",
self.url
)
def edit(self, name=None, description=github.GithubObject.NotSet, homepage=github.GithubObject.NotSet, private=github.GithubObject.NotSet, has_issues=github.GithubObject.NotSet, has_wiki=github.GithubObject.NotSet, has_downloads=github.GithubObject.NotSet, default_branch=github.GithubObject.NotSet):
"""
:calls: `PATCH /repos/:owner/:repo <http://developer.github.com/v3/repos>`_
:param name: string
:param description: string
:param homepage: string
:param private: bool
:param has_issues: bool
:param has_wiki: bool
:param has_downloads: bool
:param default_branch: string
:rtype: None
"""
if name is None:
name = self.name
assert isinstance(name, (str, unicode)), name
assert description is github.GithubObject.NotSet or isinstance(description, (str, unicode)), description
assert homepage is github.GithubObject.NotSet or isinstance(homepage, (str, unicode)), homepage
assert private is github.GithubObject.NotSet or isinstance(private, bool), private
assert has_issues is github.GithubObject.NotSet or isinstance(has_issues, bool), has_issues
assert has_wiki is github.GithubObject.NotSet or isinstance(has_wiki, bool), has_wiki
assert has_downloads is github.GithubObject.NotSet or isinstance(has_downloads, bool), has_downloads
assert default_branch is github.GithubObject.NotSet or isinstance(default_branch, (str, unicode)), default_branch
post_parameters = {
"name": name,
}
if description is not github.GithubObject.NotSet:
post_parameters["description"] = description
if homepage is not github.GithubObject.NotSet:
post_parameters["homepage"] = homepage
if private is not github.GithubObject.NotSet:
post_parameters["private"] = private
if has_issues is not github.GithubObject.NotSet:
post_parameters["has_issues"] = has_issues
if has_wiki is not github.GithubObject.NotSet:
post_parameters["has_wiki"] = has_wiki
if has_downloads is not github.GithubObject.NotSet:
post_parameters["has_downloads"] = has_downloads
if default_branch is not github.GithubObject.NotSet:
post_parameters["default_branch"] = default_branch
headers, data = self._requester.requestJsonAndCheck(
"PATCH",
self.url,
input=post_parameters
)
self._useAttributes(data)
def get_archive_link(self, archive_format, ref=github.GithubObject.NotSet):
"""
:calls: `GET /repos/:owner/:repo/:archive_format/:ref <http://developer.github.com/v3/repos/contents>`_
:param archive_format: string
:param ref: string
:rtype: string
"""
assert isinstance(archive_format, (str, unicode)), archive_format
assert ref is github.GithubObject.NotSet or isinstance(ref, (str, unicode)), ref
url = self.url + "/" + archive_format
if ref is not github.GithubObject.NotSet:
url += "/" + ref
headers, data = self._requester.requestJsonAndCheck(
"GET",
url
)
return headers["location"]
def get_assignees(self):
"""
:calls: `GET /repos/:owner/:repo/assignees <http://developer.github.com/v3/issues/assignees>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser`
"""
return github.PaginatedList.PaginatedList(
github.NamedUser.NamedUser,
self._requester,
self.url + "/assignees",
None
)
def get_branch(self, branch):
"""
:calls: `GET /repos/:owner/:repo/branches/:branch <http://developer.github.com/v3/repos>`_
:param branch: string
:rtype: :class:`github.Branch.Branch`
"""
assert isinstance(branch, (str, unicode)), branch
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/branches/" + branch
)
return github.Branch.Branch(self._requester, headers, data, completed=True)
def get_protected_branch(self, branch):
"""
:calls: `GET /repos/:owner/:repo/branches/:branch <https://developer.github.com/v3/repos/#response-10>`_
:param branch: string
:rtype: :class:`github.Branch.Branch`
"""
assert isinstance(branch, (str, unicode)), branch
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/branches/" + branch,
headers={'Accept': 'application/vnd.github.loki-preview+json'}
)
return github.Branch.Branch(self._requester, headers, data, completed=True)
def get_branches(self):
"""
:calls: `GET /repos/:owner/:repo/branches <http://developer.github.com/v3/repos>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Branch.Branch`
"""
return github.PaginatedList.PaginatedList(
github.Branch.Branch,
self._requester,
self.url + "/branches",
None
)
def get_collaborators(self):
"""
:calls: `GET /repos/:owner/:repo/collaborators <http://developer.github.com/v3/repos/collaborators>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser`
"""
return github.PaginatedList.PaginatedList(
github.NamedUser.NamedUser,
self._requester,
self.url + "/collaborators",
None
)
def get_comment(self, id):
"""
:calls: `GET /repos/:owner/:repo/comments/:id <http://developer.github.com/v3/repos/comments>`_
:param id: integer
:rtype: :class:`github.CommitComment.CommitComment`
"""
assert isinstance(id, (int, long)), id
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/comments/" + str(id)
)
return github.CommitComment.CommitComment(self._requester, headers, data, completed=True)
def get_comments(self):
"""
:calls: `GET /repos/:owner/:repo/comments <http://developer.github.com/v3/repos/comments>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.CommitComment.CommitComment`
"""
return github.PaginatedList.PaginatedList(
github.CommitComment.CommitComment,
self._requester,
self.url + "/comments",
None
)
def get_commit(self, sha):
"""
:calls: `GET /repos/:owner/:repo/commits/:sha <http://developer.github.com/v3/repos/commits>`_
:param sha: string
:rtype: :class:`github.Commit.Commit`
"""
assert isinstance(sha, (str, unicode)), sha
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/commits/" + sha
)
return github.Commit.Commit(self._requester, headers, data, completed=True)
def get_commits(self, sha=github.GithubObject.NotSet, path=github.GithubObject.NotSet, since=github.GithubObject.NotSet, until=github.GithubObject.NotSet, author=github.GithubObject.NotSet):
"""
:calls: `GET /repos/:owner/:repo/commits <http://developer.github.com/v3/repos/commits>`_
:param sha: string
:param path: string
:param since: datetime.datetime
:param until: datetime.datetime
:param author: string or :class:`github.NamedUser.NamedUser` or :class:`github.AuthenticatedUser.AuthenticatedUser`
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Commit.Commit`
"""
assert sha is github.GithubObject.NotSet or isinstance(sha, (str, unicode)), sha
assert path is github.GithubObject.NotSet or isinstance(path, (str, unicode)), path
assert since is github.GithubObject.NotSet or isinstance(since, datetime.datetime), since
assert until is github.GithubObject.NotSet or isinstance(until, datetime.datetime), until
assert author is github.GithubObject.NotSet or isinstance(author, (str, unicode, github.NamedUser.NamedUser, github.AuthenticatedUser.AuthenticatedUser)), author
url_parameters = dict()
if sha is not github.GithubObject.NotSet:
url_parameters["sha"] = sha
if path is not github.GithubObject.NotSet:
url_parameters["path"] = path
if since is not github.GithubObject.NotSet:
url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ")
if until is not github.GithubObject.NotSet:
url_parameters["until"] = until.strftime("%Y-%m-%dT%H:%M:%SZ")
if author is not github.GithubObject.NotSet:
if isinstance(author, (github.NamedUser.NamedUser, github.AuthenticatedUser.AuthenticatedUser)):
url_parameters["author"] = author.login
else:
url_parameters["author"] = author
return github.PaginatedList.PaginatedList(
github.Commit.Commit,
self._requester,
self.url + "/commits",
url_parameters
)
def get_contents(self, path, ref=github.GithubObject.NotSet):
"""
:calls: `GET /repos/:owner/:repo/contents/:path <http://developer.github.com/v3/repos/contents>`_
:param path: string
:param ref: string
:rtype: :class:`github.ContentFile.ContentFile`
"""
return self.get_file_contents(path, ref)
def get_file_contents(self, path, ref=github.GithubObject.NotSet):
"""
:calls: `GET /repos/:owner/:repo/contents/:path <http://developer.github.com/v3/repos/contents>`_
:param path: string
:param ref: string
:rtype: :class:`github.ContentFile.ContentFile`
"""
assert isinstance(path, (str, unicode)), path
assert ref is github.GithubObject.NotSet or isinstance(ref, (str, unicode)), ref
url_parameters = dict()
if ref is not github.GithubObject.NotSet:
url_parameters["ref"] = ref
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/contents" + urllib.quote(path),
parameters=url_parameters
)
if isinstance(data, list):
return [
github.ContentFile.ContentFile(self._requester, headers, item, completed=False)
for item in data
]
return github.ContentFile.ContentFile(self._requester, headers, data, completed=True)
def create_file(self, path, message, content,
branch=github.GithubObject.NotSet,
committer=github.GithubObject.NotSet,
author=github.GithubObject.NotSet):
"""Create a file in this repository.
:calls: `PUT /repos/:owner/:repo/contents/:path <http://developer.github.com/v3/repos/contents#create-a-file>`_
:param path: string, (required), path of the file in the repository
:param message: string, (required), commit message
:param content: string, (required), the actual data in the file
:param branch: string, (optional), branch to create the commit on. Defaults to the default branch of the repository
:param committer: InputGitAuthor, (optional), if no information is given the authenticated user's information will be used. You must specify both a name and email.
:param author: InputGitAuthor, (optional), if omitted this will be filled in with committer information. If passed, you must specify both a name and email.
:rtype: {
'content': :class:`ContentFile <github.ContentFile.ContentFile>`:,
'commit': :class:`Commit <github.Commit.Commit>`}
"""
assert isinstance(path, (str, unicode)), \
'path must be str/unicode object'
assert isinstance(message, (str, unicode)), \
'message must be str/unicode object'
assert isinstance(content, (str, unicode, bytes)), \
'content must be a str/unicode object'
assert branch is github.GithubObject.NotSet \
or isinstance(branch, (str, unicode)), \
'branch must be a str/unicode object'
assert author is github.GithubObject.NotSet \
or isinstance(author, github.InputGitAuthor), \
'author must be a github.InputGitAuthor object'
assert committer is github.GithubObject.NotSet \
or isinstance(committer, github.InputGitAuthor), \
'committer must be a github.InputGitAuthor object'
if atLeastPython3:
if isinstance(content, str):
content = content.encode('utf-8')
content = b64encode(content).decode('utf-8')
else:
if isinstance(content, unicode):
content = content.encode('utf-8')
content = b64encode(content)
put_parameters = {'message': message, 'content': content}
if branch is not github.GithubObject.NotSet:
put_parameters['branch'] = branch
if author is not github.GithubObject.NotSet:
put_parameters["author"] = author._identity
if committer is not github.GithubObject.NotSet:
put_parameters["committer"] = committer._identity
headers, data = self._requester.requestJsonAndCheck(
"PUT",
self.url + "/contents" + urllib.quote(path),
input=put_parameters
)
return {'content': github.ContentFile.ContentFile(self._requester, headers, data["content"], completed=False),
'commit': github.Commit.Commit(self._requester, headers, data["commit"], completed=True)}
def update_file(self, path, message, content, sha,
branch=github.GithubObject.NotSet,
committer=github.GithubObject.NotSet,
author=github.GithubObject.NotSet):
"""This method updates a file in a repository
:calls: `PUT /repos/:owner/:repo/contents/:path <http://developer.github.com/v3/repos/contents#update-a-file>`_
:param path: string, Required. The content path.
:param message: string, Required. The commit message.
:param content: string, Required. The updated file content, Base64 encoded.
:param sha: string, Required. The blob SHA of the file being replaced.
:param branch: string. The branch name. Default: the repository’s default branch (usually master)
:param committer: InputGitAuthor, (optional), if no information is given the authenticated user's information will be used. You must specify both a name and email.
:param author: InputGitAuthor, (optional), if omitted this will be filled in with committer information. If passed, you must specify both a name and email.
:rtype: {
'content': :class:`ContentFile <github.ContentFile.ContentFile>`:,
'commit': :class:`Commit <github.Commit.Commit>`}
"""
assert isinstance(path, (str, unicode)), \
'path must be str/unicode object'
assert isinstance(message, (str, unicode)), \
'message must be str/unicode object'
assert isinstance(content, (str, unicode, bytes)), \
'content must be a str/unicode object'
assert isinstance(sha, (str, unicode)), \
'sha must be a str/unicode object'
assert branch is github.GithubObject.NotSet \
or isinstance(branch, (str, unicode)), \
'branch must be a str/unicode object'
assert author is github.GithubObject.NotSet \
or isinstance(author, github.InputGitAuthor), \
'author must be a github.InputGitAuthor object'
assert committer is github.GithubObject.NotSet \
or isinstance(committer, github.InputGitAuthor), \
'committer must be a github.InputGitAuthor object'
if atLeastPython3:
if isinstance(content, str):
content = content.encode('utf-8')
content = b64encode(content).decode('utf-8')
else:
if isinstance(content, unicode):
content = content.encode('utf-8')
content = b64encode(content)
put_parameters = {'message': message, 'content': content,
'sha': sha}
if branch is not github.GithubObject.NotSet:
put_parameters['branch'] = branch
if author is not github.GithubObject.NotSet:
put_parameters["author"] = author._identity
if committer is not github.GithubObject.NotSet:
put_parameters["committer"] = committer._identity
headers, data = self._requester.requestJsonAndCheck(
"PUT",
self.url + "/contents" + urllib.quote(path),
input=put_parameters
)
return {'commit': github.Commit.Commit(self._requester, headers, data["commit"], completed=True),
'content': github.ContentFile.ContentFile(self._requester, headers, data["content"], completed=False)}
def delete_file(self, path, message, sha,
branch=github.GithubObject.NotSet,
committer=github.GithubObject.NotSet,
author=github.GithubObject.NotSet):
"""This method delete a file in a repository
:calls: `DELETE /repos/:owner/:repo/contents/:path <https://developer.github.com/v3/repos/contents/#delete-a-file>`_
:param path: string, Required. The content path.
:param message: string, Required. The commit message.
:param sha: string, Required. The blob SHA of the file being replaced.
:param branch: string. The branch name. Default: the repository’s default branch (usually master)
:param committer: InputGitAuthor, (optional), if no information is given the authenticated user's information will be used. You must specify both a name and email.
:param author: InputGitAuthor, (optional), if omitted this will be filled in with committer information. If passed, you must specify both a name and email.
:rtype: {
'content': :class:`null <github.GithubObject.NotSet>`:,
'commit': :class:`Commit <github.Commit.Commit>`}
"""
assert isinstance(path, (str, unicode)), \
'path must be str/unicode object'
assert isinstance(message, (str, unicode)), \
'message must be str/unicode object'
assert isinstance(sha, (str, unicode)), \
'sha must be a str/unicode object'
assert branch is github.GithubObject.NotSet \
or isinstance(branch, (str, unicode)), \
'branch must be a str/unicode object'
assert author is github.GithubObject.NotSet \
or isinstance(author, github.InputGitAuthor), \
'author must be a github.InputGitAuthor object'
assert committer is github.GithubObject.NotSet \
or isinstance(committer, github.InputGitAuthor), \
'committer must be a github.InputGitAuthor object'
url_parameters = {'message': message, 'sha': sha}
if branch is not github.GithubObject.NotSet:
url_parameters['branch'] = branch
if author is not github.GithubObject.NotSet:
url_parameters["author"] = author._identity
if committer is not github.GithubObject.NotSet:
url_parameters["committer"] = committer._identity
headers, data = self._requester.requestJsonAndCheck(
"DELETE",
self.url + "/contents" + urllib.quote(path),
input=url_parameters
)
return {'commit': github.Commit.Commit(self._requester, headers, data["commit"], completed=True),
'content': github.GithubObject.NotSet}
def get_dir_contents(self, path, ref=github.GithubObject.NotSet):
"""
:calls: `GET /repos/:owner/:repo/contents/:path <http://developer.github.com/v3/repos/contents>`_
:param path: string
:param ref: string
:rtype: list of :class:`github.ContentFile.ContentFile`
"""
assert isinstance(path, (str, unicode)), path
assert ref is github.GithubObject.NotSet or isinstance(ref, (str, unicode)), ref
url_parameters = dict()
if ref is not github.GithubObject.NotSet:
url_parameters["ref"] = ref
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/contents" + urllib.quote(path),
parameters=url_parameters
)
# Handle 302 redirect response
if headers.get('status') == '302 Found' and headers.get('location'):
headers, data = self._requester.requestJsonAndCheck(
"GET",
headers['location'],
parameters=url_parameters
)
return [
github.ContentFile.ContentFile(self._requester, headers, attributes, completed=(attributes["type"] != "file")) # Lazy completion only makes sense for files. See discussion here: https://github.com/jacquev6/PyGithub/issues/140#issuecomment-13481130
for attributes in data
]
def get_contributors(self):
"""
:calls: `GET /repos/:owner/:repo/contributors <http://developer.github.com/v3/repos>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser`
"""
return github.PaginatedList.PaginatedList(
github.NamedUser.NamedUser,
self._requester,
self.url + "/contributors",
None
)
def get_download(self, id):
"""
:calls: `GET /repos/:owner/:repo/downloads/:id <http://developer.github.com/v3/repos/downloads>`_
:param id: integer
:rtype: :class:`github.Download.Download`
"""
assert isinstance(id, (int, long)), id
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/downloads/" + str(id)
)
return github.Download.Download(self._requester, headers, data, completed=True)
def get_downloads(self):
"""
:calls: `GET /repos/:owner/:repo/downloads <http://developer.github.com/v3/repos/downloads>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Download.Download`
"""
return github.PaginatedList.PaginatedList(
github.Download.Download,
self._requester,
self.url + "/downloads",
None
)
def get_events(self):
"""
:calls: `GET /repos/:owner/:repo/events <http://developer.github.com/v3/activity/events>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Event.Event`
"""
return github.PaginatedList.PaginatedList(
github.Event.Event,
self._requester,
self.url + "/events",
None
)
def get_forks(self):
"""
:calls: `GET /repos/:owner/:repo/forks <http://developer.github.com/v3/repos/forks>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository`
"""
return github.PaginatedList.PaginatedList(
Repository,
self._requester,
self.url + "/forks",
None
)
def get_git_blob(self, sha):
"""
:calls: `GET /repos/:owner/:repo/git/blobs/:sha <http://developer.github.com/v3/git/blobs>`_
:param sha: string
:rtype: :class:`github.GitBlob.GitBlob`
"""
assert isinstance(sha, (str, unicode)), sha
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/git/blobs/" + sha
)
return github.GitBlob.GitBlob(self._requester, headers, data, completed=True)
def get_git_commit(self, sha):
"""
:calls: `GET /repos/:owner/:repo/git/commits/:sha <http://developer.github.com/v3/git/commits>`_
:param sha: string
:rtype: :class:`github.GitCommit.GitCommit`
"""
assert isinstance(sha, (str, unicode)), sha
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/git/commits/" + sha
)
return github.GitCommit.GitCommit(self._requester, headers, data, completed=True)
def get_git_ref(self, ref):
"""
:calls: `GET /repos/:owner/:repo/git/refs/:ref <http://developer.github.com/v3/git/refs>`_
:param ref: string
:rtype: :class:`github.GitRef.GitRef`
"""
prefix = "/git/refs/"
if not self._requester.FIX_REPO_GET_GIT_REF:
prefix = "/git/"
assert isinstance(ref, (str, unicode)), ref
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + prefix + ref
)
return github.GitRef.GitRef(self._requester, headers, data, completed=True)
def get_git_refs(self):
"""
:calls: `GET /repos/:owner/:repo/git/refs <http://developer.github.com/v3/git/refs>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.GitRef.GitRef`
"""
return github.PaginatedList.PaginatedList(
github.GitRef.GitRef,
self._requester,
self.url + "/git/refs",
None
)
def get_git_tag(self, sha):
"""
:calls: `GET /repos/:owner/:repo/git/tags/:sha <http://developer.github.com/v3/git/tags>`_
:param sha: string
:rtype: :class:`github.GitTag.GitTag`
"""
assert isinstance(sha, (str, unicode)), sha
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/git/tags/" + sha
)
return github.GitTag.GitTag(self._requester, headers, data, completed=True)
def get_git_tree(self, sha, recursive=github.GithubObject.NotSet):
"""
:calls: `GET /repos/:owner/:repo/git/trees/:sha <http://developer.github.com/v3/git/trees>`_
:param sha: string
:param recursive: bool
:rtype: :class:`github.GitTree.GitTree`
"""
assert isinstance(sha, (str, unicode)), sha
assert recursive is github.GithubObject.NotSet or isinstance(recursive, bool), recursive
url_parameters = dict()
if recursive is not github.GithubObject.NotSet:
url_parameters["recursive"] = recursive
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/git/trees/" + sha,
parameters=url_parameters
)
return github.GitTree.GitTree(self._requester, headers, data, completed=True)
def get_hook(self, id):
"""
:calls: `GET /repos/:owner/:repo/hooks/:id <http://developer.github.com/v3/repos/hooks>`_
:param id: integer
:rtype: :class:`github.Hook.Hook`
"""
assert isinstance(id, (int, long)), id
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/hooks/" + str(id)
)
return github.Hook.Hook(self._requester, headers, data, completed=True)
def get_hooks(self):
"""
:calls: `GET /repos/:owner/:repo/hooks <http://developer.github.com/v3/repos/hooks>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Hook.Hook`
"""
return github.PaginatedList.PaginatedList(
github.Hook.Hook,
self._requester,
self.url + "/hooks",
None
)
def get_issue(self, number):
"""
:calls: `GET /repos/:owner/:repo/issues/:number <http://developer.github.com/v3/issues>`_
:param number: integer
:rtype: :class:`github.Issue.Issue`
"""
assert isinstance(number, (int, long)), number
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/issues/" + str(number)
)
return github.Issue.Issue(self._requester, headers, data, completed=True)
def get_issues(self, milestone=github.GithubObject.NotSet, state=github.GithubObject.NotSet, assignee=github.GithubObject.NotSet, mentioned=github.GithubObject.NotSet, labels=github.GithubObject.NotSet, sort=github.GithubObject.NotSet, direction=github.GithubObject.NotSet, since=github.GithubObject.NotSet, creator=github.GithubObject.NotSet):
"""
:calls: `GET /repos/:owner/:repo/issues <http://developer.github.com/v3/issues>`_
:param milestone: :class:`github.Milestone.Milestone` or "none" or "*"
:param state: string
:param assignee: string or :class:`github.NamedUser.NamedUser` or "none" or "*"
:param mentioned: :class:`github.NamedUser.NamedUser`
:param labels: list of :class:`github.Label.Label`
:param sort: string
:param direction: string
:param since: datetime.datetime
:param creator: string or :class:`github.NamedUser.NamedUser`
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Issue.Issue`
"""
assert milestone is github.GithubObject.NotSet or milestone == "*" or milestone == "none" or isinstance(milestone, github.Milestone.Milestone), milestone
assert state is github.GithubObject.NotSet or isinstance(state, (str, unicode)), state
assert assignee is github.GithubObject.NotSet or isinstance(assignee, github.NamedUser.NamedUser) or isinstance(assignee, (str, unicode)), assignee
assert mentioned is github.GithubObject.NotSet or isinstance(mentioned, github.NamedUser.NamedUser), mentioned
assert labels is github.GithubObject.NotSet or all(isinstance(element, github.Label.Label) for element in labels), labels
assert sort is github.GithubObject.NotSet or isinstance(sort, (str, unicode)), sort
assert direction is github.GithubObject.NotSet or isinstance(direction, (str, unicode)), direction
assert since is github.GithubObject.NotSet or isinstance(since, datetime.datetime), since
assert creator is github.GithubObject.NotSet or isinstance(creator, github.NamedUser.NamedUser) or isinstance(creator, (str, unicode)), creator
url_parameters = dict()
if milestone is not github.GithubObject.NotSet:
if isinstance(milestone, (str, unicode)):
url_parameters["milestone"] = milestone
else:
url_parameters["milestone"] = milestone._identity
if state is not github.GithubObject.NotSet:
url_parameters["state"] = state
if assignee is not github.GithubObject.NotSet:
if isinstance(assignee, (str, unicode)):
url_parameters["assignee"] = assignee
else:
url_parameters["assignee"] = assignee._identity
if mentioned is not github.GithubObject.NotSet:
url_parameters["mentioned"] = mentioned._identity
if labels is not github.GithubObject.NotSet:
url_parameters["labels"] = ",".join(label.name for label in labels)
if sort is not github.GithubObject.NotSet:
url_parameters["sort"] = sort
if direction is not github.GithubObject.NotSet:
url_parameters["direction"] = direction
if since is not github.GithubObject.NotSet:
url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ")
if creator is not github.GithubObject.NotSet:
if isinstance(creator, (str, unicode)):
url_parameters["creator"] = creator
else:
url_parameters["creator"] = creator._identity
return github.PaginatedList.PaginatedList(
github.Issue.Issue,
self._requester,
self.url + "/issues",
url_parameters
)
def get_issues_comments(self, sort=github.GithubObject.NotSet, direction=github.GithubObject.NotSet, since=github.GithubObject.NotSet):
"""
:calls: `GET /repos/:owner/:repo/issues/comments <http://developer.github.com/v3/issues/comments>`_
:param sort: string
:param direction: string
:param since: datetime.datetime
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.IssueComment.IssueComment`
"""
assert sort is github.GithubObject.NotSet or isinstance(sort, (str, unicode)), sort
assert direction is github.GithubObject.NotSet or isinstance(direction, (str, unicode)), direction
assert since is github.GithubObject.NotSet or isinstance(since, datetime.datetime), since
url_parameters = dict()
if sort is not github.GithubObject.NotSet:
url_parameters["sort"] = sort
if direction is not github.GithubObject.NotSet:
url_parameters["direction"] = direction
if since is not github.GithubObject.NotSet:
url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ")
return github.PaginatedList.PaginatedList(
github.IssueComment.IssueComment,
self._requester,
self.url + "/issues/comments",
url_parameters
)
def get_issues_event(self, id):
"""
:calls: `GET /repos/:owner/:repo/issues/events/:id <http://developer.github.com/v3/issues/events>`_
:param id: integer
:rtype: :class:`github.IssueEvent.IssueEvent`
"""
assert isinstance(id, (int, long)), id
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/issues/events/" + str(id)
)
return github.IssueEvent.IssueEvent(self._requester, headers, data, completed=True)
def get_issues_events(self):
"""
:calls: `GET /repos/:owner/:repo/issues/events <http://developer.github.com/v3/issues/events>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.IssueEvent.IssueEvent`
"""
return github.PaginatedList.PaginatedList(
github.IssueEvent.IssueEvent,
self._requester,
self.url + "/issues/events",
None
)
def get_key(self, id):
"""
:calls: `GET /repos/:owner/:repo/keys/:id <http://developer.github.com/v3/repos/keys>`_
:param id: integer
:rtype: :class:`github.RepositoryKey.RepositoryKey`
"""
assert isinstance(id, (int, long)), id
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/keys/" + str(id)
)
return github.RepositoryKey.RepositoryKey(self._requester, headers, data, completed=True, repoUrl=self.url)
def get_keys(self):
"""
:calls: `GET /repos/:owner/:repo/keys <http://developer.github.com/v3/repos/keys>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.RepositoryKey.RepositoryKey`
"""
return github.PaginatedList.PaginatedList(
lambda requester, headers, data, completed: github.RepositoryKey.RepositoryKey(requester, headers, data, completed, repoUrl=self.url),
self._requester,
self.url + "/keys",
None
)
def get_label(self, name):
"""
:calls: `GET /repos/:owner/:repo/labels/:name <http://developer.github.com/v3/issues/labels>`_
:param name: string
:rtype: :class:`github.Label.Label`
"""
assert isinstance(name, (str, unicode)), name
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/labels/" + urllib.quote(name)
)
return github.Label.Label(self._requester, headers, data, completed=True)
def get_labels(self):
"""
:calls: `GET /repos/:owner/:repo/labels <http://developer.github.com/v3/issues/labels>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Label.Label`
"""
return github.PaginatedList.PaginatedList(
github.Label.Label,
self._requester,
self.url + "/labels",
None
)
def get_languages(self):
"""
:calls: `GET /repos/:owner/:repo/languages <http://developer.github.com/v3/repos>`_
:rtype: dict of string to integer
"""
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/languages"
)
return data
def get_milestone(self, number):
"""
:calls: `GET /repos/:owner/:repo/milestones/:number <http://developer.github.com/v3/issues/milestones>`_
:param number: integer
:rtype: :class:`github.Milestone.Milestone`
"""
assert isinstance(number, (int, long)), number
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/milestones/" + str(number)
)
return github.Milestone.Milestone(self._requester, headers, data, completed=True)
def get_milestones(self, state=github.GithubObject.NotSet, sort=github.GithubObject.NotSet, direction=github.GithubObject.NotSet):
"""
:calls: `GET /repos/:owner/:repo/milestones <http://developer.github.com/v3/issues/milestones>`_
:param state: string
:param sort: string
:param direction: string
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Milestone.Milestone`
"""
assert state is github.GithubObject.NotSet or isinstance(state, (str, unicode)), state
assert sort is github.GithubObject.NotSet or isinstance(sort, (str, unicode)), sort
assert direction is github.GithubObject.NotSet or isinstance(direction, (str, unicode)), direction
url_parameters = dict()
if state is not github.GithubObject.NotSet:
url_parameters["state"] = state
if sort is not github.GithubObject.NotSet:
url_parameters["sort"] = sort
if direction is not github.GithubObject.NotSet:
url_parameters["direction"] = direction
return github.PaginatedList.PaginatedList(
github.Milestone.Milestone,
self._requester,
self.url + "/milestones",
url_parameters
)
def get_network_events(self):
"""
:calls: `GET /networks/:owner/:repo/events <http://developer.github.com/v3/activity/events>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Event.Event`
"""
return github.PaginatedList.PaginatedList(
github.Event.Event,
self._requester,
"/networks/" + self.owner.login + "/" + self.name + "/events",
None
)
def get_pull(self, number):
"""
:calls: `GET /repos/:owner/:repo/pulls/:number <http://developer.github.com/v3/pulls>`_
:param number: integer
:rtype: :class:`github.PullRequest.PullRequest`
"""
assert isinstance(number, (int, long)), number
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/pulls/" + str(number)
)
return github.PullRequest.PullRequest(self._requester, headers, data, completed=True)
def get_pulls(self, state=github.GithubObject.NotSet, sort=github.GithubObject.NotSet, direction=github.GithubObject.NotSet, base=github.GithubObject.NotSet, head=github.GithubObject.NotSet):
"""
:calls: `GET /repos/:owner/:repo/pulls <http://developer.github.com/v3/pulls>`_
:param state: string
:param sort: string
:param direction: string
:param base: string
:param head: string
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.PullRequest.PullRequest`
"""
assert state is github.GithubObject.NotSet or isinstance(state, (str, unicode)), state
assert sort is github.GithubObject.NotSet or isinstance(sort, (str, unicode)), sort
assert direction is github.GithubObject.NotSet or isinstance(direction, (str, unicode)), direction
assert base is github.GithubObject.NotSet or isinstance(base, (str, unicode)), base
assert head is github.GithubObject.NotSet or isinstance(head, (str, unicode)), head
url_parameters = dict()
if state is not github.GithubObject.NotSet:
url_parameters["state"] = state
if sort is not github.GithubObject.NotSet:
url_parameters["sort"] = sort
if direction is not github.GithubObject.NotSet:
url_parameters["direction"] = direction
if base is not github.GithubObject.NotSet:
url_parameters["base"] = base
if head is not github.GithubObject.NotSet:
url_parameters["head"] = head
return github.PaginatedList.PaginatedList(
github.PullRequest.PullRequest,
self._requester,
self.url + "/pulls",
url_parameters
)
def get_pulls_comments(self, sort=github.GithubObject.NotSet, direction=github.GithubObject.NotSet, since=github.GithubObject.NotSet):
"""
:calls: `GET /repos/:owner/:repo/pulls/comments <http://developer.github.com/v3/pulls/comments>`_
:param sort: string
:param direction: string
:param since: datetime.datetime
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.PullRequestComment.PullRequestComment`
"""
return self.get_pulls_review_comments(sort, direction, since)
def get_pulls_review_comments(self, sort=github.GithubObject.NotSet, direction=github.GithubObject.NotSet, since=github.GithubObject.NotSet):
"""
:calls: `GET /repos/:owner/:repo/pulls/comments <http://developer.github.com/v3/pulls/comments>`_
:param sort: string
:param direction: string
:param since: datetime.datetime
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.PullRequestComment.PullRequestComment`
"""
assert sort is github.GithubObject.NotSet or isinstance(sort, (str, unicode)), sort
assert direction is github.GithubObject.NotSet or isinstance(direction, (str, unicode)), direction
assert since is github.GithubObject.NotSet or isinstance(since, datetime.datetime), since
url_parameters = dict()
if sort is not github.GithubObject.NotSet:
url_parameters["sort"] = sort
if direction is not github.GithubObject.NotSet:
url_parameters["direction"] = direction
if since is not github.GithubObject.NotSet:
url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ")
return github.PaginatedList.PaginatedList(
github.IssueComment.IssueComment,
self._requester,
self.url + "/pulls/comments",
url_parameters
)
def get_readme(self, ref=github.GithubObject.NotSet):
"""
:calls: `GET /repos/:owner/:repo/readme <http://developer.github.com/v3/repos/contents>`_
:param ref: string
:rtype: :class:`github.ContentFile.ContentFile`
"""
assert ref is github.GithubObject.NotSet or isinstance(ref, (str, unicode)), ref
url_parameters = dict()
if ref is not github.GithubObject.NotSet:
url_parameters["ref"] = ref
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/readme",
parameters=url_parameters
)
return github.ContentFile.ContentFile(self._requester, headers, data, completed=True)
def get_stargazers(self):
"""
:calls: `GET /repos/:owner/:repo/stargazers <http://developer.github.com/v3/activity/starring>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser`
"""
return github.PaginatedList.PaginatedList(
github.NamedUser.NamedUser,
self._requester,
self.url + "/stargazers",
None
)
def get_stargazers_with_dates(self):
"""
:calls: `GET /repos/:owner/:repo/stargazers <http://developer.github.com/v3/activity/starring>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Stargazer.Stargazer`
"""
return github.PaginatedList.PaginatedList(
github.Stargazer.Stargazer,
self._requester,
self.url + "/stargazers",
None,
headers={'Accept': 'application/vnd.github.v3.star+json'}
)
def get_stats_contributors(self):
"""
:calls: `GET /repos/:owner/:repo/stats/contributors <http://developer.github.com/v3/repos/statistics/#get-contributors-list-with-additions-deletions-and-commit-counts>`_
:rtype: None or list of :class:`github.StatsContributor.StatsContributor`
"""
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/stats/contributors"
)
if not data:
return None
else:
return [
github.StatsContributor.StatsContributor(self._requester, headers, attributes, completed=True)
for attributes in data
]
def get_stats_commit_activity(self):
"""
:calls: `GET /repos/:owner/:repo/stats/commit_activity <developer.github.com/v3/repos/statistics/#get-the-number-of-commits-per-hour-in-each-day>`_
:rtype: None or list of :class:`github.StatsCommitActivity.StatsCommitActivity`
"""
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/stats/commit_activity"
)
if not data:
return None
else:
return [
github.StatsCommitActivity.StatsCommitActivity(self._requester, headers, attributes, completed=True)
for attributes in data
]
def get_stats_code_frequency(self):
"""
:calls: `GET /repos/:owner/:repo/stats/code_frequency <http://developer.github.com/v3/repos/statistics/#get-the-number-of-additions-and-deletions-per-week>`_
:rtype: None or list of :class:`github.StatsCodeFrequency.StatsCodeFrequency`
"""
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/stats/code_frequency"
)
if not data:
return None
else:
return [
github.StatsCodeFrequency.StatsCodeFrequency(self._requester, headers, attributes, completed=True)
for attributes in data
]
def get_stats_participation(self):
"""
:calls: `GET /repos/:owner/:repo/stats/participation <http://developer.github.com/v3/repos/statistics/#get-the-weekly-commit-count-for-the-repo-owner-and-everyone-else>`_
:rtype: None or :class:`github.StatsParticipation.StatsParticipation`
"""
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/stats/participation"
)
if not data:
return None
else:
return github.StatsParticipation.StatsParticipation(self._requester, headers, data, completed=True)
def get_stats_punch_card(self):
"""
:calls: `GET /repos/:owner/:repo/stats/punch_card <http://developer.github.com/v3/repos/statistics/#get-the-number-of-commits-per-hour-in-each-day>`_
:rtype: None or :class:`github.StatsPunchCard.StatsPunchCard`
"""
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/stats/punch_card"
)
if not data:
return None
else:
return github.StatsPunchCard.StatsPunchCard(self._requester, headers, data, completed=True)
def get_subscribers(self):
"""
:calls: `GET /repos/:owner/:repo/subscribers <http://developer.github.com/v3/activity/watching>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser`
"""
return github.PaginatedList.PaginatedList(
github.NamedUser.NamedUser,
self._requester,
self.url + "/subscribers",
None
)
def get_tags(self):
"""
:calls: `GET /repos/:owner/:repo/tags <http://developer.github.com/v3/repos>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Tag.Tag`
"""
return github.PaginatedList.PaginatedList(
github.Tag.Tag,
self._requester,
self.url + "/tags",
None
)
def get_releases(self):
"""
:calls: `GET /repos/:owner/:repo/releases <http://developer.github.com/v3/repos>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Tag.Tag`
"""
return github.PaginatedList.PaginatedList(
github.GitRelease.GitRelease,
self._requester,
self.url + "/releases",
None
)
def get_release(self, id):
"""
:calls: `GET /repos/:owner/:repo/releases/:id https://developer.github.com/v3/repos/releases/#get-a-single-release
:param id: int (release id), str (tag name)
:rtype: None or :class:`github.GitRelease.GitRelease`
"""
if isinstance(id, int):
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/releases/" + str(id)
)
return github.GitRelease.GitRelease(self._requester, headers, data, completed=True)
elif isinstance(id, (str, unicode)):
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/releases/tags/" + id
)
return github.GitRelease.GitRelease(self._requester, headers, data, completed=True)
def get_latest_release(self):
"""
:calls: `GET /repos/:owner/:repo/releases/latest https://developer.github.com/v3/repos/releases/#get-the-latest-release
:rtype: :class:`github.GitRelease.GitRelease`
"""
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/releases/latest"
)
return github.GitRelease.GitRelease(self._requester, headers, data, completed=True)
def get_teams(self):
"""
:calls: `GET /repos/:owner/:repo/teams <http://developer.github.com/v3/repos>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Team.Team`
"""
return github.PaginatedList.PaginatedList(
github.Team.Team,
self._requester,
self.url + "/teams",
None
)
def get_watchers(self):
"""
:calls: `GET /repos/:owner/:repo/watchers <http://developer.github.com/v3/activity/starring>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser`
"""
return github.PaginatedList.PaginatedList(
github.NamedUser.NamedUser,
self._requester,
self.url + "/watchers",
None
)
def has_in_assignees(self, assignee):
"""
:calls: `GET /repos/:owner/:repo/assignees/:assignee <http://developer.github.com/v3/issues/assignees>`_
:param assignee: string or :class:`github.NamedUser.NamedUser`
:rtype: bool
"""
assert isinstance(assignee, github.NamedUser.NamedUser) or isinstance(assignee, (str, unicode)), assignee
if isinstance(assignee, github.NamedUser.NamedUser):
assignee = assignee._identity
status, headers, data = self._requester.requestJson(
"GET",
self.url + "/assignees/" + assignee
)
return status == 204
def has_in_collaborators(self, collaborator):
"""
:calls: `GET /repos/:owner/:repo/collaborators/:user <http://developer.github.com/v3/repos/collaborators>`_
:param collaborator: string or :class:`github.NamedUser.NamedUser`
:rtype: bool
"""
assert isinstance(collaborator, github.NamedUser.NamedUser) or isinstance(collaborator, (str, unicode)), collaborator
if isinstance(collaborator, github.NamedUser.NamedUser):
collaborator = collaborator._identity
status, headers, data = self._requester.requestJson(
"GET",
self.url + "/collaborators/" + collaborator
)
return status == 204
def legacy_search_issues(self, state, keyword):
"""
:calls: `GET /legacy/issues/search/:owner/:repository/:state/:keyword <http://developer.github.com/v3/search/legacy>`_
:param state: "open" or "closed"
:param keyword: string
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Issue.Issue`
"""
assert state in ["open", "closed"], state
assert isinstance(keyword, (str, unicode)), keyword
headers, data = self._requester.requestJsonAndCheck(
"GET",
"/legacy/issues/search/" + self.owner.login + "/" + self.name + "/" + state + "/" + urllib.quote(keyword)
)
return [
github.Issue.Issue(self._requester, headers, github.Legacy.convertIssue(element), completed=False)
for element in data["issues"]
]
def merge(self, base, head, commit_message=github.GithubObject.NotSet):
"""
:calls: `POST /repos/:owner/:repo/merges <http://developer.github.com/v3/repos/merging>`_
:param base: string
:param head: string
:param commit_message: string
:rtype: :class:`github.Commit.Commit`
"""
assert isinstance(base, (str, unicode)), base
assert isinstance(head, (str, unicode)), head
assert commit_message is github.GithubObject.NotSet or isinstance(commit_message, (str, unicode)), commit_message
post_parameters = {
"base": base,
"head": head,
}
if commit_message is not github.GithubObject.NotSet:
post_parameters["commit_message"] = commit_message
headers, data = self._requester.requestJsonAndCheck(
"POST",
self.url + "/merges",
input=post_parameters
)
if data is None:
return None
else:
return github.Commit.Commit(self._requester, headers, data, completed=True)
def protect_branch(self, branch, enabled, enforcement_level=github.GithubObject.NotSet, contexts=github.GithubObject.NotSet):
"""
:calls: `PATCH /repos/:owner/:repo/branches/:branch <https://developer.github.com/v3/repos/#enabling-and-disabling-branch-protection>`_
:param branch: string
:param enabled: boolean
:param enforcement_level: string
:param contexts: list of strings
:rtype: None
"""
assert isinstance(branch, (str, unicode))
assert isinstance(enabled, bool)
assert enforcement_level is github.GithubObject.NotSet or isinstance(enforcement_level, (str, unicode)), enforcement_level
assert contexts is github.GithubObject.NotSet or all(isinstance(element, (str, unicode)) or isinstance(element, (str, unicode)) for element in contexts), contexts
post_parameters = {
"protection": {}
}
if enabled is not github.GithubObject.NotSet:
post_parameters["protection"]["enabled"] = enabled
if enforcement_level is not github.GithubObject.NotSet:
post_parameters["protection"]["required_status_checks"] = {}
post_parameters["protection"]["required_status_checks"]["enforcement_level"] = enforcement_level
if contexts is not github.GithubObject.NotSet:
post_parameters["protection"]["required_status_checks"]["contexts"] = contexts
headers, data = self._requester.requestJsonAndCheck(
"PATCH",
self.url + "/branches/" + branch,
input=post_parameters,
headers={'Accept': 'application/vnd.github.loki-preview+json'}
)
def remove_from_collaborators(self, collaborator):
"""
:calls: `DELETE /repos/:owner/:repo/collaborators/:user <http://developer.github.com/v3/repos/collaborators>`_
:param collaborator: string or :class:`github.NamedUser.NamedUser`
:rtype: None
"""
assert isinstance(collaborator, github.NamedUser.NamedUser) or isinstance(collaborator, (str, unicode)), collaborator
if isinstance(collaborator, github.NamedUser.NamedUser):
collaborator = collaborator._identity
headers, data = self._requester.requestJsonAndCheck(
"DELETE",
self.url + "/collaborators/" + collaborator
)
def subscribe_to_hub(self, event, callback, secret=github.GithubObject.NotSet):
"""
:calls: `POST /hub <http://developer.github.com/>`_
:param event: string
:param callback: string
:param secret: string
:rtype: None
"""
return self._hub("subscribe", event, callback, secret)
def unsubscribe_from_hub(self, event, callback):
"""
:calls: `POST /hub <http://developer.github.com/>`_
:param event: string
:param callback: string
:param secret: string
:rtype: None
"""
return self._hub("unsubscribe", event, callback, github.GithubObject.NotSet)
def _hub(self, mode, event, callback, secret):
assert isinstance(mode, (str, unicode)), mode
assert isinstance(event, (str, unicode)), event
assert isinstance(callback, (str, unicode)), callback
assert secret is github.GithubObject.NotSet or isinstance(secret, (str, unicode)), secret
post_parameters = {
"hub.mode": mode,
"hub.topic": "https://github.com/" + self.full_name + "/events/" + event,
"hub.callback": callback,
}
if secret is not github.GithubObject.NotSet:
post_parameters["hub.secret"] = secret
headers, output = self._requester.requestMultipartAndCheck(
"POST",
"/hub",
input=post_parameters
)
@property
def _identity(self):
return self.owner.login + "/" + self.name
def get_release_asset(self, id):
assert isinstance(id, (int)), id
resp_headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/releases/assets/" + str(id)
)
return github.GitReleaseAsset.GitReleaseAsset(self._requester, resp_headers, data, completed=True)
def _initAttributes(self):
self._archived = github.GithubObject.NotSet
self._archive_url = github.GithubObject.NotSet
self._assignees_url = github.GithubObject.NotSet
self._blobs_url = github.GithubObject.NotSet
self._branches_url = github.GithubObject.NotSet
self._clone_url = github.GithubObject.NotSet
self._collaborators_url = github.GithubObject.NotSet
self._comments_url = github.GithubObject.NotSet
self._commits_url = github.GithubObject.NotSet
self._compare_url = github.GithubObject.NotSet
self._contents_url = github.GithubObject.NotSet
self._contributors_url = github.GithubObject.NotSet
self._created_at = github.GithubObject.NotSet
self._default_branch = github.GithubObject.NotSet
self._description = github.GithubObject.NotSet
self._downloads_url = github.GithubObject.NotSet
self._events_url = github.GithubObject.NotSet
self._fork = github.GithubObject.NotSet
self._forks = github.GithubObject.NotSet
self._forks_count = github.GithubObject.NotSet
self._forks_url = github.GithubObject.NotSet
self._full_name = github.GithubObject.NotSet
self._git_commits_url = github.GithubObject.NotSet
self._git_refs_url = github.GithubObject.NotSet
self._git_tags_url = github.GithubObject.NotSet
self._git_url = github.GithubObject.NotSet
self._has_downloads = github.GithubObject.NotSet
self._has_issues = github.GithubObject.NotSet
self._has_wiki = github.GithubObject.NotSet
self._homepage = github.GithubObject.NotSet
self._hooks_url = github.GithubObject.NotSet
self._html_url = github.GithubObject.NotSet
self._id = github.GithubObject.NotSet
self._issue_comment_url = github.GithubObject.NotSet
self._issue_events_url = github.GithubObject.NotSet
self._issues_url = github.GithubObject.NotSet
self._keys_url = github.GithubObject.NotSet
self._labels_url = github.GithubObject.NotSet
self._language = github.GithubObject.NotSet
self._languages_url = github.GithubObject.NotSet
self._master_branch = github.GithubObject.NotSet
self._merges_url = github.GithubObject.NotSet
self._milestones_url = github.GithubObject.NotSet
self._mirror_url = github.GithubObject.NotSet
self._name = github.GithubObject.NotSet
self._network_count = github.GithubObject.NotSet
self._notifications_url = github.GithubObject.NotSet
self._open_issues = github.GithubObject.NotSet
self._open_issues_count = github.GithubObject.NotSet
self._organization = github.GithubObject.NotSet
self._owner = github.GithubObject.NotSet
self._parent = github.GithubObject.NotSet
self._permissions = github.GithubObject.NotSet
self._private = github.GithubObject.NotSet
self._pulls_url = github.GithubObject.NotSet
self._pushed_at = github.GithubObject.NotSet
self._size = github.GithubObject.NotSet
self._source = github.GithubObject.NotSet
self._ssh_url = github.GithubObject.NotSet
self._stargazers_count = github.GithubObject.NotSet
self._stargazers_url = github.GithubObject.NotSet
self._statuses_url = github.GithubObject.NotSet
self._subscribers_url = github.GithubObject.NotSet
self._subscribers_count = github.GithubObject.NotSet
self._subscription_url = github.GithubObject.NotSet
self._svn_url = github.GithubObject.NotSet
self._tags_url = github.GithubObject.NotSet
self._teams_url = github.GithubObject.NotSet
self._trees_url = github.GithubObject.NotSet
self._updated_at = github.GithubObject.NotSet
self._url = github.GithubObject.NotSet
self._watchers = github.GithubObject.NotSet
self._watchers_count = github.GithubObject.NotSet
def _useAttributes(self, attributes):
if "archived" in attributes: # pragma no branch
self._archived = self._makeBoolAttribute(attributes["archived"])
if "archive_url" in attributes: # pragma no branch
self._archive_url = self._makeStringAttribute(attributes["archive_url"])
if "assignees_url" in attributes: # pragma no branch
self._assignees_url = self._makeStringAttribute(attributes["assignees_url"])
if "blobs_url" in attributes: # pragma no branch
self._blobs_url = self._makeStringAttribute(attributes["blobs_url"])
if "branches_url" in attributes: # pragma no branch
self._branches_url = self._makeStringAttribute(attributes["branches_url"])
if "clone_url" in attributes: # pragma no branch
self._clone_url = self._makeStringAttribute(attributes["clone_url"])
if "collaborators_url" in attributes: # pragma no branch
self._collaborators_url = self._makeStringAttribute(attributes["collaborators_url"])
if "comments_url" in attributes: # pragma no branch
self._comments_url = self._makeStringAttribute(attributes["comments_url"])
if "commits_url" in attributes: # pragma no branch
self._commits_url = self._makeStringAttribute(attributes["commits_url"])
if "compare_url" in attributes: # pragma no branch
self._compare_url = self._makeStringAttribute(attributes["compare_url"])
if "contents_url" in attributes: # pragma no branch
self._contents_url = self._makeStringAttribute(attributes["contents_url"])
if "contributors_url" in attributes: # pragma no branch
self._contributors_url = self._makeStringAttribute(attributes["contributors_url"])
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "default_branch" in attributes: # pragma no branch
self._default_branch = self._makeStringAttribute(attributes["default_branch"])
if "description" in attributes: # pragma no branch
self._description = self._makeStringAttribute(attributes["description"])
if "downloads_url" in attributes: # pragma no branch
self._downloads_url = self._makeStringAttribute(attributes["downloads_url"])
if "events_url" in attributes: # pragma no branch
self._events_url = self._makeStringAttribute(attributes["events_url"])
if "fork" in attributes: # pragma no branch
self._fork = self._makeBoolAttribute(attributes["fork"])
if "forks" in attributes: # pragma no branch
self._forks = self._makeIntAttribute(attributes["forks"])
if "forks_count" in attributes: # pragma no branch
self._forks_count = self._makeIntAttribute(attributes["forks_count"])
if "forks_url" in attributes: # pragma no branch
self._forks_url = self._makeStringAttribute(attributes["forks_url"])
if "full_name" in attributes: # pragma no branch
self._full_name = self._makeStringAttribute(attributes["full_name"])
if "git_commits_url" in attributes: # pragma no branch
self._git_commits_url = self._makeStringAttribute(attributes["git_commits_url"])
if "git_refs_url" in attributes: # pragma no branch
self._git_refs_url = self._makeStringAttribute(attributes["git_refs_url"])
if "git_tags_url" in attributes: # pragma no branch
self._git_tags_url = self._makeStringAttribute(attributes["git_tags_url"])
if "git_url" in attributes: # pragma no branch
self._git_url = self._makeStringAttribute(attributes["git_url"])
if "has_downloads" in attributes: # pragma no branch
self._has_downloads = self._makeBoolAttribute(attributes["has_downloads"])
if "has_issues" in attributes: # pragma no branch
self._has_issues = self._makeBoolAttribute(attributes["has_issues"])
if "has_wiki" in attributes: # pragma no branch
self._has_wiki = self._makeBoolAttribute(attributes["has_wiki"])
if "homepage" in attributes: # pragma no branch
self._homepage = self._makeStringAttribute(attributes["homepage"])
if "hooks_url" in attributes: # pragma no branch
self._hooks_url = self._makeStringAttribute(attributes["hooks_url"])
if "html_url" in attributes: # pragma no branch
self._html_url = self._makeStringAttribute(attributes["html_url"])
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "issue_comment_url" in attributes: # pragma no branch
self._issue_comment_url = self._makeStringAttribute(attributes["issue_comment_url"])
if "issue_events_url" in attributes: # pragma no branch
self._issue_events_url = self._makeStringAttribute(attributes["issue_events_url"])
if "issues_url" in attributes: # pragma no branch
self._issues_url = self._makeStringAttribute(attributes["issues_url"])
if "keys_url" in attributes: # pragma no branch
self._keys_url = self._makeStringAttribute(attributes["keys_url"])
if "labels_url" in attributes: # pragma no branch
self._labels_url = self._makeStringAttribute(attributes["labels_url"])
if "language" in attributes: # pragma no branch
self._language = self._makeStringAttribute(attributes["language"])
if "languages_url" in attributes: # pragma no branch
self._languages_url = self._makeStringAttribute(attributes["languages_url"])
if "master_branch" in attributes: # pragma no branch
self._master_branch = self._makeStringAttribute(attributes["master_branch"])
if "merges_url" in attributes: # pragma no branch
self._merges_url = self._makeStringAttribute(attributes["merges_url"])
if "milestones_url" in attributes: # pragma no branch
self._milestones_url = self._makeStringAttribute(attributes["milestones_url"])
if "mirror_url" in attributes: # pragma no branch
self._mirror_url = self._makeStringAttribute(attributes["mirror_url"])
if "name" in attributes: # pragma no branch
self._name = self._makeStringAttribute(attributes["name"])
if "network_count" in attributes: # pragma no branch
self._network_count = self._makeIntAttribute(attributes["network_count"])
if "notifications_url" in attributes: # pragma no branch
self._notifications_url = self._makeStringAttribute(attributes["notifications_url"])
if "open_issues" in attributes: # pragma no branch
self._open_issues = self._makeIntAttribute(attributes["open_issues"])
if "open_issues_count" in attributes: # pragma no branch
self._open_issues_count = self._makeIntAttribute(attributes["open_issues_count"])
if "organization" in attributes: # pragma no branch
self._organization = self._makeClassAttribute(github.Organization.Organization, attributes["organization"])
if "owner" in attributes: # pragma no branch
self._owner = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["owner"])
if "parent" in attributes: # pragma no branch
self._parent = self._makeClassAttribute(Repository, attributes["parent"])
if "permissions" in attributes: # pragma no branch
self._permissions = self._makeClassAttribute(github.Permissions.Permissions, attributes["permissions"])
if "private" in attributes: # pragma no branch
self._private = self._makeBoolAttribute(attributes["private"])
if "pulls_url" in attributes: # pragma no branch
self._pulls_url = self._makeStringAttribute(attributes["pulls_url"])
if "pushed_at" in attributes: # pragma no branch
self._pushed_at = self._makeDatetimeAttribute(attributes["pushed_at"])
if "size" in attributes: # pragma no branch
self._size = self._makeIntAttribute(attributes["size"])
if "source" in attributes: # pragma no branch
self._source = self._makeClassAttribute(Repository, attributes["source"])
if "ssh_url" in attributes: # pragma no branch
self._ssh_url = self._makeStringAttribute(attributes["ssh_url"])
if "stargazers_count" in attributes: # pragma no branch
self._stargazers_count = self._makeIntAttribute(attributes["stargazers_count"])
if "stargazers_url" in attributes: # pragma no branch
self._stargazers_url = self._makeStringAttribute(attributes["stargazers_url"])
if "statuses_url" in attributes: # pragma no branch
self._statuses_url = self._makeStringAttribute(attributes["statuses_url"])
if "subscribers_url" in attributes: # pragma no branch
self._subscribers_url = self._makeStringAttribute(attributes["subscribers_url"])
if "subscribers_count" in attributes: # pragma no branch
self._subscribers_count = self._makeIntAttribute(attributes["subscribers_count"])
if "subscription_url" in attributes: # pragma no branch
self._subscription_url = self._makeStringAttribute(attributes["subscription_url"])
if "svn_url" in attributes: # pragma no branch
self._svn_url = self._makeStringAttribute(attributes["svn_url"])
if "tags_url" in attributes: # pragma no branch
self._tags_url = self._makeStringAttribute(attributes["tags_url"])
if "teams_url" in attributes: # pragma no branch
self._teams_url = self._makeStringAttribute(attributes["teams_url"])
if "trees_url" in attributes: # pragma no branch
self._trees_url = self._makeStringAttribute(attributes["trees_url"])
if "updated_at" in attributes: # pragma no branch
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
if "watchers" in attributes: # pragma no branch
self._watchers = self._makeIntAttribute(attributes["watchers"])
if "watchers_count" in attributes: # pragma no branch
self._watchers_count = self._makeIntAttribute(attributes["watchers_count"])
|
jrick/bitcoin | refs/heads/master | contrib/devtools/fix-copyright-headers.py | 173 | #!/usr/bin/env python
'''
Run this script inside of src/ and it will look for all the files
that were changed this year that still have the last year in the
copyright headers, and it will fix the headers on that file using
a perl regex one liner.
For example: if it finds something like this and we're in 2014
// Copyright (c) 2009-2013 The Bitcoin Core developers
it will change it to
// Copyright (c) 2009-2014 The Bitcoin Core developers
It will do this for all the files in the folder and its children.
Author: @gubatron
'''
import os
import time
year = time.gmtime()[0]
last_year = year - 1
command = "perl -pi -e 's/%s The Bitcoin/%s The Bitcoin/' %s"
listFilesCommand = "find . | grep %s"
extensions = [".cpp",".h"]
def getLastGitModifiedDate(filePath):
gitGetLastCommitDateCommand = "git log " + filePath +" | grep Date | head -n 1"
p = os.popen(gitGetLastCommitDateCommand)
result = ""
for l in p:
result = l
break
result = result.replace("\n","")
return result
n=1
for extension in extensions:
foundFiles = os.popen(listFilesCommand % extension)
for filePath in foundFiles:
filePath = filePath[1:-1]
if filePath.endswith(extension):
filePath = os.getcwd() + filePath
modifiedTime = getLastGitModifiedDate(filePath)
if len(modifiedTime) > 0 and str(year) in modifiedTime:
print n,"Last Git Modified: ", modifiedTime, " - ", filePath
os.popen(command % (last_year,year,filePath))
n = n + 1
|
fearthecowboy/pygments | refs/heads/master | Pygments/pygments-lib/pygments/styles/pastie.py | 50 | # -*- coding: utf-8 -*-
"""
pygments.styles.pastie
~~~~~~~~~~~~~~~~~~~~~~
Style similar to the `pastie`_ default style.
.. _pastie: http://pastie.caboo.se/
:copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Generic, Whitespace
class PastieStyle(Style):
"""
Style similar to the pastie default style.
"""
default_style = ''
styles = {
Whitespace: '#bbbbbb',
Comment: '#888888',
Comment.Preproc: 'bold #cc0000',
Comment.Special: 'bg:#fff0f0 bold #cc0000',
String: 'bg:#fff0f0 #dd2200',
String.Regex: 'bg:#fff0ff #008800',
String.Other: 'bg:#f0fff0 #22bb22',
String.Symbol: '#aa6600',
String.Interpol: '#3333bb',
String.Escape: '#0044dd',
Operator.Word: '#008800',
Keyword: 'bold #008800',
Keyword.Pseudo: 'nobold',
Keyword.Type: '#888888',
Name.Class: 'bold #bb0066',
Name.Exception: 'bold #bb0066',
Name.Function: 'bold #0066bb',
Name.Property: 'bold #336699',
Name.Namespace: 'bold #bb0066',
Name.Builtin: '#003388',
Name.Variable: '#336699',
Name.Variable.Class: '#336699',
Name.Variable.Instance: '#3333bb',
Name.Variable.Global: '#dd7700',
Name.Constant: 'bold #003366',
Name.Tag: 'bold #bb0066',
Name.Attribute: '#336699',
Name.Decorator: '#555555',
Name.Label: 'italic #336699',
Number: 'bold #0000DD',
Generic.Heading: '#333',
Generic.Subheading: '#666',
Generic.Deleted: 'bg:#ffdddd #000000',
Generic.Inserted: 'bg:#ddffdd #000000',
Generic.Error: '#aa0000',
Generic.Emph: 'italic',
Generic.Strong: 'bold',
Generic.Prompt: '#555555',
Generic.Output: '#888888',
Generic.Traceback: '#aa0000',
Error: 'bg:#e3d2d2 #a61717'
}
|
EmmanuelU/wild_kernel_htc_msm8660 | refs/heads/android-msm-doubleshot-3.0-ion | tools/perf/scripts/python/Perf-Trace-Util/lib/Perf/Trace/Util.py | 12527 | # Util.py - Python extension for perf script, miscellaneous utility code
#
# Copyright (C) 2010 by Tom Zanussi <tzanussi@gmail.com>
#
# This software may be distributed under the terms of the GNU General
# Public License ("GPL") version 2 as published by the Free Software
# Foundation.
import errno, os
FUTEX_WAIT = 0
FUTEX_WAKE = 1
FUTEX_PRIVATE_FLAG = 128
FUTEX_CLOCK_REALTIME = 256
FUTEX_CMD_MASK = ~(FUTEX_PRIVATE_FLAG | FUTEX_CLOCK_REALTIME)
NSECS_PER_SEC = 1000000000
def avg(total, n):
return total / n
def nsecs(secs, nsecs):
return secs * NSECS_PER_SEC + nsecs
def nsecs_secs(nsecs):
return nsecs / NSECS_PER_SEC
def nsecs_nsecs(nsecs):
return nsecs % NSECS_PER_SEC
def nsecs_str(nsecs):
str = "%5u.%09u" % (nsecs_secs(nsecs), nsecs_nsecs(nsecs)),
return str
def add_stats(dict, key, value):
if not dict.has_key(key):
dict[key] = (value, value, value, 1)
else:
min, max, avg, count = dict[key]
if value < min:
min = value
if value > max:
max = value
avg = (avg + value) / 2
dict[key] = (min, max, avg, count + 1)
def clear_term():
print("\x1b[H\x1b[2J")
audit_package_warned = False
try:
import audit
machine_to_id = {
'x86_64': audit.MACH_86_64,
'alpha' : audit.MACH_ALPHA,
'ia64' : audit.MACH_IA64,
'ppc' : audit.MACH_PPC,
'ppc64' : audit.MACH_PPC64,
's390' : audit.MACH_S390,
's390x' : audit.MACH_S390X,
'i386' : audit.MACH_X86,
'i586' : audit.MACH_X86,
'i686' : audit.MACH_X86,
}
try:
machine_to_id['armeb'] = audit.MACH_ARMEB
except:
pass
machine_id = machine_to_id[os.uname()[4]]
except:
if not audit_package_warned:
audit_package_warned = True
print "Install the audit-libs-python package to get syscall names"
def syscall_name(id):
try:
return audit.audit_syscall_to_name(id, machine_id)
except:
return str(id)
def strerror(nr):
try:
return errno.errorcode[abs(nr)]
except:
return "Unknown %d errno" % nr
|
Beyond-Imagination/BlubBlub | refs/heads/master | ChatbotServer/ChatbotEnv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/pep425tags.py | 340 | """Generate and work with PEP 425 Compatibility Tags."""
from __future__ import absolute_import
import re
import sys
import warnings
import platform
import logging
try:
import sysconfig
except ImportError: # pragma nocover
# Python < 2.7
import distutils.sysconfig as sysconfig
import distutils.util
from pip.compat import OrderedDict
import pip.utils.glibc
logger = logging.getLogger(__name__)
_osx_arch_pat = re.compile(r'(.+)_(\d+)_(\d+)_(.+)')
def get_config_var(var):
try:
return sysconfig.get_config_var(var)
except IOError as e: # Issue #1074
warnings.warn("{0}".format(e), RuntimeWarning)
return None
def get_abbr_impl():
"""Return abbreviated implementation name."""
if hasattr(sys, 'pypy_version_info'):
pyimpl = 'pp'
elif sys.platform.startswith('java'):
pyimpl = 'jy'
elif sys.platform == 'cli':
pyimpl = 'ip'
else:
pyimpl = 'cp'
return pyimpl
def get_impl_ver():
"""Return implementation version."""
impl_ver = get_config_var("py_version_nodot")
if not impl_ver or get_abbr_impl() == 'pp':
impl_ver = ''.join(map(str, get_impl_version_info()))
return impl_ver
def get_impl_version_info():
"""Return sys.version_info-like tuple for use in decrementing the minor
version."""
if get_abbr_impl() == 'pp':
# as per https://github.com/pypa/pip/issues/2882
return (sys.version_info[0], sys.pypy_version_info.major,
sys.pypy_version_info.minor)
else:
return sys.version_info[0], sys.version_info[1]
def get_impl_tag():
"""
Returns the Tag for this specific implementation.
"""
return "{0}{1}".format(get_abbr_impl(), get_impl_ver())
def get_flag(var, fallback, expected=True, warn=True):
"""Use a fallback method for determining SOABI flags if the needed config
var is unset or unavailable."""
val = get_config_var(var)
if val is None:
if warn:
logger.debug("Config variable '%s' is unset, Python ABI tag may "
"be incorrect", var)
return fallback()
return val == expected
def get_abi_tag():
"""Return the ABI tag based on SOABI (if available) or emulate SOABI
(CPython 2, PyPy)."""
soabi = get_config_var('SOABI')
impl = get_abbr_impl()
if not soabi and impl in ('cp', 'pp') and hasattr(sys, 'maxunicode'):
d = ''
m = ''
u = ''
if get_flag('Py_DEBUG',
lambda: hasattr(sys, 'gettotalrefcount'),
warn=(impl == 'cp')):
d = 'd'
if get_flag('WITH_PYMALLOC',
lambda: impl == 'cp',
warn=(impl == 'cp')):
m = 'm'
if get_flag('Py_UNICODE_SIZE',
lambda: sys.maxunicode == 0x10ffff,
expected=4,
warn=(impl == 'cp' and
sys.version_info < (3, 3))) \
and sys.version_info < (3, 3):
u = 'u'
abi = '%s%s%s%s%s' % (impl, get_impl_ver(), d, m, u)
elif soabi and soabi.startswith('cpython-'):
abi = 'cp' + soabi.split('-')[1]
elif soabi:
abi = soabi.replace('.', '_').replace('-', '_')
else:
abi = None
return abi
def _is_running_32bit():
return sys.maxsize == 2147483647
def get_platform():
"""Return our platform name 'win32', 'linux_x86_64'"""
if sys.platform == 'darwin':
# distutils.util.get_platform() returns the release based on the value
# of MACOSX_DEPLOYMENT_TARGET on which Python was built, which may
# be significantly older than the user's current machine.
release, _, machine = platform.mac_ver()
split_ver = release.split('.')
if machine == "x86_64" and _is_running_32bit():
machine = "i386"
elif machine == "ppc64" and _is_running_32bit():
machine = "ppc"
return 'macosx_{0}_{1}_{2}'.format(split_ver[0], split_ver[1], machine)
# XXX remove distutils dependency
result = distutils.util.get_platform().replace('.', '_').replace('-', '_')
if result == "linux_x86_64" and _is_running_32bit():
# 32 bit Python program (running on a 64 bit Linux): pip should only
# install and run 32 bit compiled extensions in that case.
result = "linux_i686"
return result
def is_manylinux1_compatible():
# Only Linux, and only x86-64 / i686
if get_platform() not in ("linux_x86_64", "linux_i686"):
return False
# Check for presence of _manylinux module
try:
import _manylinux
return bool(_manylinux.manylinux1_compatible)
except (ImportError, AttributeError):
# Fall through to heuristic check below
pass
# Check glibc version. CentOS 5 uses glibc 2.5.
return pip.utils.glibc.have_compatible_glibc(2, 5)
def get_darwin_arches(major, minor, machine):
"""Return a list of supported arches (including group arches) for
the given major, minor and machine architecture of an macOS machine.
"""
arches = []
def _supports_arch(major, minor, arch):
# Looking at the application support for macOS versions in the chart
# provided by https://en.wikipedia.org/wiki/OS_X#Versions it appears
# our timeline looks roughly like:
#
# 10.0 - Introduces ppc support.
# 10.4 - Introduces ppc64, i386, and x86_64 support, however the ppc64
# and x86_64 support is CLI only, and cannot be used for GUI
# applications.
# 10.5 - Extends ppc64 and x86_64 support to cover GUI applications.
# 10.6 - Drops support for ppc64
# 10.7 - Drops support for ppc
#
# Given that we do not know if we're installing a CLI or a GUI
# application, we must be conservative and assume it might be a GUI
# application and behave as if ppc64 and x86_64 support did not occur
# until 10.5.
#
# Note: The above information is taken from the "Application support"
# column in the chart not the "Processor support" since I believe
# that we care about what instruction sets an application can use
# not which processors the OS supports.
if arch == 'ppc':
return (major, minor) <= (10, 5)
if arch == 'ppc64':
return (major, minor) == (10, 5)
if arch == 'i386':
return (major, minor) >= (10, 4)
if arch == 'x86_64':
return (major, minor) >= (10, 5)
if arch in groups:
for garch in groups[arch]:
if _supports_arch(major, minor, garch):
return True
return False
groups = OrderedDict([
("fat", ("i386", "ppc")),
("intel", ("x86_64", "i386")),
("fat64", ("x86_64", "ppc64")),
("fat32", ("x86_64", "i386", "ppc")),
])
if _supports_arch(major, minor, machine):
arches.append(machine)
for garch in groups:
if machine in groups[garch] and _supports_arch(major, minor, garch):
arches.append(garch)
arches.append('universal')
return arches
def get_supported(versions=None, noarch=False, platform=None,
impl=None, abi=None):
"""Return a list of supported tags for each version specified in
`versions`.
:param versions: a list of string versions, of the form ["33", "32"],
or None. The first version will be assumed to support our ABI.
:param platform: specify the exact platform you want valid
tags for, or None. If None, use the local system platform.
:param impl: specify the exact implementation you want valid
tags for, or None. If None, use the local interpreter impl.
:param abi: specify the exact abi you want valid
tags for, or None. If None, use the local interpreter abi.
"""
supported = []
# Versions must be given with respect to the preference
if versions is None:
versions = []
version_info = get_impl_version_info()
major = version_info[:-1]
# Support all previous minor Python versions.
for minor in range(version_info[-1], -1, -1):
versions.append(''.join(map(str, major + (minor,))))
impl = impl or get_abbr_impl()
abis = []
abi = abi or get_abi_tag()
if abi:
abis[0:0] = [abi]
abi3s = set()
import imp
for suffix in imp.get_suffixes():
if suffix[0].startswith('.abi'):
abi3s.add(suffix[0].split('.', 2)[1])
abis.extend(sorted(list(abi3s)))
abis.append('none')
if not noarch:
arch = platform or get_platform()
if arch.startswith('macosx'):
# support macosx-10.6-intel on macosx-10.9-x86_64
match = _osx_arch_pat.match(arch)
if match:
name, major, minor, actual_arch = match.groups()
tpl = '{0}_{1}_%i_%s'.format(name, major)
arches = []
for m in reversed(range(int(minor) + 1)):
for a in get_darwin_arches(int(major), m, actual_arch):
arches.append(tpl % (m, a))
else:
# arch pattern didn't match (?!)
arches = [arch]
elif platform is None and is_manylinux1_compatible():
arches = [arch.replace('linux', 'manylinux1'), arch]
else:
arches = [arch]
# Current version, current API (built specifically for our Python):
for abi in abis:
for arch in arches:
supported.append(('%s%s' % (impl, versions[0]), abi, arch))
# abi3 modules compatible with older version of Python
for version in versions[1:]:
# abi3 was introduced in Python 3.2
if version in ('31', '30'):
break
for abi in abi3s: # empty set if not Python 3
for arch in arches:
supported.append(("%s%s" % (impl, version), abi, arch))
# Has binaries, does not use the Python API:
for arch in arches:
supported.append(('py%s' % (versions[0][0]), 'none', arch))
# No abi / arch, but requires our implementation:
supported.append(('%s%s' % (impl, versions[0]), 'none', 'any'))
# Tagged specifically as being cross-version compatible
# (with just the major version specified)
supported.append(('%s%s' % (impl, versions[0][0]), 'none', 'any'))
# No abi / arch, generic Python
for i, version in enumerate(versions):
supported.append(('py%s' % (version,), 'none', 'any'))
if i == 0:
supported.append(('py%s' % (version[0]), 'none', 'any'))
return supported
supported_tags = get_supported()
supported_tags_noarch = get_supported(noarch=True)
implementation_tag = get_impl_tag()
|
arnulfojr/money-manager | refs/heads/master | src/api/accounts/controllers/accounts.py | 1 |
from .. import blueprint
from flask import request, make_response, jsonify
from cerberus import Validator
from lib.db import session
from lib.request import is_json
from core.accounts import Account
@blueprint.route('/', methods=['GET'])
def get_accounts():
"""Returns all the accounts registered"""
accounts = Account.query()
payload = [account.to_dict() for account in accounts]
response = make_response(jsonify(payload), 200)
return response
@blueprint.route('/', methods=['POST'])
@is_json
def save_account():
payload = request.get_json()
validator = Validator(Account.schema)
if not validator.validate(payload):
response = make_response(jsonify(validator.errors), 400)
return response
document = validator.document
account = Account.from_dict(document)
session.add(account)
session.commit()
session.flush()
response = make_response(jsonify(account.to_dict()), 201)
session.close()
return response
@blueprint.route('/<code>/', methods=['GET'])
def get_account(code):
account = Account.get(code)
if account is None:
response = make_response(jsonify({'message': 'No Account was found'}), 404)
return response
payload = account.to_dict()
response = make_response(jsonify(payload), 200)
return response
@blueprint.route('/<code>/', methods=['PUT'])
@is_json
def update_account(code):
account = Account.get(code)
if account is None:
response = make_response(jsonify({'message': 'No Account was found'}), 404)
return response
validator = Validator(Account.schema)
payload = request.get_json()
if not validator.validate(payload):
response = make_response(jsonify(validator.errors), 400)
return response
account = Account.from_dict(validator.document, account)
session.add(account)
session.commit()
session.flush()
payload = account.to_dict()
session.close()
response = make_response(jsonify(payload), 200)
return response
@blueprint.route('/<code>/', methods=['DELETE'])
def delete_account(code):
account = Account.get(code)
if account is None:
response = make_response(jsonify({'message': 'No account was found'}), 404)
return response
session.delete(account)
session.commit()
session.flush()
session.close()
response = make_response(jsonify({'message': 'Account {} was deleted'.format(code)}), 200)
return response
|
lamenezes/simple-model | refs/heads/master | simple_model/builder.py | 1 | from typing import Any, Generator
from .models import Model
from .utils import camel_case, coerce_to_alpha, snake_case, remove_private_keys
def model_class_builder(class_name: str, data: Any) -> type:
keys = data.keys() or ('',)
attrs = {key: None for key in keys}
attrs['__annotations__'] = {key: Any for key in keys} # type: ignore
new_class = type(class_name, (Model,), remove_private_keys(attrs))
return new_class
def model_builder(
data: Any, class_name: str = 'MyModel', cls: type = None, recurse: bool = True,
snake_case_keys: bool = True, alpha_keys: bool = True,
) -> Model:
clean_funcs = []
if snake_case_keys:
clean_funcs.append(snake_case)
if alpha_keys:
clean_funcs.append(coerce_to_alpha)
data = {func(key): value for key, value in data.items() for func in clean_funcs}
if not cls:
cls = model_class_builder(class_name, data)
instance = cls(**remove_private_keys(data))
if not recurse:
return instance
for name, descriptor in instance._get_fields():
value = getattr(instance, name)
if isinstance(value, dict):
value = model_builder(value, camel_case(name))
elif isinstance(value, (list, tuple)):
value = list(value)
for i, elem in enumerate(value):
if not isinstance(elem, dict):
continue
value[i] = model_builder(elem, 'NamelessModel')
field_class = value.__class__
value = field_class(value)
setattr(instance, name, value)
return instance
def model_many_builder(
data: list, class_name: str = 'MyModel', cls: type = None, recurse: bool = True,
snake_case_keys: bool = True, alpha_keys: bool = True,
) -> Generator[Model, None, None]:
if len(data) == 0:
return
first = data[0]
cls = cls or model_class_builder(class_name, first)
for element in data:
model = model_builder(
data=element,
class_name=class_name,
cls=cls,
recurse=recurse,
snake_case_keys=snake_case_keys,
alpha_keys=alpha_keys,
)
yield model
|
zjh3123629/linux-3.0.101 | refs/heads/master | tools/perf/scripts/python/Perf-Trace-Util/lib/Perf/Trace/Util.py | 12527 | # Util.py - Python extension for perf script, miscellaneous utility code
#
# Copyright (C) 2010 by Tom Zanussi <tzanussi@gmail.com>
#
# This software may be distributed under the terms of the GNU General
# Public License ("GPL") version 2 as published by the Free Software
# Foundation.
import errno, os
FUTEX_WAIT = 0
FUTEX_WAKE = 1
FUTEX_PRIVATE_FLAG = 128
FUTEX_CLOCK_REALTIME = 256
FUTEX_CMD_MASK = ~(FUTEX_PRIVATE_FLAG | FUTEX_CLOCK_REALTIME)
NSECS_PER_SEC = 1000000000
def avg(total, n):
return total / n
def nsecs(secs, nsecs):
return secs * NSECS_PER_SEC + nsecs
def nsecs_secs(nsecs):
return nsecs / NSECS_PER_SEC
def nsecs_nsecs(nsecs):
return nsecs % NSECS_PER_SEC
def nsecs_str(nsecs):
str = "%5u.%09u" % (nsecs_secs(nsecs), nsecs_nsecs(nsecs)),
return str
def add_stats(dict, key, value):
if not dict.has_key(key):
dict[key] = (value, value, value, 1)
else:
min, max, avg, count = dict[key]
if value < min:
min = value
if value > max:
max = value
avg = (avg + value) / 2
dict[key] = (min, max, avg, count + 1)
def clear_term():
print("\x1b[H\x1b[2J")
audit_package_warned = False
try:
import audit
machine_to_id = {
'x86_64': audit.MACH_86_64,
'alpha' : audit.MACH_ALPHA,
'ia64' : audit.MACH_IA64,
'ppc' : audit.MACH_PPC,
'ppc64' : audit.MACH_PPC64,
's390' : audit.MACH_S390,
's390x' : audit.MACH_S390X,
'i386' : audit.MACH_X86,
'i586' : audit.MACH_X86,
'i686' : audit.MACH_X86,
}
try:
machine_to_id['armeb'] = audit.MACH_ARMEB
except:
pass
machine_id = machine_to_id[os.uname()[4]]
except:
if not audit_package_warned:
audit_package_warned = True
print "Install the audit-libs-python package to get syscall names"
def syscall_name(id):
try:
return audit.audit_syscall_to_name(id, machine_id)
except:
return str(id)
def strerror(nr):
try:
return errno.errorcode[abs(nr)]
except:
return "Unknown %d errno" % nr
|
ahmadia/bokeh | refs/heads/master | bokeh/models/plots.py | 19 | """ Models for representing top-level plot objects.
"""
from __future__ import absolute_import
from six import string_types
from ..enums import Location
from ..mixins import LineProps, TextProps
from ..plot_object import PlotObject
from ..properties import Bool, Int, String, Color, Enum, Auto, Instance, Either, List, Dict, Include
from ..query import find
from ..util.string import nice_join
from ..validation.warnings import MISSING_RENDERERS, NO_GLYPH_RENDERERS, EMPTY_LAYOUT
from ..validation.errors import REQUIRED_RANGE
from .. import validation
from .glyphs import Glyph
from .ranges import Range, Range1d
from .renderers import Renderer, GlyphRenderer
from .sources import DataSource, ColumnDataSource
from .tools import Tool, ToolEvents
from .widget import Widget
def _select_helper(args, kwargs):
"""
Allow fexible selector syntax.
Returns:
a dict
"""
if len(args) > 1:
raise TypeError("select accepts at most ONE positional argument.")
if len(args) > 0 and len(kwargs) > 0:
raise TypeError("select accepts EITHER a positional argument, OR keyword arguments (not both).")
if len(args) == 0 and len(kwargs) == 0:
raise TypeError("select requires EITHER a positional argument, OR keyword arguments.")
if args:
arg = args[0]
if isinstance(arg, dict):
selector = arg
elif isinstance(arg, string_types):
selector = dict(name=arg)
elif issubclass(arg, PlotObject):
selector = {"type" : arg}
else:
raise RuntimeError("Selector must be a dictionary, string or plot object.")
else:
selector = kwargs
return selector
class PlotContext(PlotObject):
""" A container for multiple plot objects.
``PlotContext`` objects are a source of confusion. Their purpose
is to collect together different top-level objects (e.g., ``Plot``
or layout widgets). The reason for this is that different plots may
need to share ranges or data sources between them. A ``PlotContext``
is a container in which such sharing can occur between the contained
objects.
"""
children = List(Instance(PlotObject), help="""
A list of top level objects in this ``PlotContext`` container.
""")
# TODO (bev) : is this used anywhere?
class PlotList(PlotContext):
# just like plot context, except plot context has special meaning
# everywhere, so plotlist is the generic one
pass
class Plot(Widget):
""" Model representing a plot, containing glyphs, guides, annotations.
"""
def __init__(self, **kwargs):
if "tool_events" not in kwargs:
kwargs["tool_events"] = ToolEvents()
super(Plot, self).__init__(**kwargs)
def select(self, *args, **kwargs):
''' Query this object and all of its references for objects that
match the given selector.
There are a few different ways to call the ``select`` method.
The most general is to supply a JSON-like query dictionary as the
single argument or as keyword arguments:
Args:
selector (JSON-like) : some sample text
Keyword Arguments:
kwargs : query dict key/values as keyword arguments
For convenience, queries on just names can be made by supplying
the ``name`` string as the single parameter:
Args:
name (str) : the name to query on
Also queries on just type can be made simply by supplying the
``PlotObject`` subclass as the single parameter:
Args:
type (PlotObject) : the type to query on
Returns:
seq[PlotObject]
Examples:
.. code-block:: python
# These two are equivalent
p.select({"type": HoverTool})
p.select(HoverTool)
# These two are also equivalent
p.select({"name": "mycircle"})
p.select("mycircle")
# Keyword arguments can be supplied in place of selector dict
p.select({"name": "foo", "type": HoverTool})
p.select(name="foo", type=HoverTool)
'''
selector = _select_helper(args, kwargs)
# Want to pass selector that is a dictionary
from ..plotting_helpers import _list_attr_splat
return _list_attr_splat(find(self.references(), selector, {'plot': self}))
def row(self, row, gridplot):
''' Return whether this plot is in a given row of a GridPlot.
Args:
row (int) : index of the row to test
gridplot (GridPlot) : the GridPlot to check
Returns:
bool
'''
return self in gridplot.row(row)
def column(self, col, gridplot):
''' Return whether this plot is in a given column of a GridPlot.
Args:
col (int) : index of the column to test
gridplot (GridPlot) : the GridPlot to check
Returns:
bool
'''
return self in gridplot.column(col)
def add_layout(self, obj, place='center'):
''' Adds an object to the plot in a specified place.
Args:
obj (Renderer) : the object to add to the Plot
place (str, optional) : where to add the object (default: 'center')
Valid places are: 'left', 'right', 'above', 'below', 'center'.
Returns:
None
'''
valid_places = ['left', 'right', 'above', 'below', 'center']
if place not in valid_places:
raise ValueError(
"Invalid place '%s' specified. Valid place values are: %s" % (place, nice_join(valid_places))
)
if hasattr(obj, 'plot'):
if obj.plot is not None:
raise ValueError("object to be added already has 'plot' attribute set")
obj.plot = self
self.renderers.append(obj)
if place is not 'center':
getattr(self, place).append(obj)
def add_tools(self, *tools):
''' Adds an tools to the plot.
Args:
*tools (Tool) : the tools to add to the Plot
Returns:
None
'''
if not all(isinstance(tool, Tool) for tool in tools):
raise ValueError("All arguments to add_tool must be Tool subclasses.")
for tool in tools:
if tool.plot is not None:
raise ValueError("tool %s to be added already has 'plot' attribute set" % tool)
tool.plot = self
self.tools.append(tool)
def add_glyph(self, source_or_glyph, glyph=None, **kw):
''' Adds a glyph to the plot with associated data sources and ranges.
This function will take care of creating and configurinf a Glyph object,
and then add it to the plot's list of renderers.
Args:
source (DataSource) : a data source for the glyphs to all use
glyph (Glyph) : the glyph to add to the Plot
Keyword Arguments:
Any additional keyword arguments are passed on as-is to the
Glyph initializer.
Returns:
glyph : Glyph
'''
if glyph is not None:
source = source_or_glyph
else:
source, glyph = ColumnDataSource(), source_or_glyph
if not isinstance(source, DataSource):
raise ValueError("'source' argument to add_glyph() must be DataSource subclass")
if not isinstance(glyph, Glyph):
raise ValueError("'glyph' argument to add_glyph() must be Glyph subclass")
g = GlyphRenderer(data_source=source, glyph=glyph, **kw)
self.renderers.append(g)
return g
@validation.error(REQUIRED_RANGE)
def _check_required_range(self):
missing = []
if not self.x_range: missing.append('x_range')
if not self.y_range: missing.append('y_range')
if missing:
return ", ".join(missing) + " [%s]" % self
@validation.warning(MISSING_RENDERERS)
def _check_missing_renderers(self):
if len(self.renderers) == 0:
return str(self)
@validation.warning(NO_GLYPH_RENDERERS)
def _check_no_glyph_renderers(self):
if len(self.select(GlyphRenderer)) == 0:
return str(self)
x_range = Instance(Range, help="""
The (default) data range of the horizontal dimension of the plot.
""")
y_range = Instance(Range, help="""
The (default) data range of the vertical dimension of the plot.
""")
x_mapper_type = Either(Auto, String, help="""
What kind of mapper to use to convert x-coordinates in data space
into x-coordinates in screen space.
Typically this can be determined automatically, but this property
can be useful to, e.g., show datetime values as floating point
"seconds since epoch" instead of formatted dates.
""")
y_mapper_type = Either(Auto, String, help="""
What kind of mapper to use to convert y-coordinates in data space
into y-coordinates in screen space.
Typically this can be determined automatically, but this property
can be useful to, e.g., show datetime values as floating point
"seconds since epoch" instead of formatted dates
""")
extra_x_ranges = Dict(String, Instance(Range1d), help="""
Additional named ranges to make available for mapping x-coordinates.
This is useful for adding additional axes.
""")
extra_y_ranges = Dict(String, Instance(Range), help="""
Additional named ranges to make available for mapping y-coordinates.
This is useful for adding additional axes.
""")
title = String('', help="""
A title for the plot.
""")
title_props = Include(TextProps, help="""
The %s for the plot title.
""")
outline_props = Include(LineProps, help="""
The %s for the plot border outline.
""")
renderers = List(Instance(Renderer), help="""
A list of all renderers for this plot, including guides and annotations
in addition to glyphs and markers.
This property can be manipulated by hand, but the ``add_glyph`` and
``add_layout`` methods are recommended to help make sure all necessary
setup is performed.
""")
tools = List(Instance(Tool), help="""
A list of tools to add to the plot.
""")
tool_events = Instance(ToolEvents, help="""
A ToolEvents object to share and report tool events.
""")
left = List(Instance(Renderer), help="""
A list of renderers to occupy the area to the left of the plot.
""")
right = List(Instance(Renderer), help="""
A list of renderers to occupy the area to the right of the plot.
""")
above = List(Instance(Renderer), help="""
A list of renderers to occupy the area above of the plot.
""")
below = List(Instance(Renderer), help="""
A list of renderers to occupy the area below of the plot.
""")
toolbar_location = Enum(Location, help="""
Where the toolbar will be located. If set to None, no toolbar
will be attached to the plot.
""")
logo = Enum("normal", "grey", help="""
What version of the Bokeh logo to display on the toolbar. If
set to None, no logo will be displayed.
""")
plot_height = Int(600, help="""
Total height of the entire plot (including any axes, titles,
border padding, etc.)
.. note::
This corresponds directly to the height of the HTML
canvas that will be used.
""")
plot_width = Int(600, help="""
Total width of the entire plot (including any axes, titles,
border padding, etc.)
.. note::
This corresponds directly to the width of the HTML
canvas that will be used.
""")
background_fill = Color("white", help="""
""")
border_fill = Color("white", help="""
""")
min_border_top = Int(50, help="""
Minimum size in pixels of the padding region above the top of the
central plot region.
.. note::
This is a *minimum*. The padding region may expand as needed to
accommodate titles or axes, etc.
""")
min_border_bottom = Int(50, help="""
Minimum size in pixels of the padding region below the bottom of
the central plot region.
.. note::
This is a *minimum*. The padding region may expand as needed to
accommodate titles or axes, etc.
""")
min_border_left = Int(50, help="""
Minimum size in pixels of the padding region to the left of
the central plot region.
.. note::
This is a *minimum*. The padding region may expand as needed to
accommodate titles or axes, etc.
""")
min_border_right = Int(50, help="""
Minimum size in pixels of the padding region to the right of
the central plot region.
.. note::
This is a *minimum*. The padding region may expand as needed to
accommodate titles or axes, etc.
""")
min_border = Int(50, help="""
A convenience property to set all all the ``min_X_border`` properties
to the same value. If an individual border property is explicitly set,
it will override ``min_border``.
""")
h_symmetry = Bool(True, help="""
Whether the total horizontal padding on both sides of the plot will
be made equal (the left or right padding amount, whichever is larger).
""")
v_symmetry = Bool(False, help="""
Whether the total vertical padding on both sides of the plot will
be made equal (the top or bottom padding amount, whichever is larger).
""")
lod_factor = Int(10, help="""
Decimation factor to use when applying level-of-detail decimation.
""")
lod_threshold = Int(2000, help="""
A number of data points, above which level-of-detail downsampling may
be performed by glyph renderers. Set to ``None`` to disable any
level-of-detail downsampling.
""")
lod_interval = Int(300, help="""
Interval (in ms) during which an interactive tool event will enable
level-of-detail downsampling.
""")
lod_timeout = Int(500, help="""
Timeout (in ms) for checking whether interactive tool events are still
occurring. Once level-of-detail mode is enabled, a check is made every
``lod_timeout`` ms. If no interactive tool events have happened,
level-of-detail mode is disabled.
""")
class GridPlot(Plot):
""" A 2D grid of plots rendered on separate canvases in an HTML table.
"""
# TODO (bev) really, GridPlot should be a layout, not a Plot subclass
@validation.error(REQUIRED_RANGE)
def _check_required_range(self):
pass
@validation.warning(MISSING_RENDERERS)
def _check_missing_renderers(self):
pass
@validation.warning(NO_GLYPH_RENDERERS)
def _check_no_glyph_renderers(self):
pass
@validation.warning(EMPTY_LAYOUT)
def _check_empty_layout(self):
from itertools import chain
if not list(chain(self.children)):
return str(self)
children = List(List(Instance(Plot)), help="""
An array of plots to display in a grid, given as a list of lists of
Plot objects. To leave a position in the grid empty, pass None for
that position in the ``children`` list.
""")
border_space = Int(0, help="""
Distance (in pixels) between adjacent plots.
""")
def select(self, *args, **kwargs):
''' Query this object and all of its references for objects that
match the given selector. See Plot.select for detailed usage infomation.
Returns:
seq[PlotObject]
'''
selector = _select_helper(args, kwargs)
# Want to pass selector that is a dictionary
from ..plotting_helpers import _list_attr_splat
return _list_attr_splat(find(self.references(), selector, {'gridplot': self}))
def column(self, col):
''' Return a given column of plots from this GridPlot.
Args:
col (int) : index of the column to return
Returns:
seq[Plot] : column of plots
'''
try:
return [row[col] for row in self.children]
except:
return []
def row(self, row):
''' Return a given row of plots from this GridPlot.
Args:
rwo (int) : index of the row to return
Returns:
seq[Plot] : row of plots
'''
try:
return self.children[row]
except:
return []
|
payeldillip/django | refs/heads/master | tests/template_tests/filter_tests/test_time.py | 326 | from datetime import time
from django.template.defaultfilters import time as time_filter
from django.test import SimpleTestCase
from django.utils import timezone
from ..utils import setup
from .timezone_utils import TimezoneTestCase
class TimeTests(TimezoneTestCase):
"""
#20693: Timezone support for the time template filter
"""
@setup({'time01': '{{ dt|time:"e:O:T:Z" }}'})
def test_time01(self):
output = self.engine.render_to_string('time01', {'dt': self.now_tz_i})
self.assertEqual(output, '+0315:+0315:+0315:11700')
@setup({'time02': '{{ dt|time:"e:T" }}'})
def test_time02(self):
output = self.engine.render_to_string('time02', {'dt': self.now})
self.assertEqual(output, ':' + self.now_tz.tzinfo.tzname(self.now_tz))
@setup({'time03': '{{ t|time:"P:e:O:T:Z" }}'})
def test_time03(self):
output = self.engine.render_to_string('time03', {'t': time(4, 0, tzinfo=timezone.get_fixed_timezone(30))})
self.assertEqual(output, '4 a.m.::::')
@setup({'time04': '{{ t|time:"P:e:O:T:Z" }}'})
def test_time04(self):
output = self.engine.render_to_string('time04', {'t': time(4, 0)})
self.assertEqual(output, '4 a.m.::::')
@setup({'time05': '{{ d|time:"P:e:O:T:Z" }}'})
def test_time05(self):
output = self.engine.render_to_string('time05', {'d': self.today})
self.assertEqual(output, '')
@setup({'time06': '{{ obj|time:"P:e:O:T:Z" }}'})
def test_time06(self):
output = self.engine.render_to_string('time06', {'obj': 'non-datetime-value'})
self.assertEqual(output, '')
class FunctionTests(SimpleTestCase):
def test_inputs(self):
self.assertEqual(time_filter(time(13), 'h'), '01')
self.assertEqual(time_filter(time(0), 'h'), '12')
|
odoousers2014/odoo | refs/heads/master | addons/website_sale_digital/controllers/main.py | 7 | # -*- coding: utf-8 -*-
import base64
from openerp.addons.web import http
from openerp.addons.web.http import request
from openerp.addons.website.controllers.main import Website
from openerp.addons.website_sale.controllers.main import website_sale
from cStringIO import StringIO
from werkzeug.utils import redirect
class website_sale_digital(website_sale):
orders_page = '/shop/orders'
@http.route([
'/shop/confirmation',
], type='http', auth="public", website=True)
def payment_confirmation(self, **post):
response = super(website_sale_digital, self).payment_confirmation(**post)
order_lines = response.qcontext['order'].order_line
digital_content = map(lambda x: x.product_id.digital_content, order_lines)
response.qcontext.update(digital=any(digital_content))
return response
@http.route([
'/shop/orders',
'/shop/orders/page/<int:page>',
], type='http', auth='user', website=True)
def orders_followup(self, page=1, **post):
response = super(website_sale_digital, self).orders_followup(**post)
order_products_attachments = {}
for o in response.qcontext['orders']:
invoiced_lines = request.env['account.invoice.line'].sudo().search([('invoice_id', 'in', o.invoice_ids.ids), ('invoice_id.state', '=', 'paid')])
purchased_products_attachments = {}
for il in invoiced_lines:
p_obj = il.product_id
# Ignore products that do not have digital content
if not p_obj.product_tmpl_id.digital_content:
continue
# Search for product attachments
A = request.env['ir.attachment']
p_id = p_obj.id
template = p_obj.product_tmpl_id
att = A.search_read(
domain=['|', '&', ('res_model', '=', p_obj._name), ('res_id', '=', p_id), '&', ('res_model', '=', template._name), ('res_id', '=', template.id)],
fields=['name', 'write_date'],
order='write_date desc',
)
# Ignore products with no attachments
if not att:
continue
purchased_products_attachments[p_id] = att
order_products_attachments[o.id] = purchased_products_attachments
response.qcontext.update({
'digital_attachments': order_products_attachments,
})
return response
@http.route([
'/shop/download',
], type='http', auth='public')
def download_attachment(self, attachment_id):
# Check if this is a valid attachment id
attachment = request.env['ir.attachment'].sudo().search_read(
[('id', '=', int(attachment_id))],
["name", "datas", "file_type", "res_model", "res_id", "type", "url"]
)
if attachment:
attachment = attachment[0]
else:
return redirect(self.orders_page)
# Check if the user has bought the associated product
res_model = attachment['res_model']
res_id = attachment['res_id']
purchased_products = request.env['account.invoice.line'].get_digital_purchases(request.uid)
if res_model == 'product.product':
if res_id not in purchased_products:
return redirect(self.orders_page)
# Also check for attachments in the product templates
elif res_model == 'product.template':
P = request.env['product.product']
template_ids = map(lambda x: P.browse(x).product_tmpl_id.id, purchased_products)
if res_id not in template_ids:
return redirect(self.orders_page)
else:
return redirect(self.orders_page)
# The client has bought the product, otherwise it would have been blocked by now
if attachment["type"] == "url":
if attachment["url"]:
return redirect(attachment["url"])
else:
return request.not_found()
elif attachment["datas"]:
data = StringIO(base64.standard_b64decode(attachment["datas"]))
return http.send_file(data, filename=attachment['name'], as_attachment=True)
else:
return request.not_found()
|
flumotion-mirror/flumotion | refs/heads/master | flumotion/component/misc/repeater/repeater.py | 3 | # -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L.
# Copyright (C) 2010,2011 Flumotion Services, S.A.
# All rights reserved.
#
# This file may be distributed and/or modified under the terms of
# the GNU Lesser General Public License version 2.1 as published by
# the Free Software Foundation.
# This file is distributed without any warranty; without even the implied
# warranty of merchantability or fitness for a particular purpose.
# See "LICENSE.LGPL" in the source distribution for more information.
#
# Headers in this file shall remain intact.
from flumotion.common import gstreamer, messages, errors
from flumotion.common.i18n import N_, gettexter
from flumotion.component import feedcomponent
T_ = gettexter()
__version__ = "$Rev$"
class Repeater(feedcomponent.ParseLaunchComponent):
def get_pipeline_string(self, properties):
dp = ""
if 'drop-probability' in properties:
vt = gstreamer.get_plugin_version('coreelements')
if not vt:
raise errors.MissingElementError('identity')
if not vt > (0, 10, 12, 0):
self.addMessage(
messages.Warning(T_(N_(
"The 'drop-probability' property is specified, but "
"it only works with GStreamer core newer than 0.10.12."
" You should update your version of GStreamer."))))
else:
drop_probability = properties['drop-probability']
if drop_probability < 0.0 or drop_probability > 1.0:
self.addMessage(
messages.Warning(T_(N_(
"The 'drop-probability' property can only be "
"between 0.0 and 1.0."))))
else:
dp = " drop-probability=%f" % drop_probability
return 'identity silent=true %s' % dp
|
SanchayanMaity/gem5 | refs/heads/CS570 | ext/ply/test/lex_dup3.py | 174 | # lex_dup3.py
#
# Duplicated rule specifiers
import sys
if ".." not in sys.path: sys.path.insert(0,"..")
import ply.lex as lex
tokens = [
"PLUS",
"MINUS",
"NUMBER",
]
t_PLUS = r'\+'
t_MINUS = r'-'
t_NUMBER = r'\d+'
def t_NUMBER(t):
r'\d+'
pass
def t_error(t):
pass
lex.lex()
|
simonemurzilli/geonode | refs/heads/master | geonode/layers/views.py | 7 | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2012 OpenPlans
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
import os
import sys
import logging
import shutil
import traceback
from guardian.shortcuts import get_perms
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.conf import settings
from django.template import RequestContext
from django.utils.translation import ugettext as _
from django.utils import simplejson as json
from django.utils.html import escape
from django.template.defaultfilters import slugify
from django.forms.models import inlineformset_factory
from django.db.models import F
from geonode.tasks.deletion import delete_layer
from geonode.services.models import Service
from geonode.layers.forms import LayerForm, LayerUploadForm, NewLayerUploadForm, LayerAttributeForm
from geonode.base.forms import CategoryForm
from geonode.layers.models import Layer, Attribute, UploadSession
from geonode.base.enumerations import CHARSETS
from geonode.base.models import TopicCategory
from geonode.utils import default_map_config
from geonode.utils import GXPLayer
from geonode.utils import GXPMap
from geonode.layers.utils import file_upload, is_raster, is_vector
from geonode.utils import resolve_object, llbbox_to_mercator
from geonode.people.forms import ProfileForm, PocForm
from geonode.security.views import _perms_info_json
from geonode.documents.models import get_related_documents
from geonode.utils import build_social_links
from geonode.geoserver.helpers import cascading_delete, gs_catalog
CONTEXT_LOG_FILE = None
if 'geonode.geoserver' in settings.INSTALLED_APPS:
from geonode.geoserver.helpers import _render_thumbnail
from geonode.geoserver.helpers import ogc_server_settings
CONTEXT_LOG_FILE = ogc_server_settings.LOG_FILE
logger = logging.getLogger("geonode.layers.views")
DEFAULT_SEARCH_BATCH_SIZE = 10
MAX_SEARCH_BATCH_SIZE = 25
GENERIC_UPLOAD_ERROR = _("There was an error while attempting to upload your data. \
Please try again, or contact and administrator if the problem continues.")
_PERMISSION_MSG_DELETE = _("You are not permitted to delete this layer")
_PERMISSION_MSG_GENERIC = _('You do not have permissions for this layer.')
_PERMISSION_MSG_MODIFY = _("You are not permitted to modify this layer")
_PERMISSION_MSG_METADATA = _(
"You are not permitted to modify this layer's metadata")
_PERMISSION_MSG_VIEW = _("You are not permitted to view this layer")
def log_snippet(log_file):
if not os.path.isfile(log_file):
return "No log file at %s" % log_file
with open(log_file, "r") as f:
f.seek(0, 2) # Seek @ EOF
fsize = f.tell() # Get Size
f.seek(max(fsize - 10024, 0), 0) # Set pos @ last n chars
return f.read()
def _resolve_layer(request, typename, permission='base.view_resourcebase',
msg=_PERMISSION_MSG_GENERIC, **kwargs):
"""
Resolve the layer by the provided typename (which may include service name) and check the optional permission.
"""
service_typename = typename.split(":", 1)
if Service.objects.filter(name=service_typename[0]).exists():
service = Service.objects.filter(name=service_typename[0])
return resolve_object(request,
Layer,
{'service': service[0],
'typename': service_typename[1] if service[0].method != "C" else typename},
permission=permission,
permission_msg=msg,
**kwargs)
else:
return resolve_object(request,
Layer,
{'typename': typename,
'service': None},
permission=permission,
permission_msg=msg,
**kwargs)
# Basic Layer Views #
@login_required
def layer_upload(request, template='upload/layer_upload.html'):
if request.method == 'GET':
ctx = {
'charsets': CHARSETS,
'is_layer': True,
}
return render_to_response(template,
RequestContext(request, ctx))
elif request.method == 'POST':
form = NewLayerUploadForm(request.POST, request.FILES)
tempdir = None
errormsgs = []
out = {'success': False}
if form.is_valid():
title = form.cleaned_data["layer_title"]
# Replace dots in filename - GeoServer REST API upload bug
# and avoid any other invalid characters.
# Use the title if possible, otherwise default to the filename
if title is not None and len(title) > 0:
name_base = title
else:
name_base, __ = os.path.splitext(
form.cleaned_data["base_file"].name)
name = slugify(name_base.replace(".", "_"))
try:
# Moved this inside the try/except block because it can raise
# exceptions when unicode characters are present.
# This should be followed up in upstream Django.
tempdir, base_file = form.write_files()
saved_layer = file_upload(
base_file,
name=name,
user=request.user,
overwrite=False,
charset=form.cleaned_data["charset"],
abstract=form.cleaned_data["abstract"],
title=form.cleaned_data["layer_title"],
)
except Exception as e:
exception_type, error, tb = sys.exc_info()
logger.exception(e)
out['success'] = False
out['errors'] = str(error)
# Assign the error message to the latest UploadSession from that user.
latest_uploads = UploadSession.objects.filter(user=request.user).order_by('-date')
if latest_uploads.count() > 0:
upload_session = latest_uploads[0]
upload_session.error = str(error)
upload_session.traceback = traceback.format_exc(tb)
upload_session.context = log_snippet(CONTEXT_LOG_FILE)
upload_session.save()
out['traceback'] = upload_session.traceback
out['context'] = upload_session.context
out['upload_session'] = upload_session.id
else:
out['success'] = True
if hasattr(saved_layer, 'info'):
out['info'] = saved_layer.info
out['url'] = reverse(
'layer_detail', args=[
saved_layer.service_typename])
upload_session = saved_layer.upload_session
upload_session.processed = True
upload_session.save()
permissions = form.cleaned_data["permissions"]
if permissions is not None and len(permissions.keys()) > 0:
saved_layer.set_permissions(permissions)
finally:
if tempdir is not None:
shutil.rmtree(tempdir)
else:
for e in form.errors.values():
errormsgs.extend([escape(v) for v in e])
out['errors'] = form.errors
out['errormsgs'] = errormsgs
if out['success']:
status_code = 200
else:
status_code = 400
return HttpResponse(
json.dumps(out),
mimetype='application/json',
status=status_code)
def layer_detail(request, layername, template='layers/layer_detail.html'):
layer = _resolve_layer(
request,
layername,
'base.view_resourcebase',
_PERMISSION_MSG_VIEW)
# assert False, str(layer_bbox)
config = layer.attribute_config()
# Add required parameters for GXP lazy-loading
layer_bbox = layer.bbox
bbox = [float(coord) for coord in list(layer_bbox[0:4])]
srid = layer.srid
# Transform WGS84 to Mercator.
config["srs"] = srid if srid != "EPSG:4326" else "EPSG:900913"
config["bbox"] = llbbox_to_mercator([float(coord) for coord in bbox])
config["title"] = layer.title
config["queryable"] = True
if layer.storeType == "remoteStore":
service = layer.service
source_params = {
"ptype": service.ptype,
"remote": True,
"url": service.base_url,
"name": service.name}
maplayer = GXPLayer(
name=layer.typename,
ows_url=layer.ows_url,
layer_params=json.dumps(config),
source_params=json.dumps(source_params))
else:
maplayer = GXPLayer(
name=layer.typename,
ows_url=layer.ows_url,
layer_params=json.dumps(config))
# Update count for popularity ranking,
# but do not includes admins or resource owners
if request.user != layer.owner and not request.user.is_superuser:
Layer.objects.filter(
id=layer.id).update(popular_count=F('popular_count') + 1)
# center/zoom don't matter; the viewer will center on the layer bounds
map_obj = GXPMap(projection="EPSG:900913")
NON_WMS_BASE_LAYERS = [
la for la in default_map_config()[1] if la.ows_url is None]
metadata = layer.link_set.metadata().filter(
name__in=settings.DOWNLOAD_FORMATS_METADATA)
context_dict = {
"resource": layer,
'perms_list': get_perms(request.user, layer.get_self_resource()),
"permissions_json": _perms_info_json(layer),
"documents": get_related_documents(layer),
"metadata": metadata,
"is_layer": True,
"wps_enabled": settings.OGC_SERVER['default']['WPS_ENABLED'],
}
context_dict["viewer"] = json.dumps(
map_obj.viewer_json(request.user, * (NON_WMS_BASE_LAYERS + [maplayer])))
context_dict["preview"] = getattr(
settings,
'LAYER_PREVIEW_LIBRARY',
'leaflet')
if request.user.has_perm('download_resourcebase', layer.get_self_resource()):
if layer.storeType == 'dataStore':
links = layer.link_set.download().filter(
name__in=settings.DOWNLOAD_FORMATS_VECTOR)
else:
links = layer.link_set.download().filter(
name__in=settings.DOWNLOAD_FORMATS_RASTER)
context_dict["links"] = links
if settings.SOCIAL_ORIGINS:
context_dict["social_links"] = build_social_links(request, layer)
return render_to_response(template, RequestContext(request, context_dict))
@login_required
def layer_metadata(request, layername, template='layers/layer_metadata.html'):
layer = _resolve_layer(
request,
layername,
'base.change_resourcebase_metadata',
_PERMISSION_MSG_METADATA)
layer_attribute_set = inlineformset_factory(
Layer,
Attribute,
extra=0,
form=LayerAttributeForm,
)
topic_category = layer.category
poc = layer.poc
metadata_author = layer.metadata_author
if request.method == "POST":
layer_form = LayerForm(request.POST, instance=layer, prefix="resource")
attribute_form = layer_attribute_set(
request.POST,
instance=layer,
prefix="layer_attribute_set",
queryset=Attribute.objects.order_by('display_order'))
category_form = CategoryForm(
request.POST,
prefix="category_choice_field",
initial=int(
request.POST["category_choice_field"]) if "category_choice_field" in request.POST else None)
else:
layer_form = LayerForm(instance=layer, prefix="resource")
attribute_form = layer_attribute_set(
instance=layer,
prefix="layer_attribute_set",
queryset=Attribute.objects.order_by('display_order'))
category_form = CategoryForm(
prefix="category_choice_field",
initial=topic_category.id if topic_category else None)
if request.method == "POST" and layer_form.is_valid(
) and attribute_form.is_valid() and category_form.is_valid():
new_poc = layer_form.cleaned_data['poc']
new_author = layer_form.cleaned_data['metadata_author']
new_keywords = layer_form.cleaned_data['keywords']
if new_poc is None:
if poc is None:
poc_form = ProfileForm(
request.POST,
prefix="poc",
instance=poc)
else:
poc_form = ProfileForm(request.POST, prefix="poc")
if poc_form.has_changed and poc_form.is_valid():
new_poc = poc_form.save()
if new_author is None:
if metadata_author is None:
author_form = ProfileForm(request.POST, prefix="author",
instance=metadata_author)
else:
author_form = ProfileForm(request.POST, prefix="author")
if author_form.has_changed and author_form.is_valid():
new_author = author_form.save()
new_category = TopicCategory.objects.get(
id=category_form.cleaned_data['category_choice_field'])
for form in attribute_form.cleaned_data:
la = Attribute.objects.get(id=int(form['id'].id))
la.description = form["description"]
la.attribute_label = form["attribute_label"]
la.visible = form["visible"]
la.display_order = form["display_order"]
la.save()
if new_poc is not None and new_author is not None:
new_keywords = layer_form.cleaned_data['keywords']
layer.keywords.clear()
layer.keywords.add(*new_keywords)
the_layer = layer_form.save()
the_layer.poc = new_poc
the_layer.metadata_author = new_author
Layer.objects.filter(id=the_layer.id).update(
category=new_category
)
if getattr(settings, 'SLACK_ENABLED', False):
try:
from geonode.contrib.slack.utils import build_slack_message_layer, send_slack_messages
send_slack_messages(build_slack_message_layer("layer_edit", the_layer))
except:
print "Could not send slack message."
return HttpResponseRedirect(
reverse(
'layer_detail',
args=(
layer.service_typename,
)))
if poc is None:
poc_form = ProfileForm(instance=poc, prefix="poc")
else:
layer_form.fields['poc'].initial = poc.id
poc_form = ProfileForm(prefix="poc")
poc_form.hidden = True
if metadata_author is None:
author_form = ProfileForm(instance=metadata_author, prefix="author")
else:
layer_form.fields['metadata_author'].initial = metadata_author.id
author_form = ProfileForm(prefix="author")
author_form.hidden = True
return render_to_response(template, RequestContext(request, {
"layer": layer,
"layer_form": layer_form,
"poc_form": poc_form,
"author_form": author_form,
"attribute_form": attribute_form,
"category_form": category_form,
}))
@login_required
def layer_change_poc(request, ids, template='layers/layer_change_poc.html'):
layers = Layer.objects.filter(id__in=ids.split('_'))
if request.method == 'POST':
form = PocForm(request.POST)
if form.is_valid():
for layer in layers:
layer.poc = form.cleaned_data['contact']
layer.save()
# Process the data in form.cleaned_data
# ...
# Redirect after POST
return HttpResponseRedirect('/admin/maps/layer')
else:
form = PocForm() # An unbound form
return render_to_response(
template, RequestContext(
request, {
'layers': layers, 'form': form}))
@login_required
def layer_replace(request, layername, template='layers/layer_replace.html'):
layer = _resolve_layer(
request,
layername,
'base.change_resourcebase',
_PERMISSION_MSG_MODIFY)
if request.method == 'GET':
ctx = {
'charsets': CHARSETS,
'layer': layer,
'is_featuretype': layer.is_vector(),
'is_layer': True,
}
return render_to_response(template,
RequestContext(request, ctx))
elif request.method == 'POST':
form = LayerUploadForm(request.POST, request.FILES)
tempdir = None
out = {}
if form.is_valid():
try:
tempdir, base_file = form.write_files()
if layer.is_vector() and is_raster(base_file):
out['success'] = False
out['errors'] = _("You are attempting to replace a vector layer with a raster.")
elif (not layer.is_vector()) and is_vector(base_file):
out['success'] = False
out['errors'] = _("You are attempting to replace a raster layer with a vector.")
else:
# delete geoserver's store before upload
cat = gs_catalog
cascading_delete(cat, layer.typename)
saved_layer = file_upload(
base_file,
name=layer.name,
user=request.user,
overwrite=True,
charset=form.cleaned_data["charset"],
)
out['success'] = True
out['url'] = reverse(
'layer_detail', args=[
saved_layer.service_typename])
except Exception as e:
out['success'] = False
out['errors'] = str(e)
finally:
if tempdir is not None:
shutil.rmtree(tempdir)
else:
errormsgs = []
for e in form.errors.values():
errormsgs.append([escape(v) for v in e])
out['errors'] = form.errors
out['errormsgs'] = errormsgs
if out['success']:
status_code = 200
else:
status_code = 400
return HttpResponse(
json.dumps(out),
mimetype='application/json',
status=status_code)
@login_required
def layer_remove(request, layername, template='layers/layer_remove.html'):
layer = _resolve_layer(
request,
layername,
'base.delete_resourcebase',
_PERMISSION_MSG_DELETE)
if (request.method == 'GET'):
return render_to_response(template, RequestContext(request, {
"layer": layer
}))
if (request.method == 'POST'):
try:
delete_layer.delay(object_id=layer.id)
except Exception as e:
message = '{0}: {1}.'.format(_('Unable to delete layer'), layer.typename)
if 'referenced by layer group' in getattr(e, 'message', ''):
message = _('This layer is a member of a layer group, you must remove the layer from the group '
'before deleting.')
messages.error(request, message)
return render_to_response(template, RequestContext(request, {"layer": layer}))
return HttpResponseRedirect(reverse("layer_browse"))
else:
return HttpResponse("Not allowed", status=403)
def layer_thumbnail(request, layername):
if request.method == 'POST':
layer_obj = _resolve_layer(request, layername)
try:
image = _render_thumbnail(request.body)
if not image:
return
filename = "layer-%s-thumb.png" % layer_obj.uuid
layer_obj.save_thumbnail(filename, image)
return HttpResponse('Thumbnail saved')
except:
return HttpResponse(
content='error saving thumbnail',
status=500,
mimetype='text/plain'
)
|
lthurlow/Boolean-Constrained-Routing | refs/heads/master | networkx-1.8.1/networkx/algorithms/tests/test_cycles.py | 20 | #!/usr/bin/env python
from nose.tools import *
import networkx
import networkx as nx
class TestCycles:
def setUp(self):
G=networkx.Graph()
G.add_cycle([0,1,2,3])
G.add_cycle([0,3,4,5])
G.add_cycle([0,1,6,7,8])
G.add_edge(8,9)
self.G=G
def is_cyclic_permutation(self,a,b):
n=len(a)
if len(b)!=n:
return False
l=a+a
return any(l[i:i+n]==b for i in range(2*n-n+1))
def test_cycle_basis(self):
G=self.G
cy=networkx.cycle_basis(G,0)
sort_cy= sorted( sorted(c) for c in cy )
assert_equal(sort_cy, [[0,1,2,3],[0,1,6,7,8],[0,3,4,5]])
cy=networkx.cycle_basis(G,1)
sort_cy= sorted( sorted(c) for c in cy )
assert_equal(sort_cy, [[0,1,2,3],[0,1,6,7,8],[0,3,4,5]])
cy=networkx.cycle_basis(G,9)
sort_cy= sorted( sorted(c) for c in cy )
assert_equal(sort_cy, [[0,1,2,3],[0,1,6,7,8],[0,3,4,5]])
# test disconnected graphs
G.add_cycle(list("ABC"))
cy=networkx.cycle_basis(G,9)
sort_cy= sorted(sorted(c) for c in cy[:-1]) + [sorted(cy[-1])]
assert_equal(sort_cy, [[0,1,2,3],[0,1,6,7,8],[0,3,4,5],['A','B','C']])
@raises(nx.NetworkXNotImplemented)
def test_cycle_basis(self):
G=nx.DiGraph()
cy=networkx.cycle_basis(G,0)
@raises(nx.NetworkXNotImplemented)
def test_cycle_basis(self):
G=nx.MultiGraph()
cy=networkx.cycle_basis(G,0)
def test_simple_cycles(self):
G = nx.DiGraph([(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)])
cc=sorted(nx.simple_cycles(G))
ca=[[0], [0, 1, 2], [0, 2], [1, 2], [2]]
for c in cc:
assert_true(any(self.is_cyclic_permutation(c,rc) for rc in ca))
@raises(nx.NetworkXNotImplemented)
def test_simple_cycles_graph(self):
G = nx.Graph()
c = sorted(nx.simple_cycles(G))
def test_unsortable(self):
# TODO What does this test do? das 6/2013
G=nx.DiGraph()
G.add_cycle(['a',1])
c=list(nx.simple_cycles(G))
def test_simple_cycles_small(self):
G = nx.DiGraph()
G.add_cycle([1,2,3])
c=sorted(nx.simple_cycles(G))
assert_equal(len(c),1)
assert_true(self.is_cyclic_permutation(c[0],[1,2,3]))
G.add_cycle([10,20,30])
cc=sorted(nx.simple_cycles(G))
ca=[[1,2,3],[10,20,30]]
for c in cc:
assert_true(any(self.is_cyclic_permutation(c,rc) for rc in ca))
def test_simple_cycles_empty(self):
G = nx.DiGraph()
assert_equal(list(nx.simple_cycles(G)),[])
def test_complete_directed_graph(self):
# see table 2 in Johnson's paper
ncircuits=[1,5,20,84,409,2365,16064]
for n,c in zip(range(2,9),ncircuits):
G=nx.DiGraph(nx.complete_graph(n))
assert_equal(len(list(nx.simple_cycles(G))),c)
def worst_case_graph(self,k):
# see figure 1 in Johnson's paper
# this graph has excactly 3k simple cycles
G=nx.DiGraph()
for n in range(2,k+2):
G.add_edge(1,n)
G.add_edge(n,k+2)
G.add_edge(2*k+1,1)
for n in range(k+2,2*k+2):
G.add_edge(n,2*k+2)
G.add_edge(n,n+1)
G.add_edge(2*k+3,k+2)
for n in range(2*k+3,3*k+3):
G.add_edge(2*k+2,n)
G.add_edge(n,3*k+3)
G.add_edge(3*k+3,2*k+2)
return G
def test_worst_case_graph(self):
# see figure 1 in Johnson's paper
for k in range(3,10):
G=self.worst_case_graph(k)
l=len(list(nx.simple_cycles(G)))
assert_equal(l,3*k)
def test_recursive_simple_and_not(self):
for k in range(2,10):
G=self.worst_case_graph(k)
cc=sorted(nx.simple_cycles(G))
rcc=sorted(nx.recursive_simple_cycles(G))
assert_equal(len(cc),len(rcc))
for c in cc:
assert_true(any(self.is_cyclic_permutation(c,rc) for rc in rcc))
|
muravjov/ansible | refs/heads/stable-1.9 | lib/ansible/utils/unicode.py | 128 | # (c) 2012-2014, Toshio Kuraotmi <a.badger@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
# to_bytes and to_unicode were written by Toshio Kuratomi for the
# python-kitchen library https://pypi.python.org/pypi/kitchen
# They are licensed in kitchen under the terms of the GPLv2+
# They were copied and modified for use in ansible by Toshio in Jan 2015
# (simply removing the deprecated features)
#: Aliases for the utf-8 codec
_UTF8_ALIASES = frozenset(('utf-8', 'UTF-8', 'utf8', 'UTF8', 'utf_8', 'UTF_8',
'utf', 'UTF', 'u8', 'U8'))
#: Aliases for the latin-1 codec
_LATIN1_ALIASES = frozenset(('latin-1', 'LATIN-1', 'latin1', 'LATIN1',
'latin', 'LATIN', 'l1', 'L1', 'cp819', 'CP819', '8859', 'iso8859-1',
'ISO8859-1', 'iso-8859-1', 'ISO-8859-1'))
# EXCEPTION_CONVERTERS is defined below due to using to_unicode
def to_unicode(obj, encoding='utf-8', errors='replace', nonstring=None):
'''Convert an object into a :class:`unicode` string
:arg obj: Object to convert to a :class:`unicode` string. This should
normally be a byte :class:`str`
:kwarg encoding: What encoding to try converting the byte :class:`str` as.
Defaults to :term:`utf-8`
:kwarg errors: If errors are found while decoding, perform this action.
Defaults to ``replace`` which replaces the invalid bytes with
a character that means the bytes were unable to be decoded. Other
values are the same as the error handling schemes in the `codec base
classes
<http://docs.python.org/library/codecs.html#codec-base-classes>`_.
For instance ``strict`` which raises an exception and ``ignore`` which
simply omits the non-decodable characters.
:kwarg nonstring: How to treat nonstring values. Possible values are:
:simplerepr: Attempt to call the object's "simple representation"
method and return that value. Python-2.3+ has two methods that
try to return a simple representation: :meth:`object.__unicode__`
and :meth:`object.__str__`. We first try to get a usable value
from :meth:`object.__unicode__`. If that fails we try the same
with :meth:`object.__str__`.
:empty: Return an empty :class:`unicode` string
:strict: Raise a :exc:`TypeError`
:passthru: Return the object unchanged
:repr: Attempt to return a :class:`unicode` string of the repr of the
object
Default is ``simplerepr``
:raises TypeError: if :attr:`nonstring` is ``strict`` and
a non-:class:`basestring` object is passed in or if :attr:`nonstring`
is set to an unknown value
:raises UnicodeDecodeError: if :attr:`errors` is ``strict`` and
:attr:`obj` is not decodable using the given encoding
:returns: :class:`unicode` string or the original object depending on the
value of :attr:`nonstring`.
Usually this should be used on a byte :class:`str` but it can take both
byte :class:`str` and :class:`unicode` strings intelligently. Nonstring
objects are handled in different ways depending on the setting of the
:attr:`nonstring` parameter.
The default values of this function are set so as to always return
a :class:`unicode` string and never raise an error when converting from
a byte :class:`str` to a :class:`unicode` string. However, when you do
not pass validly encoded text (or a nonstring object), you may end up with
output that you don't expect. Be sure you understand the requirements of
your data, not just ignore errors by passing it through this function.
'''
# Could use isbasestring/isunicode here but we want this code to be as
# fast as possible
if isinstance(obj, basestring):
if isinstance(obj, unicode):
return obj
if encoding in _UTF8_ALIASES:
return unicode(obj, 'utf-8', errors)
if encoding in _LATIN1_ALIASES:
return unicode(obj, 'latin-1', errors)
return obj.decode(encoding, errors)
if not nonstring:
nonstring = 'simplerepr'
if nonstring == 'empty':
return u''
elif nonstring == 'passthru':
return obj
elif nonstring == 'simplerepr':
try:
simple = obj.__unicode__()
except (AttributeError, UnicodeError):
simple = None
if not simple:
try:
simple = str(obj)
except UnicodeError:
try:
simple = obj.__str__()
except (UnicodeError, AttributeError):
simple = u''
if isinstance(simple, str):
return unicode(simple, encoding, errors)
return simple
elif nonstring in ('repr', 'strict'):
obj_repr = repr(obj)
if isinstance(obj_repr, str):
obj_repr = unicode(obj_repr, encoding, errors)
if nonstring == 'repr':
return obj_repr
raise TypeError('to_unicode was given "%(obj)s" which is neither'
' a byte string (str) or a unicode string' %
{'obj': obj_repr.encode(encoding, 'replace')})
raise TypeError('nonstring value, %(param)s, is not set to a valid'
' action' % {'param': nonstring})
def to_bytes(obj, encoding='utf-8', errors='replace', nonstring=None):
'''Convert an object into a byte :class:`str`
:arg obj: Object to convert to a byte :class:`str`. This should normally
be a :class:`unicode` string.
:kwarg encoding: Encoding to use to convert the :class:`unicode` string
into a byte :class:`str`. Defaults to :term:`utf-8`.
:kwarg errors: If errors are found while encoding, perform this action.
Defaults to ``replace`` which replaces the invalid bytes with
a character that means the bytes were unable to be encoded. Other
values are the same as the error handling schemes in the `codec base
classes
<http://docs.python.org/library/codecs.html#codec-base-classes>`_.
For instance ``strict`` which raises an exception and ``ignore`` which
simply omits the non-encodable characters.
:kwarg nonstring: How to treat nonstring values. Possible values are:
:simplerepr: Attempt to call the object's "simple representation"
method and return that value. Python-2.3+ has two methods that
try to return a simple representation: :meth:`object.__unicode__`
and :meth:`object.__str__`. We first try to get a usable value
from :meth:`object.__str__`. If that fails we try the same
with :meth:`object.__unicode__`.
:empty: Return an empty byte :class:`str`
:strict: Raise a :exc:`TypeError`
:passthru: Return the object unchanged
:repr: Attempt to return a byte :class:`str` of the :func:`repr` of the
object
Default is ``simplerepr``.
:raises TypeError: if :attr:`nonstring` is ``strict`` and
a non-:class:`basestring` object is passed in or if :attr:`nonstring`
is set to an unknown value.
:raises UnicodeEncodeError: if :attr:`errors` is ``strict`` and all of the
bytes of :attr:`obj` are unable to be encoded using :attr:`encoding`.
:returns: byte :class:`str` or the original object depending on the value
of :attr:`nonstring`.
.. warning::
If you pass a byte :class:`str` into this function the byte
:class:`str` is returned unmodified. It is **not** re-encoded with
the specified :attr:`encoding`. The easiest way to achieve that is::
to_bytes(to_unicode(text), encoding='utf-8')
The initial :func:`to_unicode` call will ensure text is
a :class:`unicode` string. Then, :func:`to_bytes` will turn that into
a byte :class:`str` with the specified encoding.
Usually, this should be used on a :class:`unicode` string but it can take
either a byte :class:`str` or a :class:`unicode` string intelligently.
Nonstring objects are handled in different ways depending on the setting
of the :attr:`nonstring` parameter.
The default values of this function are set so as to always return a byte
:class:`str` and never raise an error when converting from unicode to
bytes. However, when you do not pass an encoding that can validly encode
the object (or a non-string object), you may end up with output that you
don't expect. Be sure you understand the requirements of your data, not
just ignore errors by passing it through this function.
'''
# Could use isbasestring, isbytestring here but we want this to be as fast
# as possible
if isinstance(obj, basestring):
if isinstance(obj, str):
return obj
return obj.encode(encoding, errors)
if not nonstring:
nonstring = 'simplerepr'
if nonstring == 'empty':
return ''
elif nonstring == 'passthru':
return obj
elif nonstring == 'simplerepr':
try:
simple = str(obj)
except UnicodeError:
try:
simple = obj.__str__()
except (AttributeError, UnicodeError):
simple = None
if not simple:
try:
simple = obj.__unicode__()
except (AttributeError, UnicodeError):
simple = ''
if isinstance(simple, unicode):
simple = simple.encode(encoding, 'replace')
return simple
elif nonstring in ('repr', 'strict'):
try:
obj_repr = obj.__repr__()
except (AttributeError, UnicodeError):
obj_repr = ''
if isinstance(obj_repr, unicode):
obj_repr = obj_repr.encode(encoding, errors)
else:
obj_repr = str(obj_repr)
if nonstring == 'repr':
return obj_repr
raise TypeError('to_bytes was given "%(obj)s" which is neither'
' a unicode string or a byte string (str)' % {'obj': obj_repr})
raise TypeError('nonstring value, %(param)s, is not set to a valid'
' action' % {'param': nonstring})
# force the return value of a function to be unicode. Use with partial to
# ensure that a filter will return unicode values.
def unicode_wrap(func, *args, **kwargs):
return to_unicode(func(*args, **kwargs), nonstring='passthru')
|
DatapuntAmsterdam/handelsregister | refs/heads/master | web/handelsregister/search/input_analyzer.py | 1 | """
Analyze the query input from user before starting the
search
"""
import string
import re
_REPLACE_TABLE = "".maketrans(
string.punctuation, len(string.punctuation) * " ")
class InputQAnalyzer(object):
"""
The InoutQAnalyzer takes a plain query string and performs various analyses
on it. It contains various is_XXX methods that are used to determine if
this query could refer to an XXX.
"""
def __init__(self, query: str):
self.query = query
self._cleaned_query = query.translate(_REPLACE_TABLE).lower()
self._tokens = re.findall('[^0-9 ]+|\\d+', self._cleaned_query)
self._token_count = len(self._tokens)
def get_id(self) -> str:
"""
We expect only digits
"""
if not self._token_count or self._token_count > 1:
return ""
first = self._tokens[0]
if first.isdigit():
return first
return ""
def get_handelsnaam(self) -> str:
"""
Get the querystring
"""
# could be anything...
return self._cleaned_query
|
QianBIG/odoo | refs/heads/8.0 | addons/portal_project_issue/tests/test_access_rights.py | 338 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Business Applications
# Copyright (c) 2013-TODAY OpenERP S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.addons.portal_project.tests.test_access_rights import TestPortalProjectBase
from openerp.exceptions import AccessError
from openerp.osv.orm import except_orm
from openerp.tools import mute_logger
class TestPortalProjectBase(TestPortalProjectBase):
def setUp(self):
super(TestPortalProjectBase, self).setUp()
cr, uid = self.cr, self.uid
# Useful models
self.project_issue = self.registry('project.issue')
# Various test issues
self.issue_1_id = self.project_issue.create(cr, uid, {
'name': 'Test1', 'user_id': False, 'project_id': self.project_pigs_id}, {'mail_create_nolog': True})
self.issue_2_id = self.project_issue.create(cr, uid, {
'name': 'Test2', 'user_id': False, 'project_id': self.project_pigs_id}, {'mail_create_nolog': True})
self.issue_3_id = self.project_issue.create(cr, uid, {
'name': 'Test3', 'user_id': False, 'project_id': self.project_pigs_id}, {'mail_create_nolog': True})
self.issue_4_id = self.project_issue.create(cr, uid, {
'name': 'Test4', 'user_id': self.user_projectuser_id, 'project_id': self.project_pigs_id}, {'mail_create_nolog': True})
self.issue_5_id = self.project_issue.create(cr, uid, {
'name': 'Test5', 'user_id': self.user_portal_id, 'project_id': self.project_pigs_id}, {'mail_create_nolog': True})
self.issue_6_id = self.project_issue.create(cr, uid, {
'name': 'Test6', 'user_id': self.user_public_id, 'project_id': self.project_pigs_id}, {'mail_create_nolog': True})
class TestPortalIssue(TestPortalProjectBase):
@mute_logger('openerp.addons.base.ir.ir_model', 'openerp.models')
def test_00_project_access_rights(self):
""" Test basic project access rights, for project and portal_project """
cr, uid, pigs_id = self.cr, self.uid, self.project_pigs_id
# ----------------------------------------
# CASE1: public project
# ----------------------------------------
# Do: Alfred reads project -> ok (employee ok public)
# Test: all project issues visible
issue_ids = self.project_issue.search(cr, self.user_projectuser_id, [('project_id', '=', pigs_id)])
test_issue_ids = set([self.issue_1_id, self.issue_2_id, self.issue_3_id, self.issue_4_id, self.issue_5_id, self.issue_6_id])
self.assertEqual(set(issue_ids), test_issue_ids,
'access rights: project user cannot see all issues of a public project')
# Test: all project issues readable
self.project_issue.read(cr, self.user_projectuser_id, issue_ids, ['name'])
# Test: all project issues writable
self.project_issue.write(cr, self.user_projectuser_id, issue_ids, {'description': 'TestDescription'})
# Do: Bert reads project -> crash, no group
# Test: no project issue visible
self.assertRaises(AccessError, self.project_issue.search, cr, self.user_none_id, [('project_id', '=', pigs_id)])
# Test: no project issue readable
self.assertRaises(AccessError, self.project_issue.read, cr, self.user_none_id, issue_ids, ['name'])
# Test: no project issue writable
self.assertRaises(AccessError, self.project_issue.write, cr, self.user_none_id, issue_ids, {'description': 'TestDescription'})
# Do: Chell reads project -> ok (portal ok public)
# Test: all project issues visible
issue_ids = self.project_issue.search(cr, self.user_portal_id, [('project_id', '=', pigs_id)])
self.assertEqual(set(issue_ids), test_issue_ids,
'access rights: project user cannot see all issues of a public project')
# Test: all project issues readable
self.project_issue.read(cr, self.user_portal_id, issue_ids, ['name'])
# Test: no project issue writable
self.assertRaises(AccessError, self.project_issue.write, cr, self.user_portal_id, issue_ids, {'description': 'TestDescription'})
# Do: Donovan reads project -> ok (public ok public)
# Test: all project issues visible
issue_ids = self.project_issue.search(cr, self.user_public_id, [('project_id', '=', pigs_id)])
self.assertEqual(set(issue_ids), test_issue_ids,
'access rights: project user cannot see all issues of a public project')
# ----------------------------------------
# CASE2: portal project
# ----------------------------------------
self.project_project.write(cr, uid, [pigs_id], {'privacy_visibility': 'portal'})
# Do: Alfred reads project -> ok (employee ok public)
# Test: all project issues visible
issue_ids = self.project_issue.search(cr, self.user_projectuser_id, [('project_id', '=', pigs_id)])
self.assertEqual(set(issue_ids), test_issue_ids,
'access rights: project user cannot see all issues of a portal project')
# Do: Bert reads project -> crash, no group
# Test: no project issue searchable
self.assertRaises(AccessError, self.project_issue.search, cr, self.user_none_id, [('project_id', '=', pigs_id)])
# Data: issue follower
self.project_issue.message_subscribe_users(cr, self.user_projectuser_id, [self.issue_1_id, self.issue_3_id], [self.user_portal_id])
# Do: Chell reads project -> ok (portal ok public)
# Test: only followed project issues visible + assigned
issue_ids = self.project_issue.search(cr, self.user_portal_id, [('project_id', '=', pigs_id)])
test_issue_ids = set([self.issue_1_id, self.issue_3_id, self.issue_5_id])
self.assertEqual(set(issue_ids), test_issue_ids,
'access rights: portal user should see the followed issues of a portal project')
# Data: issue follower cleaning
self.project_issue.message_unsubscribe_users(cr, self.user_projectuser_id, [self.issue_1_id, self.issue_3_id], [self.user_portal_id])
# ----------------------------------------
# CASE3: employee project
# ----------------------------------------
self.project_project.write(cr, uid, [pigs_id], {'privacy_visibility': 'employees'})
# Do: Alfred reads project -> ok (employee ok employee)
# Test: all project issues visible
issue_ids = self.project_issue.search(cr, self.user_projectuser_id, [('project_id', '=', pigs_id)])
test_issue_ids = set([self.issue_1_id, self.issue_2_id, self.issue_3_id, self.issue_4_id, self.issue_5_id, self.issue_6_id])
self.assertEqual(set(issue_ids), test_issue_ids,
'access rights: project user cannot see all issues of an employees project')
# Do: Chell reads project -> ko (portal ko employee)
# Test: no project issue visible + assigned
issue_ids = self.project_issue.search(cr, self.user_portal_id, [('project_id', '=', pigs_id)])
self.assertFalse(issue_ids, 'access rights: portal user should not see issues of an employees project, even if assigned')
# ----------------------------------------
# CASE4: followers project
# ----------------------------------------
self.project_project.write(cr, uid, [pigs_id], {'privacy_visibility': 'followers'})
# Do: Alfred reads project -> ko (employee ko followers)
# Test: no project issue visible
issue_ids = self.project_issue.search(cr, self.user_projectuser_id, [('project_id', '=', pigs_id)])
test_issue_ids = set([self.issue_4_id])
self.assertEqual(set(issue_ids), test_issue_ids,
'access rights: employee user should not see issues of a not-followed followers project, only assigned')
# Do: Chell reads project -> ko (portal ko employee)
# Test: no project issue visible
issue_ids = self.project_issue.search(cr, self.user_portal_id, [('project_id', '=', pigs_id)])
test_issue_ids = set([self.issue_5_id])
self.assertEqual(set(issue_ids), test_issue_ids,
'access rights: portal user should not see issues of a not-followed followers project, only assigned')
# Data: subscribe Alfred, Chell and Donovan as follower
self.project_project.message_subscribe_users(cr, uid, [pigs_id], [self.user_projectuser_id, self.user_portal_id, self.user_public_id])
self.project_issue.message_subscribe_users(cr, self.user_manager_id, [self.issue_1_id, self.issue_3_id], [self.user_portal_id, self.user_projectuser_id])
# Do: Alfred reads project -> ok (follower ok followers)
# Test: followed + assigned issues visible
issue_ids = self.project_issue.search(cr, self.user_projectuser_id, [('project_id', '=', pigs_id)])
test_issue_ids = set([self.issue_1_id, self.issue_3_id, self.issue_4_id])
self.assertEqual(set(issue_ids), test_issue_ids,
'access rights: employee user should not see followed + assigned issues of a follower project')
# Do: Chell reads project -> ok (follower ok follower)
# Test: followed + assigned issues visible
issue_ids = self.project_issue.search(cr, self.user_portal_id, [('project_id', '=', pigs_id)])
test_issue_ids = set([self.issue_1_id, self.issue_3_id, self.issue_5_id])
self.assertEqual(set(issue_ids), test_issue_ids,
'access rights: employee user should not see followed + assigned issues of a follower project')
|
kkdang/sage-data-analysis | refs/heads/master | cmc_code/compare_GTF_to_annotation.py | 1 | #! /usr/bin/env python
# KKD for Sage Bionetworks
# Feb. 11, 2014
import synapseclient, os, subprocess, pybedtools
syn = synapseclient.login()
mergedGTF_entity = syn.get(entity='syn2338565', downloadLocation = os.getcwd())
#ENSGv70_entity = syn.get(entity='syn2215531', downloadLocation = os.getcwd())
mergedGTF = pybedtools.BedTool(mergedGTF_entity.path)
#ENSGv70_exons = pybedtools.BedTool('/work/DAT_107__common_mind/Data/Homo_sapiens.GRCh37.70.processed.gtf').filter(lambda x: x[2] == 'exon').saveas('ENSGv70_exons.gff')
ENSGv70_exons = pybedtools.BedTool('ENSGv70_exons.gff')
def countNovelExons(fraction):
intersectFile = ''.join(['novelExons_f', str(fraction), '.gff'])
novelExons = mergedGTF.intersect(ENSGv70_exons, v=True, f=fraction).saveas(intersectFile)
totalNovelCount = subprocess.call(' '.join(['awk \'{print $1"-"$4"-"$5}\'', intersectFile, '| sort | uniq | wc -l']), shell = True)
onlyJNovelCount = subprocess.call(' '.join(['grep \'class_code "j"\'', intersectFile, '| awk \'{print $1"-"$4"-"$5}\' | sort | uniq | wc -l']), shell = True)
print 'Required fractional match: %f; total: %d, total-J: %d' % (fraction, totalNovelCount, onlyJNovelCount)
countNovelExons(fraction=0.8)
|
dd00/commandergenius | refs/heads/dd00 | project/jni/python/src/Lib/test/test_zipfile64.py | 159 | # Tests of the full ZIP64 functionality of zipfile
# The test_support.requires call is the only reason for keeping this separate
# from test_zipfile
from test import test_support
# XXX(nnorwitz): disable this test by looking for extra largfile resource
# which doesn't exist. This test takes over 30 minutes to run in general
# and requires more disk space than most of the buildbots.
test_support.requires(
'extralargefile',
'test requires loads of disk-space bytes and a long time to run'
)
# We can test part of the module without zlib.
try:
import zlib
except ImportError:
zlib = None
import zipfile, os, unittest
import time
import sys
from tempfile import TemporaryFile
from test.test_support import TESTFN, run_unittest
TESTFN2 = TESTFN + "2"
# How much time in seconds can pass before we print a 'Still working' message.
_PRINT_WORKING_MSG_INTERVAL = 5 * 60
class TestsWithSourceFile(unittest.TestCase):
def setUp(self):
# Create test data.
# xrange() is important here -- don't want to create immortal space
# for a million ints.
line_gen = ("Test of zipfile line %d." % i for i in xrange(1000000))
self.data = '\n'.join(line_gen)
# And write it to a file.
fp = open(TESTFN, "wb")
fp.write(self.data)
fp.close()
def zipTest(self, f, compression):
# Create the ZIP archive.
zipfp = zipfile.ZipFile(f, "w", compression, allowZip64=True)
# It will contain enough copies of self.data to reach about 6GB of
# raw data to store.
filecount = 6*1024**3 // len(self.data)
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
for num in range(filecount):
zipfp.writestr("testfn%d" % num, self.data)
# Print still working message since this test can be really slow
if next_time <= time.time():
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
print >>sys.__stdout__, (
' zipTest still writing %d of %d, be patient...' %
(num, filecount))
sys.__stdout__.flush()
zipfp.close()
# Read the ZIP archive
zipfp = zipfile.ZipFile(f, "r", compression)
for num in range(filecount):
self.assertEqual(zipfp.read("testfn%d" % num), self.data)
# Print still working message since this test can be really slow
if next_time <= time.time():
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
print >>sys.__stdout__, (
' zipTest still reading %d of %d, be patient...' %
(num, filecount))
sys.__stdout__.flush()
zipfp.close()
def testStored(self):
# Try the temp file first. If we do TESTFN2 first, then it hogs
# gigabytes of disk space for the duration of the test.
for f in TemporaryFile(), TESTFN2:
self.zipTest(f, zipfile.ZIP_STORED)
if zlib:
def testDeflated(self):
# Try the temp file first. If we do TESTFN2 first, then it hogs
# gigabytes of disk space for the duration of the test.
for f in TemporaryFile(), TESTFN2:
self.zipTest(f, zipfile.ZIP_DEFLATED)
def tearDown(self):
for fname in TESTFN, TESTFN2:
if os.path.exists(fname):
os.remove(fname)
class OtherTests(unittest.TestCase):
def testMoreThan64kFiles(self):
# This test checks that more than 64k files can be added to an archive,
# and that the resulting archive can be read properly by ZipFile
zipf = zipfile.ZipFile(TESTFN, mode="w")
zipf.debug = 100
numfiles = (1 << 16) * 3/2
for i in xrange(numfiles):
zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
self.assertEqual(len(zipf.namelist()), numfiles)
zipf.close()
zipf2 = zipfile.ZipFile(TESTFN, mode="r")
self.assertEqual(len(zipf2.namelist()), numfiles)
for i in xrange(numfiles):
self.assertEqual(zipf2.read("foo%08d" % i), "%d" % (i**3 % 57))
zipf.close()
def tearDown(self):
test_support.unlink(TESTFN)
test_support.unlink(TESTFN2)
def test_main():
run_unittest(TestsWithSourceFile, OtherTests)
if __name__ == "__main__":
test_main()
|
nuuuboo/odoo | refs/heads/8.0 | addons/stock_account/wizard/stock_invoice_onshipping.py | 217 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
from openerp.tools.translate import _
JOURNAL_TYPE_MAP = {
('outgoing', 'customer'): ['sale'],
('outgoing', 'supplier'): ['purchase_refund'],
('outgoing', 'transit'): ['sale', 'purchase_refund'],
('incoming', 'supplier'): ['purchase'],
('incoming', 'customer'): ['sale_refund'],
('incoming', 'transit'): ['purchase', 'sale_refund'],
}
class stock_invoice_onshipping(osv.osv_memory):
def _get_journal(self, cr, uid, context=None):
journal_obj = self.pool.get('account.journal')
journal_type = self._get_journal_type(cr, uid, context=context)
journals = journal_obj.search(cr, uid, [('type', '=', journal_type)])
return journals and journals[0] or False
def _get_journal_type(self, cr, uid, context=None):
if context is None:
context = {}
res_ids = context and context.get('active_ids', [])
pick_obj = self.pool.get('stock.picking')
pickings = pick_obj.browse(cr, uid, res_ids, context=context)
pick = pickings and pickings[0]
if not pick or not pick.move_lines:
return 'sale'
type = pick.picking_type_id.code
usage = pick.move_lines[0].location_id.usage if type == 'incoming' else pick.move_lines[0].location_dest_id.usage
return JOURNAL_TYPE_MAP.get((type, usage), ['sale'])[0]
_name = "stock.invoice.onshipping"
_description = "Stock Invoice Onshipping"
_columns = {
'journal_id': fields.many2one('account.journal', 'Destination Journal', required=True),
'journal_type': fields.selection([('purchase_refund', 'Refund Purchase'), ('purchase', 'Create Supplier Invoice'),
('sale_refund', 'Refund Sale'), ('sale', 'Create Customer Invoice')], 'Journal Type', readonly=True),
'group': fields.boolean("Group by partner"),
'invoice_date': fields.date('Invoice Date'),
}
_defaults = {
'journal_type': _get_journal_type,
'journal_id' : _get_journal,
}
def onchange_journal_id(self, cr, uid, ids, journal_id, context=None):
if context is None:
context = {}
domain = {}
value = {}
active_id = context.get('active_id')
if active_id:
picking = self.pool['stock.picking'].browse(cr, uid, active_id, context=context)
type = picking.picking_type_id.code
usage = picking.move_lines[0].location_id.usage if type == 'incoming' else picking.move_lines[0].location_dest_id.usage
journal_types = JOURNAL_TYPE_MAP.get((type, usage), ['sale', 'purchase', 'sale_refund', 'purchase_refund'])
domain['journal_id'] = [('type', 'in', journal_types)]
if journal_id:
journal = self.pool['account.journal'].browse(cr, uid, journal_id, context=context)
value['journal_type'] = journal.type
return {'value': value, 'domain': domain}
def view_init(self, cr, uid, fields_list, context=None):
if context is None:
context = {}
res = super(stock_invoice_onshipping, self).view_init(cr, uid, fields_list, context=context)
pick_obj = self.pool.get('stock.picking')
count = 0
active_ids = context.get('active_ids',[])
for pick in pick_obj.browse(cr, uid, active_ids, context=context):
if pick.invoice_state != '2binvoiced':
count += 1
if len(active_ids) == count:
raise osv.except_osv(_('Warning!'), _('None of these picking lists require invoicing.'))
return res
def open_invoice(self, cr, uid, ids, context=None):
if context is None:
context = {}
invoice_ids = self.create_invoice(cr, uid, ids, context=context)
if not invoice_ids:
raise osv.except_osv(_('Error!'), _('No invoice created!'))
data = self.browse(cr, uid, ids[0], context=context)
action_model = False
action = {}
journal2type = {'sale':'out_invoice', 'purchase':'in_invoice' , 'sale_refund':'out_refund', 'purchase_refund':'in_refund'}
inv_type = journal2type.get(data.journal_type) or 'out_invoice'
data_pool = self.pool.get('ir.model.data')
if inv_type == "out_invoice":
action_id = data_pool.xmlid_to_res_id(cr, uid, 'account.action_invoice_tree1')
elif inv_type == "in_invoice":
action_id = data_pool.xmlid_to_res_id(cr, uid, 'account.action_invoice_tree2')
elif inv_type == "out_refund":
action_id = data_pool.xmlid_to_res_id(cr, uid, 'account.action_invoice_tree3')
elif inv_type == "in_refund":
action_id = data_pool.xmlid_to_res_id(cr, uid, 'account.action_invoice_tree4')
if action_id:
action_pool = self.pool['ir.actions.act_window']
action = action_pool.read(cr, uid, action_id, context=context)
action['domain'] = "[('id','in', ["+','.join(map(str,invoice_ids))+"])]"
return action
return True
def create_invoice(self, cr, uid, ids, context=None):
context = dict(context or {})
picking_pool = self.pool.get('stock.picking')
data = self.browse(cr, uid, ids[0], context=context)
journal2type = {'sale':'out_invoice', 'purchase':'in_invoice', 'sale_refund':'out_refund', 'purchase_refund':'in_refund'}
context['date_inv'] = data.invoice_date
acc_journal = self.pool.get("account.journal")
inv_type = journal2type.get(data.journal_type) or 'out_invoice'
context['inv_type'] = inv_type
active_ids = context.get('active_ids', [])
res = picking_pool.action_invoice_create(cr, uid, active_ids,
journal_id = data.journal_id.id,
group = data.group,
type = inv_type,
context=context)
return res
|
grilo/ansible-1 | refs/heads/devel | lib/ansible/modules/cloud/openstack/os_zone.py | 19 | #!/usr/bin/python
# Copyright (c) 2016 Hewlett-Packard Enterprise
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: os_zone
short_description: Manage OpenStack DNS zones
extends_documentation_fragment: openstack
version_added: "2.2"
author: "Ricardo Carrillo Cruz (@rcarrillocruz)"
description:
- Manage OpenStack DNS zones. Zones can be created, deleted or
updated. Only the I(email), I(description), I(ttl) and I(masters) values
can be updated.
options:
name:
description:
- Zone name
required: true
zone_type:
description:
- Zone type
choices: [primary, secondary]
default: None
email:
description:
- Email of the zone owner (only applies if zone_type is primary)
required: false
description:
description:
- Zone description
required: false
default: None
ttl:
description:
- TTL (Time To Live) value in seconds
required: false
default: None
masters:
description:
- Master nameservers (only applies if zone_type is secondary)
required: false
default: None
state:
description:
- Should the resource be present or absent.
choices: [present, absent]
default: present
availability_zone:
description:
- Ignored. Present for backwards compatibility
required: false
requirements:
- "python >= 2.6"
- "shade"
'''
EXAMPLES = '''
# Create a zone named "example.net"
- os_zone:
cloud: mycloud
state: present
name: example.net.
zone_type: primary
email: test@example.net
description: Test zone
ttl: 3600
# Update the TTL on existing "example.net." zone
- os_zone:
cloud: mycloud
state: present
name: example.net.
ttl: 7200
# Delete zone named "example.net."
- os_zone:
cloud: mycloud
state: absent
name: example.net.
'''
RETURN = '''
zone:
description: Dictionary describing the zone.
returned: On success when I(state) is 'present'.
type: complex
contains:
id:
description: Unique zone ID
type: string
sample: "c1c530a3-3619-46f3-b0f6-236927b2618c"
name:
description: Zone name
type: string
sample: "example.net."
type:
description: Zone type
type: string
sample: "PRIMARY"
email:
description: Zone owner email
type: string
sample: "test@example.net"
description:
description: Zone description
type: string
sample: "Test description"
ttl:
description: Zone TTL value
type: int
sample: 3600
masters:
description: Zone master nameservers
type: list
sample: []
'''
try:
import shade
HAS_SHADE = True
except ImportError:
HAS_SHADE = False
from distutils.version import StrictVersion
def _system_state_change(state, email, description, ttl, masters, zone):
if state == 'present':
if not zone:
return True
if email is not None and zone.email != email:
return True
if description is not None and zone.description != description:
return True
if ttl is not None and zone.ttl != ttl:
return True
if masters is not None and zone.masters != masters:
return True
if state == 'absent' and zone:
return True
return False
def main():
argument_spec = openstack_full_argument_spec(
name=dict(required=True),
zone_type=dict(required=False, choice=['primary', 'secondary']),
email=dict(required=False, default=None),
description=dict(required=False, default=None),
ttl=dict(required=False, default=None, type='int'),
masters=dict(required=False, default=None, type='list'),
state=dict(default='present', choices=['absent', 'present']),
)
module_kwargs = openstack_module_kwargs()
module = AnsibleModule(argument_spec,
supports_check_mode=True,
**module_kwargs)
if not HAS_SHADE:
module.fail_json(msg='shade is required for this module')
if StrictVersion(shade.__version__) < StrictVersion('1.8.0'):
module.fail_json(msg="To utilize this module, the installed version of"
"the shade library MUST be >=1.8.0")
name = module.params.get('name')
state = module.params.get('state')
try:
cloud = shade.openstack_cloud(**module.params)
zone = cloud.get_zone(name)
if state == 'present':
zone_type = module.params.get('zone_type')
email = module.params.get('email')
description = module.params.get('description')
ttl = module.params.get('ttl')
masters = module.params.get('masters')
if module.check_mode:
module.exit_json(changed=_system_state_change(state, email,
description, ttl,
masters, zone))
if zone is None:
zone = cloud.create_zone(
name=name, zone_type=zone_type, email=email,
description=description, ttl=ttl, masters=masters)
changed = True
else:
if masters is None:
masters = []
pre_update_zone = zone
changed = _system_state_change(state, email,
description, ttl,
masters, pre_update_zone)
if changed:
zone = cloud.update_zone(
name, email=email,
description=description,
ttl=ttl, masters=masters)
module.exit_json(changed=changed, zone=zone)
elif state == 'absent':
if module.check_mode:
module.exit_json(changed=_system_state_change(state, None,
None, None,
None, zone))
if zone is None:
changed=False
else:
cloud.delete_zone(name)
changed=True
module.exit_json(changed=changed)
except shade.OpenStackCloudException as e:
module.fail_json(msg=str(e))
from ansible.module_utils.basic import *
from ansible.module_utils.openstack import *
if __name__ == '__main__':
main()
|
kvnn/btcimg | refs/heads/master | btcimg/settings/dev_sample.py | 1 | from .base import *
DEBUG = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'btc51w-&=!oukvwe36vii9p-m11hs#vqgx$w(##8j7%xoj!sy)dv+img'
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = ["*"]
INSTALLED_APPS = globals().get('INSTALLED_APPS', [])
INSTALLED_APPS += (
'debug_toolbar',
)
|
eunchong/build | refs/heads/master | third_party/buildbot_8_4p1/buildbot/util/monkeypatches.py | 4 | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import sys
import twisted
from twisted.trial import unittest
def add_debugging_monkeypatches():
"""
DO NOT CALL THIS DIRECTLY
This adds a few "harmless" monkeypatches which make it easier to debug
failing tests. It is called automatically by buildbot.test.__init__.
"""
from twisted.application.service import Service
old_startService = Service.startService
old_stopService = Service.stopService
def startService(self):
assert not self.running
return old_startService(self)
def stopService(self):
assert self.running
return old_stopService(self)
Service.startService = startService
Service.stopService = stopService
# versions of Twisted before 9.0.0 did not have a UnitTest.patch that worked
# on Python-2.7
if twisted.version.major <= 9 and sys.version_info[:2] == (2,7):
def nopatch(self, *args):
raise unittest.SkipTest('unittest.TestCase.patch is not available')
unittest.TestCase.patch = nopatch
|
dcalacci/Interactive_estimation | refs/heads/video | docs/__init__.py | 887 | # Included so that Django's startproject comment runs against the docs directory
|
hexxter/home-assistant | refs/heads/dev | homeassistant/components/lock/zwave.py | 14 | """
Zwave platform that handles simple door locks.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/lock.zwave/
"""
# Because we do not compile openzwave on CI
# pylint: disable=import-error
from homeassistant.components.lock import DOMAIN, LockDevice
from homeassistant.components import zwave
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Find and return Z-Wave switches."""
if discovery_info is None or zwave.NETWORK is None:
return
node = zwave.NETWORK.nodes[discovery_info[zwave.const.ATTR_NODE_ID]]
value = node.values[discovery_info[zwave.const.ATTR_VALUE_ID]]
if value.command_class != zwave.const.COMMAND_CLASS_DOOR_LOCK:
return
if value.type != zwave.const.TYPE_BOOL:
return
if value.genre != zwave.const.GENRE_USER:
return
value.set_change_verified(False)
add_devices([ZwaveLock(value)])
class ZwaveLock(zwave.ZWaveDeviceEntity, LockDevice):
"""Representation of a Z-Wave switch."""
def __init__(self, value):
"""Initialize the Z-Wave switch device."""
from openzwave.network import ZWaveNetwork
from pydispatch import dispatcher
zwave.ZWaveDeviceEntity.__init__(self, value, DOMAIN)
self._state = value.data
dispatcher.connect(
self._value_changed, ZWaveNetwork.SIGNAL_VALUE_CHANGED)
def _value_changed(self, value):
"""Called when a value has changed on the network."""
if self._value.value_id == value.value_id:
self._state = value.data
self.update_ha_state()
@property
def is_locked(self):
"""Return true if device is locked."""
return self._state
def lock(self, **kwargs):
"""Lock the device."""
self._value.data = True
def unlock(self, **kwargs):
"""Unlock the device."""
self._value.data = False
|
lnielsen/mytest | refs/heads/master | tests/api/conftest.py | 1 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2019 CERN.
#
# My site is free software; you can redistribute it and/or modify it under
# the terms of the MIT License; see LICENSE file for more details.
"""Pytest fixtures and plugins for the API application."""
from __future__ import absolute_import, print_function
import pytest
from invenio_app.factory import create_api
@pytest.fixture(scope='module')
def create_app():
"""Create test app."""
return create_api
|
kustomzone/Fuzium | refs/heads/master | bin/core/src/lib/rsa/varblock.py | 216 | # -*- coding: utf-8 -*-
#
# Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
#
# 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.
'''VARBLOCK file support
The VARBLOCK file format is as follows, where || denotes byte concatenation:
FILE := VERSION || BLOCK || BLOCK ...
BLOCK := LENGTH || DATA
LENGTH := varint-encoded length of the subsequent data. Varint comes from
Google Protobuf, and encodes an integer into a variable number of bytes.
Each byte uses the 7 lowest bits to encode the value. The highest bit set
to 1 indicates the next byte is also part of the varint. The last byte will
have this bit set to 0.
This file format is called the VARBLOCK format, in line with the varint format
used to denote the block sizes.
'''
from rsa._compat import byte, b
ZERO_BYTE = b('\x00')
VARBLOCK_VERSION = 1
def read_varint(infile):
'''Reads a varint from the file.
When the first byte to be read indicates EOF, (0, 0) is returned. When an
EOF occurs when at least one byte has been read, an EOFError exception is
raised.
@param infile: the file-like object to read from. It should have a read()
method.
@returns (varint, length), the read varint and the number of read bytes.
'''
varint = 0
read_bytes = 0
while True:
char = infile.read(1)
if len(char) == 0:
if read_bytes == 0:
return (0, 0)
raise EOFError('EOF while reading varint, value is %i so far' %
varint)
byte = ord(char)
varint += (byte & 0x7F) << (7 * read_bytes)
read_bytes += 1
if not byte & 0x80:
return (varint, read_bytes)
def write_varint(outfile, value):
'''Writes a varint to a file.
@param outfile: the file-like object to write to. It should have a write()
method.
@returns the number of written bytes.
'''
# there is a big difference between 'write the value 0' (this case) and
# 'there is nothing left to write' (the false-case of the while loop)
if value == 0:
outfile.write(ZERO_BYTE)
return 1
written_bytes = 0
while value > 0:
to_write = value & 0x7f
value = value >> 7
if value > 0:
to_write |= 0x80
outfile.write(byte(to_write))
written_bytes += 1
return written_bytes
def yield_varblocks(infile):
'''Generator, yields each block in the input file.
@param infile: file to read, is expected to have the VARBLOCK format as
described in the module's docstring.
@yields the contents of each block.
'''
# Check the version number
first_char = infile.read(1)
if len(first_char) == 0:
raise EOFError('Unable to read VARBLOCK version number')
version = ord(first_char)
if version != VARBLOCK_VERSION:
raise ValueError('VARBLOCK version %i not supported' % version)
while True:
(block_size, read_bytes) = read_varint(infile)
# EOF at block boundary, that's fine.
if read_bytes == 0 and block_size == 0:
break
block = infile.read(block_size)
read_size = len(block)
if read_size != block_size:
raise EOFError('Block size is %i, but could read only %i bytes' %
(block_size, read_size))
yield block
def yield_fixedblocks(infile, blocksize):
'''Generator, yields each block of ``blocksize`` bytes in the input file.
:param infile: file to read and separate in blocks.
:returns: a generator that yields the contents of each block
'''
while True:
block = infile.read(blocksize)
read_bytes = len(block)
if read_bytes == 0:
break
yield block
if read_bytes < blocksize:
break
|
JT5D/Alfred-Popclip-Sublime | refs/heads/master | Sublime Text 2/SideBarGit/sidebar/SideBarSelection.py | 6 | # coding=utf8
import sublime
import os
import re
from SideBarProject import SideBarProject
from SideBarItem import SideBarItem
class SideBarSelection:
def __init__(self, paths = []):
if len(paths) < 1:
try:
path = sublime.active_window().active_view().file_name()
if self.isNone(path):
paths = []
else:
paths = [path]
except:
paths = []
self._paths = paths
self._paths.sort()
self._obtained_selection_information_basic = False
self._obtained_selection_information_extended = False
def len(self):
return len(self._paths)
def hasDirectories(self):
self._obtainSelectionInformationBasic()
return self._has_directories
def hasFiles(self):
self._obtainSelectionInformationBasic()
return self._has_files
def hasOnlyDirectories(self):
self._obtainSelectionInformationBasic()
return self._only_directories
def hasOnlyFiles(self):
self._obtainSelectionInformationBasic()
return self._only_files
def hasProjectDirectories(self):
if self.hasDirectories():
project_directories = SideBarProject().getDirectories()
for item in self.getSelectedDirectories():
if item.path() in project_directories:
return True
return False
else:
return False
def hasItemsUnderProject(self):
for item in self.getSelectedItems():
if item.isUnderCurrentProject():
return True
return False
def hasImages(self):
return self.hasFilesWithExtension('gif|jpg|jpeg|png')
def hasFilesWithExtension(self, extensions):
extensions = re.compile('('+extensions+')$', re.I);
for item in self.getSelectedFiles():
if extensions.search(item.path()):
return True;
return False
def getSelectedItems(self):
self._obtainSelectionInformationExtended()
return self._files + self._directories;
def getSelectedItemsWithoutChildItems(self):
self._obtainSelectionInformationExtended()
items = []
for item in self._items_without_containing_child_items:
items.append(SideBarItem(item, os.path.isdir(item)))
return items
def getSelectedDirectories(self):
self._obtainSelectionInformationExtended()
return self._directories;
def getSelectedFiles(self):
self._obtainSelectionInformationExtended()
return self._files;
def getSelectedDirectoriesOrDirnames(self):
self._obtainSelectionInformationExtended()
return self._directories_or_dirnames;
def getSelectedImages(self):
return self.getSelectedFilesWithExtension('gif|jpg|jpeg|png')
def getSelectedFilesWithExtension(self, extensions):
items = []
extensions = re.compile('('+extensions+')$', re.I);
for item in self.getSelectedFiles():
if extensions.search(item.path()):
items.append(item)
return items
def _obtainSelectionInformationBasic(self):
if not self._obtained_selection_information_basic:
self._obtained_selection_information_basic = True
self._has_directories = False
self._has_files = False
self._only_directories = False
self._only_files = False
for path in self._paths:
if self._has_directories == False and os.path.isdir(path):
self._has_directories = True
if self._has_files == False and os.path.isdir(path) == False:
self._has_files = True
if self._has_files and self._has_directories:
break
if self._has_files and self._has_directories:
self._only_directories = False
self._only_files = False
elif self._has_files:
self._only_files = True
elif self._has_directories:
self._only_directories = True
def _obtainSelectionInformationExtended(self):
if not self._obtained_selection_information_extended:
self._obtained_selection_information_extended = True
self._directories = []
self._files = []
self._directories_or_dirnames = []
self._items_without_containing_child_items = []
_directories = []
_files = []
_directories_or_dirnames = []
_items_without_containing_child_items = []
for path in self._paths:
if os.path.isdir(path):
item = SideBarItem(path, True)
if item.path() not in _directories:
_directories.append(item.path())
self._directories.append(item)
if item.path() not in _directories_or_dirnames:
_directories_or_dirnames.append(item.path())
self._directories_or_dirnames.append(item)
_items_without_containing_child_items = self._itemsWithoutContainingChildItems(_items_without_containing_child_items, item.path())
else:
item = SideBarItem(path, False)
if item.path() not in _files:
_files.append(item.path())
self._files.append(item)
_items_without_containing_child_items = self._itemsWithoutContainingChildItems(_items_without_containing_child_items, item.path())
item = SideBarItem(os.path.dirname(path), True)
if item.path() not in _directories_or_dirnames:
_directories_or_dirnames.append(item.path())
self._directories_or_dirnames.append(item)
self._items_without_containing_child_items = _items_without_containing_child_items
def _itemsWithoutContainingChildItems(self, items, item):
new_list = []
add = True
for i in items:
if i.find(item+'\\') == 0 or i.find(item+'/') == 0:
continue
else:
new_list.append(i)
if (item+'\\').find(i+'\\') == 0 or (item+'/').find(i+'/') == 0:
add = False
if add:
new_list.append(item)
return new_list
def isNone(self, path):
if path == None or path == '' or path == '.' or path == '..' or path == './' or path == '/' or path == '//' or path == '\\' or path == '\\\\' or path == '\\\\\\\\':
return True
else:
return False
|
Bang3DEngine/Bang | refs/heads/master | Compile/CompileDependencies/ThirdParty/assimp/contrib/gtest/test/gtest_output_test.py | 363 | #!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Tests the text output of Google C++ Testing Framework.
SYNOPSIS
gtest_output_test.py --build_dir=BUILD/DIR --gengolden
# where BUILD/DIR contains the built gtest_output_test_ file.
gtest_output_test.py --gengolden
gtest_output_test.py
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
import difflib
import os
import re
import sys
import gtest_test_utils
# The flag for generating the golden file
GENGOLDEN_FLAG = '--gengolden'
CATCH_EXCEPTIONS_ENV_VAR_NAME = 'GTEST_CATCH_EXCEPTIONS'
IS_WINDOWS = os.name == 'nt'
# TODO(vladl@google.com): remove the _lin suffix.
GOLDEN_NAME = 'gtest_output_test_golden_lin.txt'
PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_output_test_')
# At least one command we exercise must not have the
# 'internal_skip_environment_and_ad_hoc_tests' argument.
COMMAND_LIST_TESTS = ({}, [PROGRAM_PATH, '--gtest_list_tests'])
COMMAND_WITH_COLOR = ({}, [PROGRAM_PATH, '--gtest_color=yes'])
COMMAND_WITH_TIME = ({}, [PROGRAM_PATH,
'--gtest_print_time',
'internal_skip_environment_and_ad_hoc_tests',
'--gtest_filter=FatalFailureTest.*:LoggingTest.*'])
COMMAND_WITH_DISABLED = (
{}, [PROGRAM_PATH,
'--gtest_also_run_disabled_tests',
'internal_skip_environment_and_ad_hoc_tests',
'--gtest_filter=*DISABLED_*'])
COMMAND_WITH_SHARDING = (
{'GTEST_SHARD_INDEX': '1', 'GTEST_TOTAL_SHARDS': '2'},
[PROGRAM_PATH,
'internal_skip_environment_and_ad_hoc_tests',
'--gtest_filter=PassingTest.*'])
GOLDEN_PATH = os.path.join(gtest_test_utils.GetSourceDir(), GOLDEN_NAME)
def ToUnixLineEnding(s):
"""Changes all Windows/Mac line endings in s to UNIX line endings."""
return s.replace('\r\n', '\n').replace('\r', '\n')
def RemoveLocations(test_output):
"""Removes all file location info from a Google Test program's output.
Args:
test_output: the output of a Google Test program.
Returns:
output with all file location info (in the form of
'DIRECTORY/FILE_NAME:LINE_NUMBER: 'or
'DIRECTORY\\FILE_NAME(LINE_NUMBER): ') replaced by
'FILE_NAME:#: '.
"""
return re.sub(r'.*[/\\](.+)(\:\d+|\(\d+\))\: ', r'\1:#: ', test_output)
def RemoveStackTraceDetails(output):
"""Removes all stack traces from a Google Test program's output."""
# *? means "find the shortest string that matches".
return re.sub(r'Stack trace:(.|\n)*?\n\n',
'Stack trace: (omitted)\n\n', output)
def RemoveStackTraces(output):
"""Removes all traces of stack traces from a Google Test program's output."""
# *? means "find the shortest string that matches".
return re.sub(r'Stack trace:(.|\n)*?\n\n', '', output)
def RemoveTime(output):
"""Removes all time information from a Google Test program's output."""
return re.sub(r'\(\d+ ms', '(? ms', output)
def RemoveTypeInfoDetails(test_output):
"""Removes compiler-specific type info from Google Test program's output.
Args:
test_output: the output of a Google Test program.
Returns:
output with type information normalized to canonical form.
"""
# some compilers output the name of type 'unsigned int' as 'unsigned'
return re.sub(r'unsigned int', 'unsigned', test_output)
def NormalizeToCurrentPlatform(test_output):
"""Normalizes platform specific output details for easier comparison."""
if IS_WINDOWS:
# Removes the color information that is not present on Windows.
test_output = re.sub('\x1b\\[(0;3\d)?m', '', test_output)
# Changes failure message headers into the Windows format.
test_output = re.sub(r': Failure\n', r': error: ', test_output)
# Changes file(line_number) to file:line_number.
test_output = re.sub(r'((\w|\.)+)\((\d+)\):', r'\1:\3:', test_output)
return test_output
def RemoveTestCounts(output):
"""Removes test counts from a Google Test program's output."""
output = re.sub(r'\d+ tests?, listed below',
'? tests, listed below', output)
output = re.sub(r'\d+ FAILED TESTS',
'? FAILED TESTS', output)
output = re.sub(r'\d+ tests? from \d+ test cases?',
'? tests from ? test cases', output)
output = re.sub(r'\d+ tests? from ([a-zA-Z_])',
r'? tests from \1', output)
return re.sub(r'\d+ tests?\.', '? tests.', output)
def RemoveMatchingTests(test_output, pattern):
"""Removes output of specified tests from a Google Test program's output.
This function strips not only the beginning and the end of a test but also
all output in between.
Args:
test_output: A string containing the test output.
pattern: A regex string that matches names of test cases or
tests to remove.
Returns:
Contents of test_output with tests whose names match pattern removed.
"""
test_output = re.sub(
r'.*\[ RUN \] .*%s(.|\n)*?\[( FAILED | OK )\] .*%s.*\n' % (
pattern, pattern),
'',
test_output)
return re.sub(r'.*%s.*\n' % pattern, '', test_output)
def NormalizeOutput(output):
"""Normalizes output (the output of gtest_output_test_.exe)."""
output = ToUnixLineEnding(output)
output = RemoveLocations(output)
output = RemoveStackTraceDetails(output)
output = RemoveTime(output)
return output
def GetShellCommandOutput(env_cmd):
"""Runs a command in a sub-process, and returns its output in a string.
Args:
env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra
environment variables to set, and element 1 is a string with
the command and any flags.
Returns:
A string with the command's combined standard and diagnostic output.
"""
# Spawns cmd in a sub-process, and gets its standard I/O file objects.
# Set and save the environment properly.
environ = os.environ.copy()
environ.update(env_cmd[0])
p = gtest_test_utils.Subprocess(env_cmd[1], env=environ)
return p.output
def GetCommandOutput(env_cmd):
"""Runs a command and returns its output with all file location
info stripped off.
Args:
env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra
environment variables to set, and element 1 is a string with
the command and any flags.
"""
# Disables exception pop-ups on Windows.
environ, cmdline = env_cmd
environ = dict(environ) # Ensures we are modifying a copy.
environ[CATCH_EXCEPTIONS_ENV_VAR_NAME] = '1'
return NormalizeOutput(GetShellCommandOutput((environ, cmdline)))
def GetOutputOfAllCommands():
"""Returns concatenated output from several representative commands."""
return (GetCommandOutput(COMMAND_WITH_COLOR) +
GetCommandOutput(COMMAND_WITH_TIME) +
GetCommandOutput(COMMAND_WITH_DISABLED) +
GetCommandOutput(COMMAND_WITH_SHARDING))
test_list = GetShellCommandOutput(COMMAND_LIST_TESTS)
SUPPORTS_DEATH_TESTS = 'DeathTest' in test_list
SUPPORTS_TYPED_TESTS = 'TypedTest' in test_list
SUPPORTS_THREADS = 'ExpectFailureWithThreadsTest' in test_list
SUPPORTS_STACK_TRACES = False
CAN_GENERATE_GOLDEN_FILE = (SUPPORTS_DEATH_TESTS and
SUPPORTS_TYPED_TESTS and
SUPPORTS_THREADS and
not IS_WINDOWS)
class GTestOutputTest(gtest_test_utils.TestCase):
def RemoveUnsupportedTests(self, test_output):
if not SUPPORTS_DEATH_TESTS:
test_output = RemoveMatchingTests(test_output, 'DeathTest')
if not SUPPORTS_TYPED_TESTS:
test_output = RemoveMatchingTests(test_output, 'TypedTest')
test_output = RemoveMatchingTests(test_output, 'TypedDeathTest')
test_output = RemoveMatchingTests(test_output, 'TypeParamDeathTest')
if not SUPPORTS_THREADS:
test_output = RemoveMatchingTests(test_output,
'ExpectFailureWithThreadsTest')
test_output = RemoveMatchingTests(test_output,
'ScopedFakeTestPartResultReporterTest')
test_output = RemoveMatchingTests(test_output,
'WorksConcurrently')
if not SUPPORTS_STACK_TRACES:
test_output = RemoveStackTraces(test_output)
return test_output
def testOutput(self):
output = GetOutputOfAllCommands()
golden_file = open(GOLDEN_PATH, 'r')
# A mis-configured source control system can cause \r appear in EOL
# sequences when we read the golden file irrespective of an operating
# system used. Therefore, we need to strip those \r's from newlines
# unconditionally.
golden = ToUnixLineEnding(golden_file.read())
golden_file.close()
# We want the test to pass regardless of certain features being
# supported or not.
# We still have to remove type name specifics in all cases.
normalized_actual = RemoveTypeInfoDetails(output)
normalized_golden = RemoveTypeInfoDetails(golden)
if CAN_GENERATE_GOLDEN_FILE:
self.assertEqual(normalized_golden, normalized_actual,
'\n'.join(difflib.unified_diff(
normalized_golden.split('\n'),
normalized_actual.split('\n'),
'golden', 'actual')))
else:
normalized_actual = NormalizeToCurrentPlatform(
RemoveTestCounts(normalized_actual))
normalized_golden = NormalizeToCurrentPlatform(
RemoveTestCounts(self.RemoveUnsupportedTests(normalized_golden)))
# This code is very handy when debugging golden file differences:
if os.getenv('DEBUG_GTEST_OUTPUT_TEST'):
open(os.path.join(
gtest_test_utils.GetSourceDir(),
'_gtest_output_test_normalized_actual.txt'), 'wb').write(
normalized_actual)
open(os.path.join(
gtest_test_utils.GetSourceDir(),
'_gtest_output_test_normalized_golden.txt'), 'wb').write(
normalized_golden)
self.assertEqual(normalized_golden, normalized_actual)
if __name__ == '__main__':
if sys.argv[1:] == [GENGOLDEN_FLAG]:
if CAN_GENERATE_GOLDEN_FILE:
output = GetOutputOfAllCommands()
golden_file = open(GOLDEN_PATH, 'wb')
golden_file.write(output)
golden_file.close()
else:
message = (
"""Unable to write a golden file when compiled in an environment
that does not support all the required features (death tests, typed tests,
and multiple threads). Please generate the golden file using a binary built
with those features enabled.""")
sys.stderr.write(message)
sys.exit(1)
else:
gtest_test_utils.Main()
|
chiamingyen/pygroup_sqlite | refs/heads/master | wsgi/static/Brython2.1.4-20140810-083054/Lib/logging/handlers.py | 736 | # Copyright 2001-2013 by Vinay Sajip. All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this permission notice appear in
# supporting documentation, and that the name of Vinay Sajip
# not be used in advertising or publicity pertaining to distribution
# of the software without specific, written prior permission.
# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""
Additional handlers for the logging package for Python. The core package is
based on PEP 282 and comments thereto in comp.lang.python.
Copyright (C) 2001-2013 Vinay Sajip. All Rights Reserved.
To use, simply 'import logging.handlers' and log away!
"""
import errno, logging, socket, os, pickle, struct, time, re
from codecs import BOM_UTF8
from stat import ST_DEV, ST_INO, ST_MTIME
import queue
try:
import threading
except ImportError: #pragma: no cover
threading = None
#
# Some constants...
#
DEFAULT_TCP_LOGGING_PORT = 9020
DEFAULT_UDP_LOGGING_PORT = 9021
DEFAULT_HTTP_LOGGING_PORT = 9022
DEFAULT_SOAP_LOGGING_PORT = 9023
SYSLOG_UDP_PORT = 514
SYSLOG_TCP_PORT = 514
_MIDNIGHT = 24 * 60 * 60 # number of seconds in a day
class BaseRotatingHandler(logging.FileHandler):
"""
Base class for handlers that rotate log files at a certain point.
Not meant to be instantiated directly. Instead, use RotatingFileHandler
or TimedRotatingFileHandler.
"""
def __init__(self, filename, mode, encoding=None, delay=False):
"""
Use the specified filename for streamed logging
"""
logging.FileHandler.__init__(self, filename, mode, encoding, delay)
self.mode = mode
self.encoding = encoding
self.namer = None
self.rotator = None
def emit(self, record):
"""
Emit a record.
Output the record to the file, catering for rollover as described
in doRollover().
"""
try:
if self.shouldRollover(record):
self.doRollover()
logging.FileHandler.emit(self, record)
except (KeyboardInterrupt, SystemExit): #pragma: no cover
raise
except:
self.handleError(record)
def rotation_filename(self, default_name):
"""
Modify the filename of a log file when rotating.
This is provided so that a custom filename can be provided.
The default implementation calls the 'namer' attribute of the
handler, if it's callable, passing the default name to
it. If the attribute isn't callable (the default is None), the name
is returned unchanged.
:param default_name: The default name for the log file.
"""
if not callable(self.namer):
result = default_name
else:
result = self.namer(default_name)
return result
def rotate(self, source, dest):
"""
When rotating, rotate the current log.
The default implementation calls the 'rotator' attribute of the
handler, if it's callable, passing the source and dest arguments to
it. If the attribute isn't callable (the default is None), the source
is simply renamed to the destination.
:param source: The source filename. This is normally the base
filename, e.g. 'test.log'
:param dest: The destination filename. This is normally
what the source is rotated to, e.g. 'test.log.1'.
"""
if not callable(self.rotator):
# Issue 18940: A file may not have been created if delay is True.
if os.path.exists(source):
os.rename(source, dest)
else:
self.rotator(source, dest)
class RotatingFileHandler(BaseRotatingHandler):
"""
Handler for logging to a set of files, which switches from one file
to the next when the current file reaches a certain size.
"""
def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False):
"""
Open the specified file and use it as the stream for logging.
By default, the file grows indefinitely. You can specify particular
values of maxBytes and backupCount to allow the file to rollover at
a predetermined size.
Rollover occurs whenever the current log file is nearly maxBytes in
length. If backupCount is >= 1, the system will successively create
new files with the same pathname as the base file, but with extensions
".1", ".2" etc. appended to it. For example, with a backupCount of 5
and a base file name of "app.log", you would get "app.log",
"app.log.1", "app.log.2", ... through to "app.log.5". The file being
written to is always "app.log" - when it gets filled up, it is closed
and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc.
exist, then they are renamed to "app.log.2", "app.log.3" etc.
respectively.
If maxBytes is zero, rollover never occurs.
"""
# If rotation/rollover is wanted, it doesn't make sense to use another
# mode. If for example 'w' were specified, then if there were multiple
# runs of the calling application, the logs from previous runs would be
# lost if the 'w' is respected, because the log file would be truncated
# on each run.
if maxBytes > 0:
mode = 'a'
BaseRotatingHandler.__init__(self, filename, mode, encoding, delay)
self.maxBytes = maxBytes
self.backupCount = backupCount
def doRollover(self):
"""
Do a rollover, as described in __init__().
"""
if self.stream:
self.stream.close()
self.stream = None
if self.backupCount > 0:
for i in range(self.backupCount - 1, 0, -1):
sfn = self.rotation_filename("%s.%d" % (self.baseFilename, i))
dfn = self.rotation_filename("%s.%d" % (self.baseFilename,
i + 1))
if os.path.exists(sfn):
if os.path.exists(dfn):
os.remove(dfn)
os.rename(sfn, dfn)
dfn = self.rotation_filename(self.baseFilename + ".1")
if os.path.exists(dfn):
os.remove(dfn)
self.rotate(self.baseFilename, dfn)
if not self.delay:
self.stream = self._open()
def shouldRollover(self, record):
"""
Determine if rollover should occur.
Basically, see if the supplied record would cause the file to exceed
the size limit we have.
"""
if self.stream is None: # delay was set...
self.stream = self._open()
if self.maxBytes > 0: # are we rolling over?
msg = "%s\n" % self.format(record)
self.stream.seek(0, 2) #due to non-posix-compliant Windows feature
if self.stream.tell() + len(msg) >= self.maxBytes:
return 1
return 0
class TimedRotatingFileHandler(BaseRotatingHandler):
"""
Handler for logging to a file, rotating the log file at certain timed
intervals.
If backupCount is > 0, when rollover is done, no more than backupCount
files are kept - the oldest ones are deleted.
"""
def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False):
BaseRotatingHandler.__init__(self, filename, 'a', encoding, delay)
self.when = when.upper()
self.backupCount = backupCount
self.utc = utc
# Calculate the real rollover interval, which is just the number of
# seconds between rollovers. Also set the filename suffix used when
# a rollover occurs. Current 'when' events supported:
# S - Seconds
# M - Minutes
# H - Hours
# D - Days
# midnight - roll over at midnight
# W{0-6} - roll over on a certain day; 0 - Monday
#
# Case of the 'when' specifier is not important; lower or upper case
# will work.
if self.when == 'S':
self.interval = 1 # one second
self.suffix = "%Y-%m-%d_%H-%M-%S"
self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}(\.\w+)?$"
elif self.when == 'M':
self.interval = 60 # one minute
self.suffix = "%Y-%m-%d_%H-%M"
self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}(\.\w+)?$"
elif self.when == 'H':
self.interval = 60 * 60 # one hour
self.suffix = "%Y-%m-%d_%H"
self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}(\.\w+)?$"
elif self.when == 'D' or self.when == 'MIDNIGHT':
self.interval = 60 * 60 * 24 # one day
self.suffix = "%Y-%m-%d"
self.extMatch = r"^\d{4}-\d{2}-\d{2}(\.\w+)?$"
elif self.when.startswith('W'):
self.interval = 60 * 60 * 24 * 7 # one week
if len(self.when) != 2:
raise ValueError("You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s" % self.when)
if self.when[1] < '0' or self.when[1] > '6':
raise ValueError("Invalid day specified for weekly rollover: %s" % self.when)
self.dayOfWeek = int(self.when[1])
self.suffix = "%Y-%m-%d"
self.extMatch = r"^\d{4}-\d{2}-\d{2}(\.\w+)?$"
else:
raise ValueError("Invalid rollover interval specified: %s" % self.when)
self.extMatch = re.compile(self.extMatch, re.ASCII)
self.interval = self.interval * interval # multiply by units requested
if os.path.exists(filename):
t = os.stat(filename)[ST_MTIME]
else:
t = int(time.time())
self.rolloverAt = self.computeRollover(t)
def computeRollover(self, currentTime):
"""
Work out the rollover time based on the specified time.
"""
result = currentTime + self.interval
# If we are rolling over at midnight or weekly, then the interval is already known.
# What we need to figure out is WHEN the next interval is. In other words,
# if you are rolling over at midnight, then your base interval is 1 day,
# but you want to start that one day clock at midnight, not now. So, we
# have to fudge the rolloverAt value in order to trigger the first rollover
# at the right time. After that, the regular interval will take care of
# the rest. Note that this code doesn't care about leap seconds. :)
if self.when == 'MIDNIGHT' or self.when.startswith('W'):
# This could be done with less code, but I wanted it to be clear
if self.utc:
t = time.gmtime(currentTime)
else:
t = time.localtime(currentTime)
currentHour = t[3]
currentMinute = t[4]
currentSecond = t[5]
# r is the number of seconds left between now and midnight
r = _MIDNIGHT - ((currentHour * 60 + currentMinute) * 60 +
currentSecond)
result = currentTime + r
# If we are rolling over on a certain day, add in the number of days until
# the next rollover, but offset by 1 since we just calculated the time
# until the next day starts. There are three cases:
# Case 1) The day to rollover is today; in this case, do nothing
# Case 2) The day to rollover is further in the interval (i.e., today is
# day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to
# next rollover is simply 6 - 2 - 1, or 3.
# Case 3) The day to rollover is behind us in the interval (i.e., today
# is day 5 (Saturday) and rollover is on day 3 (Thursday).
# Days to rollover is 6 - 5 + 3, or 4. In this case, it's the
# number of days left in the current week (1) plus the number
# of days in the next week until the rollover day (3).
# The calculations described in 2) and 3) above need to have a day added.
# This is because the above time calculation takes us to midnight on this
# day, i.e. the start of the next day.
if self.when.startswith('W'):
day = t[6] # 0 is Monday
if day != self.dayOfWeek:
if day < self.dayOfWeek:
daysToWait = self.dayOfWeek - day
else:
daysToWait = 6 - day + self.dayOfWeek + 1
newRolloverAt = result + (daysToWait * (60 * 60 * 24))
if not self.utc:
dstNow = t[-1]
dstAtRollover = time.localtime(newRolloverAt)[-1]
if dstNow != dstAtRollover:
if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
addend = -3600
else: # DST bows out before next rollover, so we need to add an hour
addend = 3600
newRolloverAt += addend
result = newRolloverAt
return result
def shouldRollover(self, record):
"""
Determine if rollover should occur.
record is not used, as we are just comparing times, but it is needed so
the method signatures are the same
"""
t = int(time.time())
if t >= self.rolloverAt:
return 1
return 0
def getFilesToDelete(self):
"""
Determine the files to delete when rolling over.
More specific than the earlier method, which just used glob.glob().
"""
dirName, baseName = os.path.split(self.baseFilename)
fileNames = os.listdir(dirName)
result = []
prefix = baseName + "."
plen = len(prefix)
for fileName in fileNames:
if fileName[:plen] == prefix:
suffix = fileName[plen:]
if self.extMatch.match(suffix):
result.append(os.path.join(dirName, fileName))
result.sort()
if len(result) < self.backupCount:
result = []
else:
result = result[:len(result) - self.backupCount]
return result
def doRollover(self):
"""
do a rollover; in this case, a date/time stamp is appended to the filename
when the rollover happens. However, you want the file to be named for the
start of the interval, not the current time. If there is a backup count,
then we have to get a list of matching filenames, sort them and remove
the one with the oldest suffix.
"""
if self.stream:
self.stream.close()
self.stream = None
# get the time that this sequence started at and make it a TimeTuple
currentTime = int(time.time())
dstNow = time.localtime(currentTime)[-1]
t = self.rolloverAt - self.interval
if self.utc:
timeTuple = time.gmtime(t)
else:
timeTuple = time.localtime(t)
dstThen = timeTuple[-1]
if dstNow != dstThen:
if dstNow:
addend = 3600
else:
addend = -3600
timeTuple = time.localtime(t + addend)
dfn = self.rotation_filename(self.baseFilename + "." +
time.strftime(self.suffix, timeTuple))
if os.path.exists(dfn):
os.remove(dfn)
self.rotate(self.baseFilename, dfn)
if self.backupCount > 0:
for s in self.getFilesToDelete():
os.remove(s)
if not self.delay:
self.stream = self._open()
newRolloverAt = self.computeRollover(currentTime)
while newRolloverAt <= currentTime:
newRolloverAt = newRolloverAt + self.interval
#If DST changes and midnight or weekly rollover, adjust for this.
if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc:
dstAtRollover = time.localtime(newRolloverAt)[-1]
if dstNow != dstAtRollover:
if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
addend = -3600
else: # DST bows out before next rollover, so we need to add an hour
addend = 3600
newRolloverAt += addend
self.rolloverAt = newRolloverAt
class WatchedFileHandler(logging.FileHandler):
"""
A handler for logging to a file, which watches the file
to see if it has changed while in use. This can happen because of
usage of programs such as newsyslog and logrotate which perform
log file rotation. This handler, intended for use under Unix,
watches the file to see if it has changed since the last emit.
(A file has changed if its device or inode have changed.)
If it has changed, the old file stream is closed, and the file
opened to get a new stream.
This handler is not appropriate for use under Windows, because
under Windows open files cannot be moved or renamed - logging
opens the files with exclusive locks - and so there is no need
for such a handler. Furthermore, ST_INO is not supported under
Windows; stat always returns zero for this value.
This handler is based on a suggestion and patch by Chad J.
Schroeder.
"""
def __init__(self, filename, mode='a', encoding=None, delay=False):
logging.FileHandler.__init__(self, filename, mode, encoding, delay)
self.dev, self.ino = -1, -1
self._statstream()
def _statstream(self):
if self.stream:
sres = os.fstat(self.stream.fileno())
self.dev, self.ino = sres[ST_DEV], sres[ST_INO]
def emit(self, record):
"""
Emit a record.
First check if the underlying file has changed, and if it
has, close the old stream and reopen the file to get the
current stream.
"""
# Reduce the chance of race conditions by stat'ing by path only
# once and then fstat'ing our new fd if we opened a new log stream.
# See issue #14632: Thanks to John Mulligan for the problem report
# and patch.
try:
# stat the file by path, checking for existence
sres = os.stat(self.baseFilename)
except OSError as err:
if err.errno == errno.ENOENT:
sres = None
else:
raise
# compare file system stat with that of our stream file handle
if not sres or sres[ST_DEV] != self.dev or sres[ST_INO] != self.ino:
if self.stream is not None:
# we have an open file handle, clean it up
self.stream.flush()
self.stream.close()
# open a new file handle and get new stat info from that fd
self.stream = self._open()
self._statstream()
logging.FileHandler.emit(self, record)
class SocketHandler(logging.Handler):
"""
A handler class which writes logging records, in pickle format, to
a streaming socket. The socket is kept open across logging calls.
If the peer resets it, an attempt is made to reconnect on the next call.
The pickle which is sent is that of the LogRecord's attribute dictionary
(__dict__), so that the receiver does not need to have the logging module
installed in order to process the logging event.
To unpickle the record at the receiving end into a LogRecord, use the
makeLogRecord function.
"""
def __init__(self, host, port):
"""
Initializes the handler with a specific host address and port.
When the attribute *closeOnError* is set to True - if a socket error
occurs, the socket is silently closed and then reopened on the next
logging call.
"""
logging.Handler.__init__(self)
self.host = host
self.port = port
self.sock = None
self.closeOnError = False
self.retryTime = None
#
# Exponential backoff parameters.
#
self.retryStart = 1.0
self.retryMax = 30.0
self.retryFactor = 2.0
def makeSocket(self, timeout=1):
"""
A factory method which allows subclasses to define the precise
type of socket they want.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if hasattr(s, 'settimeout'):
s.settimeout(timeout)
try:
s.connect((self.host, self.port))
return s
except socket.error:
s.close()
raise
def createSocket(self):
"""
Try to create a socket, using an exponential backoff with
a max retry time. Thanks to Robert Olson for the original patch
(SF #815911) which has been slightly refactored.
"""
now = time.time()
# Either retryTime is None, in which case this
# is the first time back after a disconnect, or
# we've waited long enough.
if self.retryTime is None:
attempt = True
else:
attempt = (now >= self.retryTime)
if attempt:
try:
self.sock = self.makeSocket()
self.retryTime = None # next time, no delay before trying
except socket.error:
#Creation failed, so set the retry time and return.
if self.retryTime is None:
self.retryPeriod = self.retryStart
else:
self.retryPeriod = self.retryPeriod * self.retryFactor
if self.retryPeriod > self.retryMax:
self.retryPeriod = self.retryMax
self.retryTime = now + self.retryPeriod
def send(self, s):
"""
Send a pickled string to the socket.
This function allows for partial sends which can happen when the
network is busy.
"""
if self.sock is None:
self.createSocket()
#self.sock can be None either because we haven't reached the retry
#time yet, or because we have reached the retry time and retried,
#but are still unable to connect.
if self.sock:
try:
if hasattr(self.sock, "sendall"):
self.sock.sendall(s)
else: #pragma: no cover
sentsofar = 0
left = len(s)
while left > 0:
sent = self.sock.send(s[sentsofar:])
sentsofar = sentsofar + sent
left = left - sent
except socket.error: #pragma: no cover
self.sock.close()
self.sock = None # so we can call createSocket next time
def makePickle(self, record):
"""
Pickles the record in binary format with a length prefix, and
returns it ready for transmission across the socket.
"""
ei = record.exc_info
if ei:
# just to get traceback text into record.exc_text ...
dummy = self.format(record)
# See issue #14436: If msg or args are objects, they may not be
# available on the receiving end. So we convert the msg % args
# to a string, save it as msg and zap the args.
d = dict(record.__dict__)
d['msg'] = record.getMessage()
d['args'] = None
d['exc_info'] = None
s = pickle.dumps(d, 1)
slen = struct.pack(">L", len(s))
return slen + s
def handleError(self, record):
"""
Handle an error during logging.
An error has occurred during logging. Most likely cause -
connection lost. Close the socket so that we can retry on the
next event.
"""
if self.closeOnError and self.sock:
self.sock.close()
self.sock = None #try to reconnect next time
else:
logging.Handler.handleError(self, record)
def emit(self, record):
"""
Emit a record.
Pickles the record and writes it to the socket in binary format.
If there is an error with the socket, silently drop the packet.
If there was a problem with the socket, re-establishes the
socket.
"""
try:
s = self.makePickle(record)
self.send(s)
except (KeyboardInterrupt, SystemExit): #pragma: no cover
raise
except:
self.handleError(record)
def close(self):
"""
Closes the socket.
"""
self.acquire()
try:
if self.sock:
self.sock.close()
self.sock = None
logging.Handler.close(self)
finally:
self.release()
class DatagramHandler(SocketHandler):
"""
A handler class which writes logging records, in pickle format, to
a datagram socket. The pickle which is sent is that of the LogRecord's
attribute dictionary (__dict__), so that the receiver does not need to
have the logging module installed in order to process the logging event.
To unpickle the record at the receiving end into a LogRecord, use the
makeLogRecord function.
"""
def __init__(self, host, port):
"""
Initializes the handler with a specific host address and port.
"""
SocketHandler.__init__(self, host, port)
self.closeOnError = False
def makeSocket(self):
"""
The factory method of SocketHandler is here overridden to create
a UDP socket (SOCK_DGRAM).
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return s
def send(self, s):
"""
Send a pickled string to a socket.
This function no longer allows for partial sends which can happen
when the network is busy - UDP does not guarantee delivery and
can deliver packets out of sequence.
"""
if self.sock is None:
self.createSocket()
self.sock.sendto(s, (self.host, self.port))
class SysLogHandler(logging.Handler):
"""
A handler class which sends formatted logging records to a syslog
server. Based on Sam Rushing's syslog module:
http://www.nightmare.com/squirl/python-ext/misc/syslog.py
Contributed by Nicolas Untz (after which minor refactoring changes
have been made).
"""
# from <linux/sys/syslog.h>:
# ======================================================================
# priorities/facilities are encoded into a single 32-bit quantity, where
# the bottom 3 bits are the priority (0-7) and the top 28 bits are the
# facility (0-big number). Both the priorities and the facilities map
# roughly one-to-one to strings in the syslogd(8) source code. This
# mapping is included in this file.
#
# priorities (these are ordered)
LOG_EMERG = 0 # system is unusable
LOG_ALERT = 1 # action must be taken immediately
LOG_CRIT = 2 # critical conditions
LOG_ERR = 3 # error conditions
LOG_WARNING = 4 # warning conditions
LOG_NOTICE = 5 # normal but significant condition
LOG_INFO = 6 # informational
LOG_DEBUG = 7 # debug-level messages
# facility codes
LOG_KERN = 0 # kernel messages
LOG_USER = 1 # random user-level messages
LOG_MAIL = 2 # mail system
LOG_DAEMON = 3 # system daemons
LOG_AUTH = 4 # security/authorization messages
LOG_SYSLOG = 5 # messages generated internally by syslogd
LOG_LPR = 6 # line printer subsystem
LOG_NEWS = 7 # network news subsystem
LOG_UUCP = 8 # UUCP subsystem
LOG_CRON = 9 # clock daemon
LOG_AUTHPRIV = 10 # security/authorization messages (private)
LOG_FTP = 11 # FTP daemon
# other codes through 15 reserved for system use
LOG_LOCAL0 = 16 # reserved for local use
LOG_LOCAL1 = 17 # reserved for local use
LOG_LOCAL2 = 18 # reserved for local use
LOG_LOCAL3 = 19 # reserved for local use
LOG_LOCAL4 = 20 # reserved for local use
LOG_LOCAL5 = 21 # reserved for local use
LOG_LOCAL6 = 22 # reserved for local use
LOG_LOCAL7 = 23 # reserved for local use
priority_names = {
"alert": LOG_ALERT,
"crit": LOG_CRIT,
"critical": LOG_CRIT,
"debug": LOG_DEBUG,
"emerg": LOG_EMERG,
"err": LOG_ERR,
"error": LOG_ERR, # DEPRECATED
"info": LOG_INFO,
"notice": LOG_NOTICE,
"panic": LOG_EMERG, # DEPRECATED
"warn": LOG_WARNING, # DEPRECATED
"warning": LOG_WARNING,
}
facility_names = {
"auth": LOG_AUTH,
"authpriv": LOG_AUTHPRIV,
"cron": LOG_CRON,
"daemon": LOG_DAEMON,
"ftp": LOG_FTP,
"kern": LOG_KERN,
"lpr": LOG_LPR,
"mail": LOG_MAIL,
"news": LOG_NEWS,
"security": LOG_AUTH, # DEPRECATED
"syslog": LOG_SYSLOG,
"user": LOG_USER,
"uucp": LOG_UUCP,
"local0": LOG_LOCAL0,
"local1": LOG_LOCAL1,
"local2": LOG_LOCAL2,
"local3": LOG_LOCAL3,
"local4": LOG_LOCAL4,
"local5": LOG_LOCAL5,
"local6": LOG_LOCAL6,
"local7": LOG_LOCAL7,
}
#The map below appears to be trivially lowercasing the key. However,
#there's more to it than meets the eye - in some locales, lowercasing
#gives unexpected results. See SF #1524081: in the Turkish locale,
#"INFO".lower() != "info"
priority_map = {
"DEBUG" : "debug",
"INFO" : "info",
"WARNING" : "warning",
"ERROR" : "error",
"CRITICAL" : "critical"
}
def __init__(self, address=('localhost', SYSLOG_UDP_PORT),
facility=LOG_USER, socktype=None):
"""
Initialize a handler.
If address is specified as a string, a UNIX socket is used. To log to a
local syslogd, "SysLogHandler(address="/dev/log")" can be used.
If facility is not specified, LOG_USER is used.
"""
logging.Handler.__init__(self)
self.address = address
self.facility = facility
self.socktype = socktype
if isinstance(address, str):
self.unixsocket = True
self._connect_unixsocket(address)
else:
self.unixsocket = False
if socktype is None:
socktype = socket.SOCK_DGRAM
self.socket = socket.socket(socket.AF_INET, socktype)
if socktype == socket.SOCK_STREAM:
self.socket.connect(address)
self.socktype = socktype
self.formatter = None
def _connect_unixsocket(self, address):
use_socktype = self.socktype
if use_socktype is None:
use_socktype = socket.SOCK_DGRAM
self.socket = socket.socket(socket.AF_UNIX, use_socktype)
try:
self.socket.connect(address)
# it worked, so set self.socktype to the used type
self.socktype = use_socktype
except socket.error:
self.socket.close()
if self.socktype is not None:
# user didn't specify falling back, so fail
raise
use_socktype = socket.SOCK_STREAM
self.socket = socket.socket(socket.AF_UNIX, use_socktype)
try:
self.socket.connect(address)
# it worked, so set self.socktype to the used type
self.socktype = use_socktype
except socket.error:
self.socket.close()
raise
def encodePriority(self, facility, priority):
"""
Encode the facility and priority. You can pass in strings or
integers - if strings are passed, the facility_names and
priority_names mapping dictionaries are used to convert them to
integers.
"""
if isinstance(facility, str):
facility = self.facility_names[facility]
if isinstance(priority, str):
priority = self.priority_names[priority]
return (facility << 3) | priority
def close (self):
"""
Closes the socket.
"""
self.acquire()
try:
self.socket.close()
logging.Handler.close(self)
finally:
self.release()
def mapPriority(self, levelName):
"""
Map a logging level name to a key in the priority_names map.
This is useful in two scenarios: when custom levels are being
used, and in the case where you can't do a straightforward
mapping by lowercasing the logging level name because of locale-
specific issues (see SF #1524081).
"""
return self.priority_map.get(levelName, "warning")
ident = '' # prepended to all messages
append_nul = True # some old syslog daemons expect a NUL terminator
def emit(self, record):
"""
Emit a record.
The record is formatted, and then sent to the syslog server. If
exception information is present, it is NOT sent to the server.
"""
msg = self.format(record)
if self.ident:
msg = self.ident + msg
if self.append_nul:
msg += '\000'
"""
We need to convert record level to lowercase, maybe this will
change in the future.
"""
prio = '<%d>' % self.encodePriority(self.facility,
self.mapPriority(record.levelname))
prio = prio.encode('utf-8')
# Message is a string. Convert to bytes as required by RFC 5424
msg = msg.encode('utf-8')
msg = prio + msg
try:
if self.unixsocket:
try:
self.socket.send(msg)
except socket.error:
self.socket.close()
self._connect_unixsocket(self.address)
self.socket.send(msg)
elif self.socktype == socket.SOCK_DGRAM:
self.socket.sendto(msg, self.address)
else:
self.socket.sendall(msg)
except (KeyboardInterrupt, SystemExit): #pragma: no cover
raise
except:
self.handleError(record)
class SMTPHandler(logging.Handler):
"""
A handler class which sends an SMTP email for each logging event.
"""
def __init__(self, mailhost, fromaddr, toaddrs, subject,
credentials=None, secure=None, timeout=5.0):
"""
Initialize the handler.
Initialize the instance with the from and to addresses and subject
line of the email. To specify a non-standard SMTP port, use the
(host, port) tuple format for the mailhost argument. To specify
authentication credentials, supply a (username, password) tuple
for the credentials argument. To specify the use of a secure
protocol (TLS), pass in a tuple for the secure argument. This will
only be used when authentication credentials are supplied. The tuple
will be either an empty tuple, or a single-value tuple with the name
of a keyfile, or a 2-value tuple with the names of the keyfile and
certificate file. (This tuple is passed to the `starttls` method).
A timeout in seconds can be specified for the SMTP connection (the
default is one second).
"""
logging.Handler.__init__(self)
if isinstance(mailhost, tuple):
self.mailhost, self.mailport = mailhost
else:
self.mailhost, self.mailport = mailhost, None
if isinstance(credentials, tuple):
self.username, self.password = credentials
else:
self.username = None
self.fromaddr = fromaddr
if isinstance(toaddrs, str):
toaddrs = [toaddrs]
self.toaddrs = toaddrs
self.subject = subject
self.secure = secure
self.timeout = timeout
def getSubject(self, record):
"""
Determine the subject for the email.
If you want to specify a subject line which is record-dependent,
override this method.
"""
return self.subject
def emit(self, record):
"""
Emit a record.
Format the record and send it to the specified addressees.
"""
try:
import smtplib
from email.utils import formatdate
port = self.mailport
if not port:
port = smtplib.SMTP_PORT
smtp = smtplib.SMTP(self.mailhost, port, timeout=self.timeout)
msg = self.format(record)
msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
self.fromaddr,
",".join(self.toaddrs),
self.getSubject(record),
formatdate(), msg)
if self.username:
if self.secure is not None:
smtp.ehlo()
smtp.starttls(*self.secure)
smtp.ehlo()
smtp.login(self.username, self.password)
smtp.sendmail(self.fromaddr, self.toaddrs, msg)
smtp.quit()
except (KeyboardInterrupt, SystemExit): #pragma: no cover
raise
except:
self.handleError(record)
class NTEventLogHandler(logging.Handler):
"""
A handler class which sends events to the NT Event Log. Adds a
registry entry for the specified application name. If no dllname is
provided, win32service.pyd (which contains some basic message
placeholders) is used. Note that use of these placeholders will make
your event logs big, as the entire message source is held in the log.
If you want slimmer logs, you have to pass in the name of your own DLL
which contains the message definitions you want to use in the event log.
"""
def __init__(self, appname, dllname=None, logtype="Application"):
logging.Handler.__init__(self)
try:
import win32evtlogutil, win32evtlog
self.appname = appname
self._welu = win32evtlogutil
if not dllname:
dllname = os.path.split(self._welu.__file__)
dllname = os.path.split(dllname[0])
dllname = os.path.join(dllname[0], r'win32service.pyd')
self.dllname = dllname
self.logtype = logtype
self._welu.AddSourceToRegistry(appname, dllname, logtype)
self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE
self.typemap = {
logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE,
logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE,
logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE,
logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE,
logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE,
}
except ImportError:
print("The Python Win32 extensions for NT (service, event "\
"logging) appear not to be available.")
self._welu = None
def getMessageID(self, record):
"""
Return the message ID for the event record. If you are using your
own messages, you could do this by having the msg passed to the
logger being an ID rather than a formatting string. Then, in here,
you could use a dictionary lookup to get the message ID. This
version returns 1, which is the base message ID in win32service.pyd.
"""
return 1
def getEventCategory(self, record):
"""
Return the event category for the record.
Override this if you want to specify your own categories. This version
returns 0.
"""
return 0
def getEventType(self, record):
"""
Return the event type for the record.
Override this if you want to specify your own types. This version does
a mapping using the handler's typemap attribute, which is set up in
__init__() to a dictionary which contains mappings for DEBUG, INFO,
WARNING, ERROR and CRITICAL. If you are using your own levels you will
either need to override this method or place a suitable dictionary in
the handler's typemap attribute.
"""
return self.typemap.get(record.levelno, self.deftype)
def emit(self, record):
"""
Emit a record.
Determine the message ID, event category and event type. Then
log the message in the NT event log.
"""
if self._welu:
try:
id = self.getMessageID(record)
cat = self.getEventCategory(record)
type = self.getEventType(record)
msg = self.format(record)
self._welu.ReportEvent(self.appname, id, cat, type, [msg])
except (KeyboardInterrupt, SystemExit): #pragma: no cover
raise
except:
self.handleError(record)
def close(self):
"""
Clean up this handler.
You can remove the application name from the registry as a
source of event log entries. However, if you do this, you will
not be able to see the events as you intended in the Event Log
Viewer - it needs to be able to access the registry to get the
DLL name.
"""
#self._welu.RemoveSourceFromRegistry(self.appname, self.logtype)
logging.Handler.close(self)
class HTTPHandler(logging.Handler):
"""
A class which sends records to a Web server, using either GET or
POST semantics.
"""
def __init__(self, host, url, method="GET", secure=False, credentials=None):
"""
Initialize the instance with the host, the request URL, and the method
("GET" or "POST")
"""
logging.Handler.__init__(self)
method = method.upper()
if method not in ["GET", "POST"]:
raise ValueError("method must be GET or POST")
self.host = host
self.url = url
self.method = method
self.secure = secure
self.credentials = credentials
def mapLogRecord(self, record):
"""
Default implementation of mapping the log record into a dict
that is sent as the CGI data. Overwrite in your class.
Contributed by Franz Glasner.
"""
return record.__dict__
def emit(self, record):
"""
Emit a record.
Send the record to the Web server as a percent-encoded dictionary
"""
try:
import http.client, urllib.parse
host = self.host
if self.secure:
h = http.client.HTTPSConnection(host)
else:
h = http.client.HTTPConnection(host)
url = self.url
data = urllib.parse.urlencode(self.mapLogRecord(record))
if self.method == "GET":
if (url.find('?') >= 0):
sep = '&'
else:
sep = '?'
url = url + "%c%s" % (sep, data)
h.putrequest(self.method, url)
# support multiple hosts on one IP address...
# need to strip optional :port from host, if present
i = host.find(":")
if i >= 0:
host = host[:i]
h.putheader("Host", host)
if self.method == "POST":
h.putheader("Content-type",
"application/x-www-form-urlencoded")
h.putheader("Content-length", str(len(data)))
if self.credentials:
import base64
s = ('u%s:%s' % self.credentials).encode('utf-8')
s = 'Basic ' + base64.b64encode(s).strip()
h.putheader('Authorization', s)
h.endheaders()
if self.method == "POST":
h.send(data.encode('utf-8'))
h.getresponse() #can't do anything with the result
except (KeyboardInterrupt, SystemExit): #pragma: no cover
raise
except:
self.handleError(record)
class BufferingHandler(logging.Handler):
"""
A handler class which buffers logging records in memory. Whenever each
record is added to the buffer, a check is made to see if the buffer should
be flushed. If it should, then flush() is expected to do what's needed.
"""
def __init__(self, capacity):
"""
Initialize the handler with the buffer size.
"""
logging.Handler.__init__(self)
self.capacity = capacity
self.buffer = []
def shouldFlush(self, record):
"""
Should the handler flush its buffer?
Returns true if the buffer is up to capacity. This method can be
overridden to implement custom flushing strategies.
"""
return (len(self.buffer) >= self.capacity)
def emit(self, record):
"""
Emit a record.
Append the record. If shouldFlush() tells us to, call flush() to process
the buffer.
"""
self.buffer.append(record)
if self.shouldFlush(record):
self.flush()
def flush(self):
"""
Override to implement custom flushing behaviour.
This version just zaps the buffer to empty.
"""
self.acquire()
try:
self.buffer = []
finally:
self.release()
def close(self):
"""
Close the handler.
This version just flushes and chains to the parent class' close().
"""
self.flush()
logging.Handler.close(self)
class MemoryHandler(BufferingHandler):
"""
A handler class which buffers logging records in memory, periodically
flushing them to a target handler. Flushing occurs whenever the buffer
is full, or when an event of a certain severity or greater is seen.
"""
def __init__(self, capacity, flushLevel=logging.ERROR, target=None):
"""
Initialize the handler with the buffer size, the level at which
flushing should occur and an optional target.
Note that without a target being set either here or via setTarget(),
a MemoryHandler is no use to anyone!
"""
BufferingHandler.__init__(self, capacity)
self.flushLevel = flushLevel
self.target = target
def shouldFlush(self, record):
"""
Check for buffer full or a record at the flushLevel or higher.
"""
return (len(self.buffer) >= self.capacity) or \
(record.levelno >= self.flushLevel)
def setTarget(self, target):
"""
Set the target handler for this handler.
"""
self.target = target
def flush(self):
"""
For a MemoryHandler, flushing means just sending the buffered
records to the target, if there is one. Override if you want
different behaviour.
The record buffer is also cleared by this operation.
"""
self.acquire()
try:
if self.target:
for record in self.buffer:
self.target.handle(record)
self.buffer = []
finally:
self.release()
def close(self):
"""
Flush, set the target to None and lose the buffer.
"""
self.flush()
self.acquire()
try:
self.target = None
BufferingHandler.close(self)
finally:
self.release()
class QueueHandler(logging.Handler):
"""
This handler sends events to a queue. Typically, it would be used together
with a multiprocessing Queue to centralise logging to file in one process
(in a multi-process application), so as to avoid file write contention
between processes.
This code is new in Python 3.2, but this class can be copy pasted into
user code for use with earlier Python versions.
"""
def __init__(self, queue):
"""
Initialise an instance, using the passed queue.
"""
logging.Handler.__init__(self)
self.queue = queue
def enqueue(self, record):
"""
Enqueue a record.
The base implementation uses put_nowait. You may want to override
this method if you want to use blocking, timeouts or custom queue
implementations.
"""
self.queue.put_nowait(record)
def prepare(self, record):
"""
Prepares a record for queuing. The object returned by this method is
enqueued.
The base implementation formats the record to merge the message
and arguments, and removes unpickleable items from the record
in-place.
You might want to override this method if you want to convert
the record to a dict or JSON string, or send a modified copy
of the record while leaving the original intact.
"""
# The format operation gets traceback text into record.exc_text
# (if there's exception data), and also puts the message into
# record.message. We can then use this to replace the original
# msg + args, as these might be unpickleable. We also zap the
# exc_info attribute, as it's no longer needed and, if not None,
# will typically not be pickleable.
self.format(record)
record.msg = record.message
record.args = None
record.exc_info = None
return record
def emit(self, record):
"""
Emit a record.
Writes the LogRecord to the queue, preparing it for pickling first.
"""
try:
self.enqueue(self.prepare(record))
except (KeyboardInterrupt, SystemExit): #pragma: no cover
raise
except:
self.handleError(record)
if threading:
class QueueListener(object):
"""
This class implements an internal threaded listener which watches for
LogRecords being added to a queue, removes them and passes them to a
list of handlers for processing.
"""
_sentinel = None
def __init__(self, queue, *handlers):
"""
Initialise an instance with the specified queue and
handlers.
"""
self.queue = queue
self.handlers = handlers
self._stop = threading.Event()
self._thread = None
def dequeue(self, block):
"""
Dequeue a record and return it, optionally blocking.
The base implementation uses get. You may want to override this method
if you want to use timeouts or work with custom queue implementations.
"""
return self.queue.get(block)
def start(self):
"""
Start the listener.
This starts up a background thread to monitor the queue for
LogRecords to process.
"""
self._thread = t = threading.Thread(target=self._monitor)
t.setDaemon(True)
t.start()
def prepare(self , record):
"""
Prepare a record for handling.
This method just returns the passed-in record. You may want to
override this method if you need to do any custom marshalling or
manipulation of the record before passing it to the handlers.
"""
return record
def handle(self, record):
"""
Handle a record.
This just loops through the handlers offering them the record
to handle.
"""
record = self.prepare(record)
for handler in self.handlers:
handler.handle(record)
def _monitor(self):
"""
Monitor the queue for records, and ask the handler
to deal with them.
This method runs on a separate, internal thread.
The thread will terminate if it sees a sentinel object in the queue.
"""
q = self.queue
has_task_done = hasattr(q, 'task_done')
while not self._stop.isSet():
try:
record = self.dequeue(True)
if record is self._sentinel:
break
self.handle(record)
if has_task_done:
q.task_done()
except queue.Empty:
pass
# There might still be records in the queue.
while True:
try:
record = self.dequeue(False)
if record is self._sentinel:
break
self.handle(record)
if has_task_done:
q.task_done()
except queue.Empty:
break
def enqueue_sentinel(self):
"""
This is used to enqueue the sentinel record.
The base implementation uses put_nowait. You may want to override this
method if you want to use timeouts or work with custom queue
implementations.
"""
self.queue.put_nowait(self._sentinel)
def stop(self):
"""
Stop the listener.
This asks the thread to terminate, and then waits for it to do so.
Note that if you don't call this before your application exits, there
may be some records still left on the queue, which won't be processed.
"""
self._stop.set()
self.enqueue_sentinel()
self._thread.join()
self._thread = None
|
subho007/androguard | refs/heads/master | androguard/decompiler/dad/tests/rpo_test.py | 2 | """Tests for rpo."""
import sys
sys.path.append('.')
import unittest
from androguard.decompiler.dad import graph
from androguard.decompiler.dad import node
class NodeTest(node.Node):
def __init__(self, name):
super(NodeTest, self).__init__(name)
def __str__(self):
return '%s (%d)' % (self.name, self.num)
class RpoTest(unittest.TestCase):
def _getNode(self, node_map, n):
ret_node = node_map.get(n)
if not ret_node:
ret_node = node_map[n] = NodeTest(n)
self.graph.add_node(ret_node)
return ret_node
def _createGraphFrom(self, edges):
node_map = {}
for n, childs in edges.items():
if n is None:
continue
parent_node = self._getNode(node_map, n)
for child in childs:
child_node = self._getNode(node_map, child)
self.graph.add_edge(parent_node, child_node)
self.graph.entry = node_map[edges[None]]
return node_map
def _verifyRpo(self, node_map, expected_rpo):
for n1, n2 in expected_rpo.items():
self.assertEqual(node_map[n1].num, n2)
def setUp(self):
self.graph = graph.Graph()
def tearDown(self):
self.graph = None
def testTarjanGraph(self):
edges = {None: 'r',
'r': ['a', 'b', 'c'],
'a': ['d'],
'b': ['a', 'd', 'e'],
'c': ['f', 'g'],
'd': ['l'],
'e': ['h'],
'f': ['i'],
'g': ['i', 'j'],
'h': ['e', 'k'],
'i': ['k'],
'j': ['i'],
'k': ['i', 'r'],
'l': ['h']}
n_map = self._createGraphFrom(edges)
self.graph.compute_rpo()
#self.graph.draw('_testTarjan_graph', '/tmp')
expected_rpo = {'r': 1, 'a': 7, 'b': 6, 'c': 2,
'd': 8, 'e': 13, 'f': 5,
'g': 3, 'h': 10, 'i': 12,
'j': 4, 'k': 11, 'l': 9}
self._verifyRpo(n_map, expected_rpo)
def testFirstGraph(self):
edges = {None: 'r',
'r': ['w1', 'x1', 'z5'],
'w1': ['w2'], 'w2': ['w3'],
'w3': ['w4'], 'w4': ['w5'],
'x1': ['x2'], 'x2': ['x3'],
'x3': ['x4'], 'x4': ['x5'], 'x5': ['y1'],
'y1': ['w1', 'w2', 'w3', 'w4', 'w5', 'y2'],
'y2': ['w1', 'w2', 'w3', 'w4', 'w5', 'y3'],
'y3': ['w1', 'w2', 'w3', 'w4', 'w5', 'y4'],
'y4': ['w1', 'w2', 'w3', 'w4', 'w5', 'y5'],
'y5': ['w1', 'w2', 'w3', 'w4', 'w5', 'z1'],
'z1': ['z2'],
'z2': ['z1', 'z3'],
'z3': ['z2', 'z4'],
'z4': ['z3', 'z5'],
'z5': ['z4']}
n_map = self._createGraphFrom(edges)
self.graph.compute_rpo()
#self.graph.draw('_testFirst_graph', '/tmp')
expected_rpo = {'r': 1, 'x1': 2, 'x2': 3, 'x3': 4, 'x4': 5, 'x5': 6,
'w1': 17, 'w2': 18, 'w3': 19, 'w4': 20, 'w5': 21,
'y1': 7, 'y2': 8, 'y3': 9, 'y4': 10, 'y5': 11,
'z1': 12, 'z2': 13, 'z3': 14, 'z4': 15, 'z5': 16}
self._verifyRpo(n_map, expected_rpo)
def testSecondGraph(self):
edges = {None: 'r',
'r': ['y1', 'x12'],
'x11': ['x12', 'x22'],
'x12': ['x11'],
'x21': ['x22'],
'x22': ['x21'],
'y1': ['y2', 'x11'],
'y2': ['x21']}
n_map = self._createGraphFrom(edges)
self.graph.compute_rpo()
#self.graph.draw('_testSecond_graph', '/tmp')
expected_rpo = {'r': 1, 'x11': 3, 'x12': 4, 'x21': 6, 'x22': 7,
'y1': 2, 'y2': 5}
self._verifyRpo(n_map, expected_rpo)
def testThirdGraph(self):
edges = {None: 'r',
'r': ['w', 'y1'],
'w': ['x1', 'x2'],
'x2': ['x1'],
'y1': ['y2'],
'y2': ['x2']}
n_map = self._createGraphFrom(edges)
self.graph.compute_rpo()
##self.graph.draw('_testThird_graph', '/tmp')
expected_rpo = {'r': 1, 'w': 4, 'x1': 6, 'x2': 5, 'y1': 2, 'y2': 3}
self._verifyRpo(n_map, expected_rpo)
def testFourthGraph(self):
edges = {None: 'r',
'r': ['x1', 'y1', 'y2'],
'x1': ['x2'],
'x2': ['y1', 'y2']}
n_map = self._createGraphFrom(edges)
self.graph.compute_rpo()
#self.graph.draw('_testFourth_graph', '/tmp')
expected_rpo = {'r': 1, 'x1': 2, 'x2': 3, 'y1': 5, 'y2': 4}
self._verifyRpo(n_map, expected_rpo)
def testFifthGraph(self):
edges = {None: 'r',
'r': ['a', 'i'],
'a': ['b', 'c'],
'b': ['c', 'e', 'g'],
'c': ['d'],
'd': ['i'],
'e': ['c', 'f'],
'f': ['i'],
'g': ['h'],
'h': ['d', 'f', 'i']}
n_map = self._createGraphFrom(edges)
self.graph.compute_rpo()
#self.graph.draw('_testFifth_graph', '/tmp')
expected_rpo = {'r': 1, 'a': 2, 'b': 3, 'c': 8,
'd': 9, 'e': 6, 'f': 7, 'g': 4,
'h': 5, 'i': 10}
self._verifyRpo(n_map, expected_rpo)
def testLinearVitGraph(self):
edges = {None: 'r',
'r': ['w', 'y'],
'w': ['x1'],
'y': ['x7'],
'x1': ['x2'],
'x2': ['x1', 'x3'],
'x3': ['x2', 'x4'],
'x4': ['x3', 'x5'],
'x5': ['x4', 'x6'],
'x6': ['x5', 'x7'],
'x7': ['x6']}
n_map = self._createGraphFrom(edges)
self.graph.compute_rpo()
#self.graph.draw('_testLinearVit_graph', '/tmp')
expected_rpo = {'r': 1, 'w': 3, 'x1': 4, 'x2': 5, 'x3': 6,
'x4': 7, 'x5': 8, 'x6': 9, 'x7': 10, 'y': 2}
self._verifyRpo(n_map, expected_rpo)
def testCrossGraph(self):
edges = {None: 'r',
'r': ['a', 'd'],
'a': ['b'],
'b': ['c'],
'c': ['a', 'd', 'g'],
'd': ['e'],
'e': ['f'],
'f': ['a', 'd', 'g']}
n_map = self._createGraphFrom(edges)
self.graph.compute_rpo()
#self.graph.draw('_testCross_graph', '/tmp')
expected_rpo = {'r': 1, 'a': 2, 'b': 3, 'c': 4,
'd': 5, 'e': 6, 'f': 7, 'g': 8}
self._verifyRpo(n_map, expected_rpo)
def testTVerifyGraph(self):
edges = {None: 'n1',
'n1': ['n2', 'n8'],
'n2': ['n3'],
'n3': ['n4', 'n8', 'n9'],
'n4': ['n3', 'n5', 'n6', 'n7'],
'n5': ['n4'],
'n6': ['n5'],
'n7': ['n6'],
'n8': ['n9', 'n12'],
'n9': ['n10', 'n11', 'n12'],
'n10': ['n11'],
'n11': ['n7'],
'n12': ['n10']}
n_map = self._createGraphFrom(edges)
self.graph.compute_rpo()
#self.graph.draw('_testTVerify_graph', '/tmp')
expected_rpo = {'n1': 1, 'n2': 2, 'n3': 3,
'n4': 9, 'n5': 12, 'n6': 11,
'n7': 10, 'n8': 4, 'n9': 5,
'n10': 7, 'n11': 8, 'n12': 6}
self._verifyRpo(n_map, expected_rpo)
if __name__ == '__main__':
unittest.main()
|
yestech/gae-django-template | refs/heads/master | django/contrib/admindocs/utils.py | 314 | "Misc. utility functions/classes for admin documentation generator."
import re
from email.Parser import HeaderParser
from email.Errors import HeaderParseError
from django.utils.safestring import mark_safe
from django.core.urlresolvers import reverse
from django.utils.encoding import smart_str
try:
import docutils.core
import docutils.nodes
import docutils.parsers.rst.roles
except ImportError:
docutils_is_available = False
else:
docutils_is_available = True
def trim_docstring(docstring):
"""
Uniformly trims leading/trailing whitespace from docstrings.
Based on http://www.python.org/peps/pep-0257.html#handling-docstring-indentation
"""
if not docstring or not docstring.strip():
return ''
# Convert tabs to spaces and split into lines
lines = docstring.expandtabs().splitlines()
indent = min([len(line) - len(line.lstrip()) for line in lines if line.lstrip()])
trimmed = [lines[0].lstrip()] + [line[indent:].rstrip() for line in lines[1:]]
return "\n".join(trimmed).strip()
def parse_docstring(docstring):
"""
Parse out the parts of a docstring. Returns (title, body, metadata).
"""
docstring = trim_docstring(docstring)
parts = re.split(r'\n{2,}', docstring)
title = parts[0]
if len(parts) == 1:
body = ''
metadata = {}
else:
parser = HeaderParser()
try:
metadata = parser.parsestr(parts[-1])
except HeaderParseError:
metadata = {}
body = "\n\n".join(parts[1:])
else:
metadata = dict(metadata.items())
if metadata:
body = "\n\n".join(parts[1:-1])
else:
body = "\n\n".join(parts[1:])
return title, body, metadata
def parse_rst(text, default_reference_context, thing_being_parsed=None):
"""
Convert the string from reST to an XHTML fragment.
"""
overrides = {
'doctitle_xform' : True,
'inital_header_level' : 3,
"default_reference_context" : default_reference_context,
"link_base" : reverse('django-admindocs-docroot').rstrip('/')
}
if thing_being_parsed:
thing_being_parsed = smart_str("<%s>" % thing_being_parsed)
parts = docutils.core.publish_parts(text, source_path=thing_being_parsed,
destination_path=None, writer_name='html',
settings_overrides=overrides)
return mark_safe(parts['fragment'])
#
# reST roles
#
ROLES = {
'model' : '%s/models/%s/',
'view' : '%s/views/%s/',
'template' : '%s/templates/%s/',
'filter' : '%s/filters/#%s',
'tag' : '%s/tags/#%s',
}
def create_reference_role(rolename, urlbase):
def _role(name, rawtext, text, lineno, inliner, options=None, content=None):
if options is None: options = {}
if content is None: content = []
node = docutils.nodes.reference(rawtext, text, refuri=(urlbase % (inliner.document.settings.link_base, text.lower())), **options)
return [node], []
docutils.parsers.rst.roles.register_canonical_role(rolename, _role)
def default_reference_role(name, rawtext, text, lineno, inliner, options=None, content=None):
if options is None: options = {}
if content is None: content = []
context = inliner.document.settings.default_reference_context
node = docutils.nodes.reference(rawtext, text, refuri=(ROLES[context] % (inliner.document.settings.link_base, text.lower())), **options)
return [node], []
if docutils_is_available:
docutils.parsers.rst.roles.register_canonical_role('cmsreference', default_reference_role)
docutils.parsers.rst.roles.DEFAULT_INTERPRETED_ROLE = 'cmsreference'
for name, urlbase in ROLES.items():
create_reference_role(name, urlbase)
|
a-parhom/edx-platform | refs/heads/master | lms/djangoapps/instructor_analytics/tests/test_basic.py | 4 | """
Tests for instructor.basic
"""
import datetime
import json
import pytz
from django.urls import reverse
from django.db.models import Q
from edx_proctoring.api import create_exam
from edx_proctoring.models import ProctoredExamStudentAttempt
from mock import MagicMock, Mock, patch
from opaque_keys.edx.locator import UsageKey
from six import text_type
from course_modes.models import CourseMode
from course_modes.tests.factories import CourseModeFactory
from courseware.tests.factories import InstructorFactory
from instructor_analytics.basic import (
AVAILABLE_FEATURES,
PROFILE_FEATURES,
STUDENT_FEATURES,
StudentModule,
coupon_codes_features,
course_registration_features,
enrolled_students_features,
get_proctored_exam_results,
list_may_enroll,
list_problem_responses,
sale_order_record_features,
sale_record_features
)
from openedx.core.djangoapps.course_groups.tests.helpers import CohortFactory
from shoppingcart.models import (
Coupon,
CouponRedemption,
CourseRegCodeItem,
CourseRegistrationCode,
CourseRegistrationCodeInvoiceItem,
Invoice,
Order,
RegistrationCodeRedemption
)
from student.models import CourseEnrollment, CourseEnrollmentAllowed
from student.roles import CourseSalesAdminRole
from student.tests.factories import UserFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
class TestAnalyticsBasic(ModuleStoreTestCase):
""" Test basic analytics functions. """
shard = 3
def setUp(self):
super(TestAnalyticsBasic, self).setUp()
self.course_key = self.store.make_course_key('robot', 'course', 'id')
self.users = tuple(UserFactory() for _ in xrange(30))
self.ces = tuple(CourseEnrollment.enroll(user, self.course_key)
for user in self.users)
self.instructor = InstructorFactory(course_key=self.course_key)
for user in self.users:
user.profile.meta = json.dumps({
"position": "edX expert {}".format(user.id),
"company": "Open edX Inc {}".format(user.id),
})
user.profile.save()
self.students_who_may_enroll = list(self.users) + [UserFactory() for _ in range(5)]
for student in self.students_who_may_enroll:
CourseEnrollmentAllowed.objects.create(
email=student.email, course_id=self.course_key
)
def test_list_problem_responses(self):
def result_factory(result_id):
"""
Return a dummy StudentModule object that can be queried for
relevant info (student.username and state).
"""
result = Mock(spec=['student', 'state'])
result.student.username.return_value = u'user{}'.format(result_id)
result.state.return_value = u'state{}'.format(result_id)
return result
# Ensure that UsageKey.from_string returns a problem key that list_problem_responses can work with
# (even when called with a dummy location):
mock_problem_key = Mock(return_value=u'')
mock_problem_key.course_key = self.course_key
with patch.object(UsageKey, 'from_string') as patched_from_string:
patched_from_string.return_value = mock_problem_key
# Ensure that StudentModule.objects.filter returns a result set that list_problem_responses can work with
# (this keeps us from having to create fixtures for this test):
mock_results = MagicMock(return_value=[result_factory(n) for n in range(5)])
with patch.object(StudentModule, 'objects') as patched_manager:
patched_manager.filter.return_value = mock_results
mock_problem_location = ''
problem_responses = list_problem_responses(self.course_key, problem_location=mock_problem_location)
# Check if list_problem_responses called UsageKey.from_string to look up problem key:
patched_from_string.assert_called_once_with(mock_problem_location)
# Check if list_problem_responses called StudentModule.objects.filter to obtain relevant records:
patched_manager.filter.assert_called_once_with(
course_id=self.course_key, module_state_key=mock_problem_key
)
# Check if list_problem_responses returned expected results:
self.assertEqual(len(problem_responses), len(mock_results))
for mock_result in mock_results:
self.assertIn(
{'username': mock_result.student.username, 'state': mock_result.state},
problem_responses
)
def test_enrolled_students_features_username(self):
self.assertIn('username', AVAILABLE_FEATURES)
userreports = enrolled_students_features(self.course_key, ['username'])
self.assertEqual(len(userreports), len(self.users))
for userreport in userreports:
self.assertEqual(userreport.keys(), ['username'])
self.assertIn(userreport['username'], [user.username for user in self.users])
def test_enrolled_students_features_keys(self):
query_features = ('username', 'name', 'email', 'city', 'country',)
for user in self.users:
user.profile.city = "Mos Eisley {}".format(user.id)
user.profile.country = "Tatooine {}".format(user.id)
user.profile.save()
for feature in query_features:
self.assertIn(feature, AVAILABLE_FEATURES)
with self.assertNumQueries(1):
userreports = enrolled_students_features(self.course_key, query_features)
self.assertEqual(len(userreports), len(self.users))
userreports = sorted(userreports, key=lambda u: u["username"])
users = sorted(self.users, key=lambda u: u.username)
for userreport, user in zip(userreports, users):
self.assertEqual(set(userreport.keys()), set(query_features))
self.assertEqual(userreport['username'], user.username)
self.assertEqual(userreport['email'], user.email)
self.assertEqual(userreport['name'], user.profile.name)
self.assertEqual(userreport['city'], user.profile.city)
self.assertEqual(userreport['country'], user.profile.country)
def test_enrolled_student_with_no_country_city(self):
userreports = enrolled_students_features(self.course_key, ('username', 'city', 'country',))
for userreport in userreports:
# This behaviour is somewhat inconsistent: None string fields
# objects are converted to "None", but non-JSON serializable fields
# are converted to an empty string.
self.assertEqual(userreport['city'], "None")
self.assertEqual(userreport['country'], "")
def test_enrolled_students_meta_features_keys(self):
"""
Assert that we can query individual fields in the 'meta' field in the UserProfile
"""
query_features = ('meta.position', 'meta.company')
with self.assertNumQueries(1):
userreports = enrolled_students_features(self.course_key, query_features)
self.assertEqual(len(userreports), len(self.users))
for userreport in userreports:
self.assertEqual(set(userreport.keys()), set(query_features))
self.assertIn(userreport['meta.position'], ["edX expert {}".format(user.id) for user in self.users])
self.assertIn(userreport['meta.company'], ["Open edX Inc {}".format(user.id) for user in self.users])
def test_enrolled_students_enrollment_verification(self):
"""
Assert that we can get enrollment mode and verification status
"""
query_features = ('enrollment_mode', 'verification_status')
userreports = enrolled_students_features(self.course_key, query_features)
self.assertEqual(len(userreports), len(self.users))
# by default all users should have "audit" as their enrollment mode
# and "N/A" as their verification status
for userreport in userreports:
self.assertEqual(set(userreport.keys()), set(query_features))
self.assertIn(userreport['enrollment_mode'], ["audit"])
self.assertIn(userreport['verification_status'], ["N/A"])
# make sure that the user report respects whatever value
# is returned by verification and enrollment code
with patch("student.models.CourseEnrollment.enrollment_mode_for_user") as enrollment_patch:
with patch(
"lms.djangoapps.verify_student.services.IDVerificationService.verification_status_for_user"
) as verify_patch:
enrollment_patch.return_value = ["verified"]
verify_patch.return_value = "dummy verification status"
userreports = enrolled_students_features(self.course_key, query_features)
self.assertEqual(len(userreports), len(self.users))
for userreport in userreports:
self.assertEqual(set(userreport.keys()), set(query_features))
self.assertIn(userreport['enrollment_mode'], ["verified"])
self.assertIn(userreport['verification_status'], ["dummy verification status"])
def test_enrolled_students_features_keys_cohorted(self):
course = CourseFactory.create(org="test", course="course1", display_name="run1")
course.cohort_config = {'cohorted': True, 'auto_cohort': True, 'auto_cohort_groups': ['cohort']}
self.store.update_item(course, self.instructor.id)
cohorted_students = [UserFactory.create() for _ in xrange(10)]
cohort = CohortFactory.create(name='cohort', course_id=course.id, users=cohorted_students)
cohorted_usernames = [student.username for student in cohorted_students]
non_cohorted_student = UserFactory.create()
for student in cohorted_students:
cohort.users.add(student)
CourseEnrollment.enroll(student, course.id)
CourseEnrollment.enroll(non_cohorted_student, course.id)
instructor = InstructorFactory(course_key=course.id)
self.client.login(username=instructor.username, password='test')
query_features = ('username', 'cohort')
# There should be a constant of 2 SQL queries when calling
# enrolled_students_features. The first query comes from the call to
# User.objects.filter(...), and the second comes from
# prefetch_related('course_groups').
with self.assertNumQueries(2):
userreports = enrolled_students_features(course.id, query_features)
self.assertEqual(len([r for r in userreports if r['username'] in cohorted_usernames]), len(cohorted_students))
self.assertEqual(len([r for r in userreports if r['username'] == non_cohorted_student.username]), 1)
for report in userreports:
self.assertEqual(set(report.keys()), set(query_features))
if report['username'] in cohorted_usernames:
self.assertEqual(report['cohort'], cohort.name)
else:
self.assertEqual(report['cohort'], '[unassigned]')
def test_available_features(self):
self.assertEqual(len(AVAILABLE_FEATURES), len(STUDENT_FEATURES + PROFILE_FEATURES))
self.assertEqual(set(AVAILABLE_FEATURES), set(STUDENT_FEATURES + PROFILE_FEATURES))
def test_list_may_enroll(self):
may_enroll = list_may_enroll(self.course_key, ['email'])
self.assertEqual(len(may_enroll), len(self.students_who_may_enroll) - len(self.users))
email_adresses = [student.email for student in self.students_who_may_enroll]
for student in may_enroll:
self.assertEqual(student.keys(), ['email'])
self.assertIn(student['email'], email_adresses)
def test_get_student_exam_attempt_features(self):
query_features = [
'email',
'exam_name',
'allowed_time_limit_mins',
'is_sample_attempt',
'started_at',
'completed_at',
'status',
'Suspicious Count',
'Suspicious Comments',
'Rules Violation Count',
'Rules Violation Comments',
]
proctored_exam_id = create_exam(self.course_key, 'Test Content', 'Test Exam', 1)
ProctoredExamStudentAttempt.create_exam_attempt(
proctored_exam_id, self.users[0].id, '',
'Test Code 1', True, False, 'ad13'
)
ProctoredExamStudentAttempt.create_exam_attempt(
proctored_exam_id, self.users[1].id, '',
'Test Code 2', True, False, 'ad13'
)
ProctoredExamStudentAttempt.create_exam_attempt(
proctored_exam_id, self.users[2].id, '',
'Test Code 3', True, False, 'asd'
)
proctored_exam_attempts = get_proctored_exam_results(self.course_key, query_features)
self.assertEqual(len(proctored_exam_attempts), 3)
for proctored_exam_attempt in proctored_exam_attempts:
self.assertEqual(set(proctored_exam_attempt.keys()), set(query_features))
@patch.dict('django.conf.settings.FEATURES', {'ENABLE_PAID_COURSE_REGISTRATION': True})
class TestCourseSaleRecordsAnalyticsBasic(ModuleStoreTestCase):
""" Test basic course sale records analytics functions. """
def setUp(self):
"""
Fixtures.
"""
super(TestCourseSaleRecordsAnalyticsBasic, self).setUp()
self.course = CourseFactory.create()
self.cost = 40
self.course_mode = CourseMode(
course_id=self.course.id, mode_slug="honor",
mode_display_name="honor cert", min_price=self.cost
)
self.course_mode.save()
self.instructor = InstructorFactory(course_key=self.course.id)
self.client.login(username=self.instructor.username, password='test')
def test_course_sale_features(self):
query_features = [
'company_name', 'company_contact_name', 'company_contact_email', 'total_codes', 'total_used_codes',
'total_amount', 'created', 'customer_reference_number', 'recipient_name', 'recipient_email',
'created_by', 'internal_reference', 'invoice_number', 'codes', 'course_id'
]
#create invoice
sale_invoice = Invoice.objects.create(
total_amount=1234.32, company_name='Test1', company_contact_name='TestName',
company_contact_email='test@company.com', recipient_name='Testw_1', recipient_email='test2@test.com',
customer_reference_number='2Fwe23S', internal_reference="ABC", course_id=self.course.id
)
invoice_item = CourseRegistrationCodeInvoiceItem.objects.create(
invoice=sale_invoice,
qty=1,
unit_price=1234.32,
course_id=self.course.id
)
for i in range(5):
course_code = CourseRegistrationCode(
code="test_code{}".format(i), course_id=text_type(self.course.id),
created_by=self.instructor, invoice=sale_invoice, invoice_item=invoice_item, mode_slug='honor'
)
course_code.save()
course_sale_records_list = sale_record_features(self.course.id, query_features)
for sale_record in course_sale_records_list:
self.assertEqual(sale_record['total_amount'], sale_invoice.total_amount)
self.assertEqual(sale_record['recipient_email'], sale_invoice.recipient_email)
self.assertEqual(sale_record['recipient_name'], sale_invoice.recipient_name)
self.assertEqual(sale_record['company_name'], sale_invoice.company_name)
self.assertEqual(sale_record['company_contact_name'], sale_invoice.company_contact_name)
self.assertEqual(sale_record['company_contact_email'], sale_invoice.company_contact_email)
self.assertEqual(sale_record['internal_reference'], sale_invoice.internal_reference)
self.assertEqual(sale_record['customer_reference_number'], sale_invoice.customer_reference_number)
self.assertEqual(sale_record['invoice_number'], sale_invoice.id)
self.assertEqual(sale_record['created_by'], self.instructor)
self.assertEqual(sale_record['total_used_codes'], 0)
self.assertEqual(sale_record['total_codes'], 5)
def test_course_sale_no_codes(self):
query_features = [
'company_name', 'company_contact_name', 'company_contact_email', 'total_codes', 'total_used_codes',
'total_amount', 'created', 'customer_reference_number', 'recipient_name', 'recipient_email',
'created_by', 'internal_reference', 'invoice_number', 'codes', 'course_id'
]
#create invoice
sale_invoice = Invoice.objects.create(
total_amount=0.00, company_name='Test1', company_contact_name='TestName',
company_contact_email='test@company.com', recipient_name='Testw_1', recipient_email='test2@test.com',
customer_reference_number='2Fwe23S', internal_reference="ABC", course_id=self.course.id
)
CourseRegistrationCodeInvoiceItem.objects.create(
invoice=sale_invoice,
qty=0,
unit_price=0.00,
course_id=self.course.id
)
course_sale_records_list = sale_record_features(self.course.id, query_features)
for sale_record in course_sale_records_list:
self.assertEqual(sale_record['total_amount'], sale_invoice.total_amount)
self.assertEqual(sale_record['recipient_email'], sale_invoice.recipient_email)
self.assertEqual(sale_record['recipient_name'], sale_invoice.recipient_name)
self.assertEqual(sale_record['company_name'], sale_invoice.company_name)
self.assertEqual(sale_record['company_contact_name'], sale_invoice.company_contact_name)
self.assertEqual(sale_record['company_contact_email'], sale_invoice.company_contact_email)
self.assertEqual(sale_record['internal_reference'], sale_invoice.internal_reference)
self.assertEqual(sale_record['customer_reference_number'], sale_invoice.customer_reference_number)
self.assertEqual(sale_record['invoice_number'], sale_invoice.id)
self.assertEqual(sale_record['created_by'], None)
self.assertEqual(sale_record['total_used_codes'], 0)
self.assertEqual(sale_record['total_codes'], 0)
def test_sale_order_features_with_discount(self):
"""
Test Order Sales Report CSV
"""
query_features = [
('id', 'Order Id'),
('company_name', 'Company Name'),
('company_contact_name', 'Company Contact Name'),
('company_contact_email', 'Company Contact Email'),
('total_amount', 'Total Amount'),
('total_codes', 'Total Codes'),
('total_used_codes', 'Total Used Codes'),
('logged_in_username', 'Login Username'),
('logged_in_email', 'Login User Email'),
('purchase_time', 'Date of Sale'),
('customer_reference_number', 'Customer Reference Number'),
('recipient_name', 'Recipient Name'),
('recipient_email', 'Recipient Email'),
('bill_to_street1', 'Street 1'),
('bill_to_street2', 'Street 2'),
('bill_to_city', 'City'),
('bill_to_state', 'State'),
('bill_to_postalcode', 'Postal Code'),
('bill_to_country', 'Country'),
('order_type', 'Order Type'),
('status', 'Order Item Status'),
('coupon_code', 'Coupon Code'),
('unit_cost', 'Unit Price'),
('list_price', 'List Price'),
('codes', 'Registration Codes'),
('course_id', 'Course Id')
]
# add the coupon code for the course
coupon = Coupon(
code='test_code',
description='test_description',
course_id=self.course.id,
percentage_discount='10',
created_by=self.instructor,
is_active=True
)
coupon.save()
order = Order.get_cart_for_user(self.instructor)
order.order_type = 'business'
order.save()
order.add_billing_details(
company_name='Test Company',
company_contact_name='Test',
company_contact_email='test@123',
recipient_name='R1', recipient_email='',
customer_reference_number='PO#23'
)
CourseRegCodeItem.add_to_order(order, self.course.id, 4)
# apply the coupon code to the item in the cart
resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': coupon.code})
self.assertEqual(resp.status_code, 200)
order.purchase()
# get the updated item
item = order.orderitem_set.all().select_subclasses()[0]
# get the redeemed coupon information
coupon_redemption = CouponRedemption.objects.select_related('coupon').filter(order=order)
db_columns = [x[0] for x in query_features]
sale_order_records_list = sale_order_record_features(self.course.id, db_columns)
for sale_order_record in sale_order_records_list:
self.assertEqual(sale_order_record['recipient_email'], order.recipient_email)
self.assertEqual(sale_order_record['recipient_name'], order.recipient_name)
self.assertEqual(sale_order_record['company_name'], order.company_name)
self.assertEqual(sale_order_record['company_contact_name'], order.company_contact_name)
self.assertEqual(sale_order_record['company_contact_email'], order.company_contact_email)
self.assertEqual(sale_order_record['customer_reference_number'], order.customer_reference_number)
self.assertEqual(sale_order_record['unit_cost'], item.unit_cost)
self.assertEqual(sale_order_record['list_price'], item.list_price)
self.assertEqual(sale_order_record['status'], item.status)
self.assertEqual(sale_order_record['coupon_code'], coupon_redemption[0].coupon.code)
def test_sale_order_features_without_discount(self):
"""
Test Order Sales Report CSV
"""
query_features = [
('id', 'Order Id'),
('company_name', 'Company Name'),
('company_contact_name', 'Company Contact Name'),
('company_contact_email', 'Company Contact Email'),
('total_amount', 'Total Amount'),
('total_codes', 'Total Codes'),
('total_used_codes', 'Total Used Codes'),
('logged_in_username', 'Login Username'),
('logged_in_email', 'Login User Email'),
('purchase_time', 'Date of Sale'),
('customer_reference_number', 'Customer Reference Number'),
('recipient_name', 'Recipient Name'),
('recipient_email', 'Recipient Email'),
('bill_to_street1', 'Street 1'),
('bill_to_street2', 'Street 2'),
('bill_to_city', 'City'),
('bill_to_state', 'State'),
('bill_to_postalcode', 'Postal Code'),
('bill_to_country', 'Country'),
('order_type', 'Order Type'),
('status', 'Order Item Status'),
('coupon_code', 'Coupon Code'),
('unit_cost', 'Unit Price'),
('list_price', 'List Price'),
('codes', 'Registration Codes'),
('course_id', 'Course Id'),
('quantity', 'Quantity'),
('total_discount', 'Total Discount'),
('total_amount', 'Total Amount Paid'),
]
# add the coupon code for the course
order = Order.get_cart_for_user(self.instructor)
order.order_type = 'business'
order.save()
order.add_billing_details(
company_name='Test Company',
company_contact_name='Test',
company_contact_email='test@123',
recipient_name='R1', recipient_email='',
customer_reference_number='PO#23'
)
CourseRegCodeItem.add_to_order(order, self.course.id, 4)
order.purchase()
# get the updated item
item = order.orderitem_set.all().select_subclasses()[0]
db_columns = [x[0] for x in query_features]
sale_order_records_list = sale_order_record_features(self.course.id, db_columns)
for sale_order_record in sale_order_records_list:
self.assertEqual(sale_order_record['recipient_email'], order.recipient_email)
self.assertEqual(sale_order_record['recipient_name'], order.recipient_name)
self.assertEqual(sale_order_record['company_name'], order.company_name)
self.assertEqual(sale_order_record['company_contact_name'], order.company_contact_name)
self.assertEqual(sale_order_record['company_contact_email'], order.company_contact_email)
self.assertEqual(sale_order_record['customer_reference_number'], order.customer_reference_number)
self.assertEqual(sale_order_record['unit_cost'], item.unit_cost)
# Make sure list price is not None and matches the unit price since no discount was applied.
self.assertIsNotNone(sale_order_record['list_price'])
self.assertEqual(sale_order_record['list_price'], item.unit_cost)
self.assertEqual(sale_order_record['status'], item.status)
self.assertEqual(sale_order_record['coupon_code'], 'N/A')
self.assertEqual(sale_order_record['total_amount'], item.unit_cost * item.qty)
self.assertEqual(sale_order_record['total_discount'], 0)
self.assertEqual(sale_order_record['quantity'], item.qty)
class TestCourseRegistrationCodeAnalyticsBasic(ModuleStoreTestCase):
""" Test basic course registration codes analytics functions. """
def setUp(self):
"""
Fixtures.
"""
super(TestCourseRegistrationCodeAnalyticsBasic, self).setUp()
self.course = CourseFactory.create()
self.instructor = InstructorFactory(course_key=self.course.id)
self.client.login(username=self.instructor.username, password='test')
CourseSalesAdminRole(self.course.id).add_users(self.instructor)
# Create a paid course mode.
mode = CourseModeFactory.create(course_id=self.course.id, min_price=1)
url = reverse('generate_registration_codes',
kwargs={'course_id': text_type(self.course.id)})
data = {
'total_registration_codes': 12, 'company_name': 'Test Group', 'unit_price': 122.45,
'company_contact_name': 'TestName', 'company_contact_email': 'test@company.com', 'recipient_name': 'Test123',
'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '',
'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '',
'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': ''
}
response = self.client.post(url, data, **{'HTTP_HOST': 'localhost'})
self.assertEqual(response.status_code, 200, response.content)
def test_course_registration_features(self):
query_features = [
'code', 'redeem_code_url', 'course_id', 'company_name', 'created_by',
'redeemed_by', 'invoice_id', 'purchaser', 'customer_reference_number', 'internal_reference'
]
order = Order(user=self.instructor, status='purchased')
order.save()
registration_code_redemption = RegistrationCodeRedemption(
registration_code_id=1, redeemed_by=self.instructor
)
registration_code_redemption.save()
registration_codes = CourseRegistrationCode.objects.all()
course_registration_list = course_registration_features(query_features, registration_codes, csv_type='download')
self.assertEqual(len(course_registration_list), len(registration_codes))
for course_registration in course_registration_list:
self.assertEqual(set(course_registration.keys()), set(query_features))
self.assertIn(course_registration['code'], [registration_code.code for registration_code in registration_codes])
self.assertIn(
course_registration['course_id'],
[text_type(registration_code.course_id) for registration_code in registration_codes]
)
self.assertIn(
course_registration['company_name'],
[
registration_code.invoice_item.invoice.company_name
for registration_code in registration_codes
]
)
self.assertIn(
course_registration['invoice_id'],
[
registration_code.invoice_item.invoice_id
for registration_code in registration_codes
]
)
def test_coupon_codes_features(self):
query_features = [
'course_id', 'percentage_discount', 'code_redeemed_count', 'description', 'expiration_date',
'total_discounted_amount', 'total_discounted_seats'
]
for i in range(10):
coupon = Coupon(
code='test_code{0}'.format(i),
description='test_description',
course_id=self.course.id, percentage_discount='{0}'.format(i),
created_by=self.instructor,
is_active=True
)
coupon.save()
#now create coupons with the expiration dates
for i in range(5):
coupon = Coupon(
code='coupon{0}'.format(i), description='test_description', course_id=self.course.id,
percentage_discount='{0}'.format(i), created_by=self.instructor, is_active=True,
expiration_date=datetime.datetime.now(pytz.UTC) + datetime.timedelta(days=2)
)
coupon.save()
active_coupons = Coupon.objects.filter(
Q(course_id=self.course.id),
Q(is_active=True),
Q(expiration_date__gt=datetime.datetime.now(pytz.UTC)) |
Q(expiration_date__isnull=True)
)
active_coupons_list = coupon_codes_features(query_features, active_coupons, self.course.id)
self.assertEqual(len(active_coupons_list), len(active_coupons))
for active_coupon in active_coupons_list:
self.assertEqual(set(active_coupon.keys()), set(query_features))
self.assertIn(active_coupon['percentage_discount'], [coupon.percentage_discount for coupon in active_coupons])
self.assertIn(active_coupon['description'], [coupon.description for coupon in active_coupons])
if active_coupon['expiration_date']:
self.assertIn(active_coupon['expiration_date'], [coupon.display_expiry_date for coupon in active_coupons])
self.assertIn(
active_coupon['course_id'],
[text_type(coupon.course_id) for coupon in active_coupons]
)
|
jayinton/FlaskDemo | refs/heads/master | simple/methodTest.py | 1 | #!/usr/bin/env python
# coding=utf-8
__author__ = 'Jayin Ton'
from flask import Flask, request
host = '127.0.0.1'
port = 8000
app = Flask(__name__)
@app.before_request
def before_request():
print("before_request")
print request
# 必须返回response
@app.after_request
def after_request(res):
print "after_request"
print res
return res
@app.route('/requesting', methods=['GET'])
def requesting():
print "requesting!"
return "requesting"
@app.route('/', methods=['GET'])
def index():
return "Welcome"
@app.route('/post', methods=['POST'])
def add():
return "Post!"
@app.route('/put', methods=['PUT'])
def put():
return "PUT"
@app.route('/delete', methods=['DELETE'])
def delete():
return "DELETE"
if __name__ == '__main__':
app.run(host=host, port=port, debug=True)
|
diogommartins/ryu | refs/heads/master | ryu/app/simple_switch_lacp.py | 58 | # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
#
# 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.
import struct
from ryu.base import app_manager
from ryu.controller.handler import MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_0
from ryu.lib import addrconv
from ryu.lib import lacplib
from ryu.lib.dpid import str_to_dpid
class SimpleSwitchLacp(app_manager.RyuApp):
OFP_VERSIONS = [ofproto_v1_0.OFP_VERSION]
_CONTEXTS = {'lacplib': lacplib.LacpLib}
def __init__(self, *args, **kwargs):
super(SimpleSwitchLacp, self).__init__(*args, **kwargs)
self.mac_to_port = {}
self._lacp = kwargs['lacplib']
# in this sample application, bonding i/fs of the switchs
# shall be set up as follows:
# - the port 1 and 2 of the datapath 1 face the slave i/fs.
# - the port 3, 4 and 5 of the datapath 1 face the others.
# - the port 1 and 2 of the datapath 2 face the others.
self._lacp.add(
dpid=str_to_dpid('0000000000000001'), ports=[1, 2])
self._lacp.add(
dpid=str_to_dpid('0000000000000001'), ports=[3, 4, 5])
self._lacp.add(
dpid=str_to_dpid('0000000000000002'), ports=[1, 2])
def add_flow(self, datapath, in_port, dst, actions):
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
match = parser.OFPMatch(in_port=in_port,
dl_dst=addrconv.mac.text_to_bin(dst))
mod = parser.OFPFlowMod(
datapath=datapath, match=match, cookie=0,
command=ofproto.OFPFC_ADD, actions=actions)
datapath.send_msg(mod)
def del_flow(self, datapath, dst):
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
match = parser.OFPMatch(dl_dst=addrconv.mac.text_to_bin(dst))
mod = parser.OFPFlowMod(
datapath=datapath, match=match, cookie=0,
command=ofproto.OFPFC_DELETE)
datapath.send_msg(mod)
@set_ev_cls(lacplib.EventPacketIn, MAIN_DISPATCHER)
def _packet_in_handler(self, ev):
msg = ev.msg
datapath = msg.datapath
ofproto = datapath.ofproto
(dst_, src_, _eth_type) = struct.unpack_from(
'!6s6sH', buffer(msg.data), 0)
src = addrconv.mac.bin_to_text(src_)
dst = addrconv.mac.bin_to_text(dst_)
dpid = datapath.id
self.mac_to_port.setdefault(dpid, {})
self.logger.info("packet in %s %s %s %s",
dpid, src, dst, msg.in_port)
# learn a mac address to avoid FLOOD next time.
self.mac_to_port[dpid][src] = msg.in_port
if dst in self.mac_to_port[dpid]:
out_port = self.mac_to_port[dpid][dst]
else:
out_port = ofproto.OFPP_FLOOD
actions = [datapath.ofproto_parser.OFPActionOutput(out_port)]
# install a flow to avoid packet_in next time
if out_port != ofproto.OFPP_FLOOD:
self.add_flow(datapath, msg.in_port, dst, actions)
out = datapath.ofproto_parser.OFPPacketOut(
datapath=datapath, buffer_id=msg.buffer_id, in_port=msg.in_port,
actions=actions)
datapath.send_msg(out)
@set_ev_cls(lacplib.EventSlaveStateChanged, MAIN_DISPATCHER)
def _slave_state_changed_handler(self, ev):
datapath = ev.datapath
dpid = datapath.id
port_no = ev.port
enabled = ev.enabled
self.logger.info("slave state changed port: %d enabled: %s",
port_no, enabled)
if dpid in self.mac_to_port:
for mac in self.mac_to_port[dpid]:
self.del_flow(datapath, mac)
del self.mac_to_port[dpid]
self.mac_to_port.setdefault(dpid, {})
|
mmardini/django | refs/heads/master | django/contrib/sitemaps/management/commands/ping_google.py | 81 | from django.core.management.base import BaseCommand
from django.contrib.sitemaps import ping_google
class Command(BaseCommand):
help = "Ping Google with an updated sitemap, pass optional url of sitemap"
def execute(self, *args, **options):
if len(args) == 1:
sitemap_url = args[0]
else:
sitemap_url = None
ping_google(sitemap_url=sitemap_url)
|
jayoshih/kolibri | refs/heads/master | kolibri/content/serializers.py | 2 | from django.db.models import Sum
from kolibri.auth.models import FacilityUser
from kolibri.content.models import ChannelMetadataCache, ContentNode, File
from rest_framework import serializers
from .content_db_router import default_database_is_attached, get_active_content_database
class ChannelMetadataCacheSerializer(serializers.ModelSerializer):
class Meta:
model = ChannelMetadataCache
fields = ('root_pk', 'id', 'name', 'description', 'author')
class FileSerializer(serializers.ModelSerializer):
storage_url = serializers.SerializerMethodField()
preset = serializers.SerializerMethodField()
download_url = serializers.SerializerMethodField()
def get_storage_url(self, target_node):
return target_node.get_storage_url()
def get_preset(self, target_node):
return target_node.get_preset()
def get_download_url(self, target_node):
return target_node.get_download_url()
class Meta:
model = File
fields = ('storage_url', 'id', 'priority', 'checksum', 'available', 'file_size', 'extension', 'preset', 'lang',
'supplementary', 'thumbnail', 'download_url')
class ContentNodeSerializer(serializers.ModelSerializer):
parent = serializers.PrimaryKeyRelatedField(read_only=True)
files = FileSerializer(many=True, read_only=True)
ancestors = serializers.SerializerMethodField()
thumbnail = serializers.SerializerMethodField()
progress_fraction = serializers.SerializerMethodField()
next_content = serializers.SerializerMethodField()
def __init__(self, *args, **kwargs):
# Instantiate the superclass normally
super(ContentNodeSerializer, self).__init__(*args, **kwargs)
# enable dynamic fields specification!
if 'request' in self.context and self.context['request'].GET.get('fields', None):
fields = self.context['request'].GET['fields'].split(',')
# Drop any fields that are not specified in the `fields` argument.
allowed = set(fields)
existing = set(self.fields.keys())
for field_name in existing - allowed:
self.fields.pop(field_name)
def get_progress_fraction(self, target_node):
from kolibri.logger.models import ContentSummaryLog
# no progress if we don't have a request object or the user isn't a FacilityUser
if 'request' not in self.context or not isinstance(self.context['request'].user, FacilityUser):
return 0
# we're getting progress for the currently logged-in user
user = self.context["request"].user
# get the content_id for every content node that's under this node
leaf_ids = target_node.get_descendants(include_self=True).exclude(kind="topic").values_list("content_id", flat=True)
# get all summary logs for the current user that correspond to the descendant content nodes
if default_database_is_attached(): # if possible, do a direct join between the content and default databases
channel_alias = get_active_content_database()
summary_logs = ContentSummaryLog.objects.using(channel_alias).filter(user=user, content_id__in=leaf_ids)
else: # otherwise, convert the leaf queryset into a flat list of ids and use that
summary_logs = ContentSummaryLog.objects.filter(user=user, content_id__in=list(leaf_ids))
# add up all the progress for the logs, and divide by the total number of content nodes to get overall progress
overall_progress = (summary_logs.aggregate(Sum("progress"))["progress__sum"] or 0) / (leaf_ids.count() or 1)
return round(overall_progress, 4)
def get_ancestors(self, target_node):
"""
in descending order (root ancestor first, immediate parent last)
"""
return target_node.get_ancestors().values('pk', 'title')
def get_thumbnail(self, target_node):
thumbnail_model = target_node.files.filter(thumbnail=True, available=True).first()
return thumbnail_model.get_storage_url() if thumbnail_model else None
def _recursive_next_item(self, target_node):
if target_node.parent:
next_item = target_node.parent.get_next_sibling()
if (next_item):
return next_item
else:
if (target_node.parent == target_node.get_root()):
return None
self._recursive_next_item(target_node.parent)
else:
return None
def get_next_content(self, target_node):
next_content = target_node.get_next_sibling()
if hasattr(next_content, 'id'):
return {'kind': next_content.kind, 'id': next_content.id}
# Has no next sibling meaning reach the end of this topic.
# Return next topic or content if there is any.
next_item = self._recursive_next_item(target_node)
if next_item:
return {'kind': next_item.kind, 'id': next_item.id}
# otherwise return root.
root = target_node.get_root()
return {'kind': root.kind, 'id': root.id}
class Meta:
model = ContentNode
fields = (
'pk', 'content_id', 'title', 'description', 'kind', 'available', 'tags', 'sort_order', 'license_owner',
'license', 'files', 'ancestors', 'parent', 'thumbnail', 'progress_fraction', 'next_content', 'author'
)
|
psy0rz/zfs_autobackup | refs/heads/master | zfs_autobackup/LogStub.py | 1 | #Used for baseclasses that dont implement their own logging (Like ExecuteNode)
#Usually logging is implemented in subclasses (Like ZfsNode thats a subclass of ExecuteNode), but for regression testing its nice to have these stubs.
class LogStub:
"""Just a stub, usually overriden in subclasses."""
# simple logging stubs
def debug(self, txt):
print("DEBUG : " + txt)
def verbose(self, txt):
print("VERBOSE: " + txt)
def warning(self, txt):
print("WARNING: " + txt)
def error(self, txt):
print("ERROR : " + txt) |
gunnarku/mysql-8.0 | refs/heads/8.0 | extra/libevent/event_rpcgen.py | 159 | #!/usr/bin/env python
#
# Copyright (c) 2005 Niels Provos <provos@citi.umich.edu>
# All rights reserved.
#
# Generates marshaling code based on libevent.
import sys
import re
#
_NAME = "event_rpcgen.py"
_VERSION = "0.1"
_STRUCT_RE = '[a-z][a-z_0-9]*'
# Globals
line_count = 0
white = re.compile(r'^\s+')
cppcomment = re.compile(r'\/\/.*$')
headerdirect = []
cppdirect = []
# Holds everything that makes a struct
class Struct:
def __init__(self, name):
self._name = name
self._entries = []
self._tags = {}
print >>sys.stderr, ' Created struct: %s' % name
def AddEntry(self, entry):
if self._tags.has_key(entry.Tag()):
print >>sys.stderr, ( 'Entry "%s" duplicates tag number '
'%d from "%s" around line %d' ) % (
entry.Name(), entry.Tag(),
self._tags[entry.Tag()], line_count)
sys.exit(1)
self._entries.append(entry)
self._tags[entry.Tag()] = entry.Name()
print >>sys.stderr, ' Added entry: %s' % entry.Name()
def Name(self):
return self._name
def EntryTagName(self, entry):
"""Creates the name inside an enumeration for distinguishing data
types."""
name = "%s_%s" % (self._name, entry.Name())
return name.upper()
def PrintIdented(self, file, ident, code):
"""Takes an array, add indentation to each entry and prints it."""
for entry in code:
print >>file, '%s%s' % (ident, entry)
def PrintTags(self, file):
"""Prints the tag definitions for a structure."""
print >>file, '/* Tag definition for %s */' % self._name
print >>file, 'enum %s_ {' % self._name.lower()
for entry in self._entries:
print >>file, ' %s=%d,' % (self.EntryTagName(entry),
entry.Tag())
print >>file, ' %s_MAX_TAGS' % (self._name.upper())
print >>file, '};\n'
def PrintForwardDeclaration(self, file):
print >>file, 'struct %s;' % self._name
def PrintDeclaration(self, file):
print >>file, '/* Structure declaration for %s */' % self._name
print >>file, 'struct %s_access_ {' % self._name
for entry in self._entries:
dcl = entry.AssignDeclaration('(*%s_assign)' % entry.Name())
dcl.extend(
entry.GetDeclaration('(*%s_get)' % entry.Name()))
if entry.Array():
dcl.extend(
entry.AddDeclaration('(*%s_add)' % entry.Name()))
self.PrintIdented(file, ' ', dcl)
print >>file, '};\n'
print >>file, 'struct %s {' % self._name
print >>file, ' struct %s_access_ *base;\n' % self._name
for entry in self._entries:
dcl = entry.Declaration()
self.PrintIdented(file, ' ', dcl)
print >>file, ''
for entry in self._entries:
print >>file, ' uint8_t %s_set;' % entry.Name()
print >>file, '};\n'
print >>file, \
"""struct %(name)s *%(name)s_new(void);
void %(name)s_free(struct %(name)s *);
void %(name)s_clear(struct %(name)s *);
void %(name)s_marshal(struct evbuffer *, const struct %(name)s *);
int %(name)s_unmarshal(struct %(name)s *, struct evbuffer *);
int %(name)s_complete(struct %(name)s *);
void evtag_marshal_%(name)s(struct evbuffer *, uint32_t,
const struct %(name)s *);
int evtag_unmarshal_%(name)s(struct evbuffer *, uint32_t,
struct %(name)s *);""" % { 'name' : self._name }
# Write a setting function of every variable
for entry in self._entries:
self.PrintIdented(file, '', entry.AssignDeclaration(
entry.AssignFuncName()))
self.PrintIdented(file, '', entry.GetDeclaration(
entry.GetFuncName()))
if entry.Array():
self.PrintIdented(file, '', entry.AddDeclaration(
entry.AddFuncName()))
print >>file, '/* --- %s done --- */\n' % self._name
def PrintCode(self, file):
print >>file, ('/*\n'
' * Implementation of %s\n'
' */\n') % self._name
print >>file, \
'static struct %(name)s_access_ __%(name)s_base = {' % \
{ 'name' : self._name }
for entry in self._entries:
self.PrintIdented(file, ' ', entry.CodeBase())
print >>file, '};\n'
# Creation
print >>file, (
'struct %(name)s *\n'
'%(name)s_new(void)\n'
'{\n'
' struct %(name)s *tmp;\n'
' if ((tmp = malloc(sizeof(struct %(name)s))) == NULL) {\n'
' event_warn("%%s: malloc", __func__);\n'
' return (NULL);\n'
' }\n'
' tmp->base = &__%(name)s_base;\n') % { 'name' : self._name }
for entry in self._entries:
self.PrintIdented(file, ' ', entry.CodeNew('tmp'))
print >>file, ' tmp->%s_set = 0;\n' % entry.Name()
print >>file, (
' return (tmp);\n'
'}\n')
# Adding
for entry in self._entries:
if entry.Array():
self.PrintIdented(file, '', entry.CodeAdd())
print >>file, ''
# Assigning
for entry in self._entries:
self.PrintIdented(file, '', entry.CodeAssign())
print >>file, ''
# Getting
for entry in self._entries:
self.PrintIdented(file, '', entry.CodeGet())
print >>file, ''
# Clearing
print >>file, ( 'void\n'
'%(name)s_clear(struct %(name)s *tmp)\n'
'{'
) % { 'name' : self._name }
for entry in self._entries:
self.PrintIdented(file, ' ', entry.CodeClear('tmp'))
print >>file, '}\n'
# Freeing
print >>file, ( 'void\n'
'%(name)s_free(struct %(name)s *tmp)\n'
'{'
) % { 'name' : self._name }
for entry in self._entries:
self.PrintIdented(file, ' ', entry.CodeFree('tmp'))
print >>file, (' free(tmp);\n'
'}\n')
# Marshaling
print >>file, ('void\n'
'%(name)s_marshal(struct evbuffer *evbuf, '
'const struct %(name)s *tmp)'
'{') % { 'name' : self._name }
for entry in self._entries:
indent = ' '
# Optional entries do not have to be set
if entry.Optional():
indent += ' '
print >>file, ' if (tmp->%s_set) {' % entry.Name()
self.PrintIdented(
file, indent,
entry.CodeMarshal('evbuf', self.EntryTagName(entry), 'tmp'))
if entry.Optional():
print >>file, ' }'
print >>file, '}\n'
# Unmarshaling
print >>file, ('int\n'
'%(name)s_unmarshal(struct %(name)s *tmp, '
' struct evbuffer *evbuf)\n'
'{\n'
' uint32_t tag;\n'
' while (EVBUFFER_LENGTH(evbuf) > 0) {\n'
' if (evtag_peek(evbuf, &tag) == -1)\n'
' return (-1);\n'
' switch (tag) {\n'
) % { 'name' : self._name }
for entry in self._entries:
print >>file, ' case %s:\n' % self.EntryTagName(entry)
if not entry.Array():
print >>file, (
' if (tmp->%s_set)\n'
' return (-1);'
) % (entry.Name())
self.PrintIdented(
file, ' ',
entry.CodeUnmarshal('evbuf',
self.EntryTagName(entry), 'tmp'))
print >>file, ( ' tmp->%s_set = 1;\n' % entry.Name() +
' break;\n' )
print >>file, ( ' default:\n'
' return -1;\n'
' }\n'
' }\n' )
# Check if it was decoded completely
print >>file, ( ' if (%(name)s_complete(tmp) == -1)\n'
' return (-1);'
) % { 'name' : self._name }
# Successfully decoded
print >>file, ( ' return (0);\n'
'}\n')
# Checking if a structure has all the required data
print >>file, (
'int\n'
'%(name)s_complete(struct %(name)s *msg)\n'
'{' ) % { 'name' : self._name }
for entry in self._entries:
self.PrintIdented(
file, ' ',
entry.CodeComplete('msg'))
print >>file, (
' return (0);\n'
'}\n' )
# Complete message unmarshaling
print >>file, (
'int\n'
'evtag_unmarshal_%(name)s(struct evbuffer *evbuf, '
'uint32_t need_tag, struct %(name)s *msg)\n'
'{\n'
' uint32_t tag;\n'
' int res = -1;\n'
'\n'
' struct evbuffer *tmp = evbuffer_new();\n'
'\n'
' if (evtag_unmarshal(evbuf, &tag, tmp) == -1'
' || tag != need_tag)\n'
' goto error;\n'
'\n'
' if (%(name)s_unmarshal(msg, tmp) == -1)\n'
' goto error;\n'
'\n'
' res = 0;\n'
'\n'
' error:\n'
' evbuffer_free(tmp);\n'
' return (res);\n'
'}\n' ) % { 'name' : self._name }
# Complete message marshaling
print >>file, (
'void\n'
'evtag_marshal_%(name)s(struct evbuffer *evbuf, uint32_t tag, '
'const struct %(name)s *msg)\n'
'{\n'
' struct evbuffer *_buf = evbuffer_new();\n'
' assert(_buf != NULL);\n'
' evbuffer_drain(_buf, -1);\n'
' %(name)s_marshal(_buf, msg);\n'
' evtag_marshal(evbuf, tag, EVBUFFER_DATA(_buf), '
'EVBUFFER_LENGTH(_buf));\n'
' evbuffer_free(_buf);\n'
'}\n' ) % { 'name' : self._name }
class Entry:
def __init__(self, type, name, tag):
self._type = type
self._name = name
self._tag = int(tag)
self._ctype = type
self._optional = 0
self._can_be_array = 0
self._array = 0
self._line_count = -1
self._struct = None
self._refname = None
def GetTranslation(self):
return { "parent_name" : self._struct.Name(),
"name" : self._name,
"ctype" : self._ctype,
"refname" : self._refname
}
def SetStruct(self, struct):
self._struct = struct
def LineCount(self):
assert self._line_count != -1
return self._line_count
def SetLineCount(self, number):
self._line_count = number
def Array(self):
return self._array
def Optional(self):
return self._optional
def Tag(self):
return self._tag
def Name(self):
return self._name
def Type(self):
return self._type
def MakeArray(self, yes=1):
self._array = yes
def MakeOptional(self):
self._optional = 1
def GetFuncName(self):
return '%s_%s_get' % (self._struct.Name(), self._name)
def GetDeclaration(self, funcname):
code = [ 'int %s(struct %s *, %s *);' % (
funcname, self._struct.Name(), self._ctype ) ]
return code
def CodeGet(self):
code = (
'int',
'%(parent_name)s_%(name)s_get(struct %(parent_name)s *msg, '
'%(ctype)s *value)',
'{',
' if (msg->%(name)s_set != 1)',
' return (-1);',
' *value = msg->%(name)s_data;',
' return (0);',
'}' )
code = '\n'.join(code)
code = code % self.GetTranslation()
return code.split('\n')
def AssignFuncName(self):
return '%s_%s_assign' % (self._struct.Name(), self._name)
def AddFuncName(self):
return '%s_%s_add' % (self._struct.Name(), self._name)
def AssignDeclaration(self, funcname):
code = [ 'int %s(struct %s *, const %s);' % (
funcname, self._struct.Name(), self._ctype ) ]
return code
def CodeAssign(self):
code = [ 'int',
'%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg,'
' const %(ctype)s value)',
'{',
' msg->%(name)s_set = 1;',
' msg->%(name)s_data = value;',
' return (0);',
'}' ]
code = '\n'.join(code)
code = code % self.GetTranslation()
return code.split('\n')
def CodeClear(self, structname):
code = [ '%s->%s_set = 0;' % (structname, self.Name()) ]
return code
def CodeComplete(self, structname):
if self.Optional():
return []
code = [ 'if (!%s->%s_set)' % (structname, self.Name()),
' return (-1);' ]
return code
def CodeFree(self, name):
return []
def CodeBase(self):
code = [
'%(parent_name)s_%(name)s_assign,',
'%(parent_name)s_%(name)s_get,'
]
if self.Array():
code.append('%(parent_name)s_%(name)s_add,')
code = '\n'.join(code)
code = code % self.GetTranslation()
return code.split('\n')
def Verify(self):
if self.Array() and not self._can_be_array:
print >>sys.stderr, (
'Entry "%s" cannot be created as an array '
'around line %d' ) % (self._name, self.LineCount())
sys.exit(1)
if not self._struct:
print >>sys.stderr, (
'Entry "%s" does not know which struct it belongs to '
'around line %d' ) % (self._name, self.LineCount())
sys.exit(1)
if self._optional and self._array:
print >>sys.stderr, ( 'Entry "%s" has illegal combination of '
'optional and array around line %d' ) % (
self._name, self.LineCount() )
sys.exit(1)
class EntryBytes(Entry):
def __init__(self, type, name, tag, length):
# Init base class
Entry.__init__(self, type, name, tag)
self._length = length
self._ctype = 'uint8_t'
def GetDeclaration(self, funcname):
code = [ 'int %s(struct %s *, %s **);' % (
funcname, self._struct.Name(), self._ctype ) ]
return code
def AssignDeclaration(self, funcname):
code = [ 'int %s(struct %s *, const %s *);' % (
funcname, self._struct.Name(), self._ctype ) ]
return code
def Declaration(self):
dcl = ['uint8_t %s_data[%s];' % (self._name, self._length)]
return dcl
def CodeGet(self):
name = self._name
code = [ 'int',
'%s_%s_get(struct %s *msg, %s **value)' % (
self._struct.Name(), name,
self._struct.Name(), self._ctype),
'{',
' if (msg->%s_set != 1)' % name,
' return (-1);',
' *value = msg->%s_data;' % name,
' return (0);',
'}' ]
return code
def CodeAssign(self):
name = self._name
code = [ 'int',
'%s_%s_assign(struct %s *msg, const %s *value)' % (
self._struct.Name(), name,
self._struct.Name(), self._ctype),
'{',
' msg->%s_set = 1;' % name,
' memcpy(msg->%s_data, value, %s);' % (
name, self._length),
' return (0);',
'}' ]
return code
def CodeUnmarshal(self, buf, tag_name, var_name):
code = [ 'if (evtag_unmarshal_fixed(%s, %s, ' % (buf, tag_name) +
'%s->%s_data, ' % (var_name, self._name) +
'sizeof(%s->%s_data)) == -1) {' % (
var_name, self._name),
' event_warnx("%%s: failed to unmarshal %s", __func__);' % (
self._name ),
' return (-1);',
'}'
]
return code
def CodeMarshal(self, buf, tag_name, var_name):
code = ['evtag_marshal(%s, %s, %s->%s_data, sizeof(%s->%s_data));' % (
buf, tag_name, var_name, self._name, var_name, self._name )]
return code
def CodeClear(self, structname):
code = [ '%s->%s_set = 0;' % (structname, self.Name()),
'memset(%s->%s_data, 0, sizeof(%s->%s_data));' % (
structname, self._name, structname, self._name)]
return code
def CodeNew(self, name):
code = ['memset(%s->%s_data, 0, sizeof(%s->%s_data));' % (
name, self._name, name, self._name)]
return code
def Verify(self):
if not self._length:
print >>sys.stderr, 'Entry "%s" needs a length around line %d' % (
self._name, self.LineCount() )
sys.exit(1)
Entry.Verify(self)
class EntryInt(Entry):
def __init__(self, type, name, tag):
# Init base class
Entry.__init__(self, type, name, tag)
self._ctype = 'uint32_t'
def CodeUnmarshal(self, buf, tag_name, var_name):
code = ['if (evtag_unmarshal_int(%s, %s, &%s->%s_data) == -1) {' % (
buf, tag_name, var_name, self._name),
' event_warnx("%%s: failed to unmarshal %s", __func__);' % (
self._name ),
' return (-1);',
'}' ]
return code
def CodeMarshal(self, buf, tag_name, var_name):
code = ['evtag_marshal_int(%s, %s, %s->%s_data);' % (
buf, tag_name, var_name, self._name)]
return code
def Declaration(self):
dcl = ['uint32_t %s_data;' % self._name]
return dcl
def CodeNew(self, name):
code = ['%s->%s_data = 0;' % (name, self._name)]
return code
class EntryString(Entry):
def __init__(self, type, name, tag):
# Init base class
Entry.__init__(self, type, name, tag)
self._ctype = 'char *'
def CodeAssign(self):
name = self._name
code = """int
%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg,
const %(ctype)s value)
{
if (msg->%(name)s_data != NULL)
free(msg->%(name)s_data);
if ((msg->%(name)s_data = strdup(value)) == NULL)
return (-1);
msg->%(name)s_set = 1;
return (0);
}""" % self.GetTranslation()
return code.split('\n')
def CodeUnmarshal(self, buf, tag_name, var_name):
code = ['if (evtag_unmarshal_string(%s, %s, &%s->%s_data) == -1) {' % (
buf, tag_name, var_name, self._name),
' event_warnx("%%s: failed to unmarshal %s", __func__);' % (
self._name ),
' return (-1);',
'}'
]
return code
def CodeMarshal(self, buf, tag_name, var_name):
code = ['evtag_marshal_string(%s, %s, %s->%s_data);' % (
buf, tag_name, var_name, self._name)]
return code
def CodeClear(self, structname):
code = [ 'if (%s->%s_set == 1) {' % (structname, self.Name()),
' free (%s->%s_data);' % (structname, self.Name()),
' %s->%s_data = NULL;' % (structname, self.Name()),
' %s->%s_set = 0;' % (structname, self.Name()),
'}'
]
return code
def CodeNew(self, name):
code = ['%s->%s_data = NULL;' % (name, self._name)]
return code
def CodeFree(self, name):
code = ['if (%s->%s_data != NULL)' % (name, self._name),
' free (%s->%s_data); ' % (name, self._name)]
return code
def Declaration(self):
dcl = ['char *%s_data;' % self._name]
return dcl
class EntryStruct(Entry):
def __init__(self, type, name, tag, refname):
# Init base class
Entry.__init__(self, type, name, tag)
self._can_be_array = 1
self._refname = refname
self._ctype = 'struct %s*' % refname
def CodeGet(self):
name = self._name
code = [ 'int',
'%s_%s_get(struct %s *msg, %s *value)' % (
self._struct.Name(), name,
self._struct.Name(), self._ctype),
'{',
' if (msg->%s_set != 1) {' % name,
' msg->%s_data = %s_new();' % (name, self._refname),
' if (msg->%s_data == NULL)' % name,
' return (-1);',
' msg->%s_set = 1;' % name,
' }',
' *value = msg->%s_data;' % name,
' return (0);',
'}' ]
return code
def CodeAssign(self):
name = self._name
code = """int
%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg,
const %(ctype)s value)
{
struct evbuffer *tmp = NULL;
if (msg->%(name)s_set) {
%(refname)s_clear(msg->%(name)s_data);
msg->%(name)s_set = 0;
} else {
msg->%(name)s_data = %(refname)s_new();
if (msg->%(name)s_data == NULL) {
event_warn("%%s: %(refname)s_new()", __func__);
goto error;
}
}
if ((tmp = evbuffer_new()) == NULL) {
event_warn("%%s: evbuffer_new()", __func__);
goto error;
}
%(refname)s_marshal(tmp, value);
if (%(refname)s_unmarshal(msg->%(name)s_data, tmp) == -1) {
event_warnx("%%s: %(refname)s_unmarshal", __func__);
goto error;
}
msg->%(name)s_set = 1;
evbuffer_free(tmp);
return (0);
error:
if (tmp != NULL)
evbuffer_free(tmp);
if (msg->%(name)s_data != NULL) {
%(refname)s_free(msg->%(name)s_data);
msg->%(name)s_data = NULL;
}
return (-1);
}""" % self.GetTranslation()
return code.split('\n')
def CodeComplete(self, structname):
if self.Optional():
code = [ 'if (%s->%s_set && %s_complete(%s->%s_data) == -1)' % (
structname, self.Name(),
self._refname, structname, self.Name()),
' return (-1);' ]
else:
code = [ 'if (%s_complete(%s->%s_data) == -1)' % (
self._refname, structname, self.Name()),
' return (-1);' ]
return code
def CodeUnmarshal(self, buf, tag_name, var_name):
code = ['%s->%s_data = %s_new();' % (
var_name, self._name, self._refname),
'if (%s->%s_data == NULL)' % (var_name, self._name),
' return (-1);',
'if (evtag_unmarshal_%s(%s, %s, %s->%s_data) == -1) {' % (
self._refname, buf, tag_name, var_name, self._name),
' event_warnx("%%s: failed to unmarshal %s", __func__);' % (
self._name ),
' return (-1);',
'}'
]
return code
def CodeMarshal(self, buf, tag_name, var_name):
code = ['evtag_marshal_%s(%s, %s, %s->%s_data);' % (
self._refname, buf, tag_name, var_name, self._name)]
return code
def CodeClear(self, structname):
code = [ 'if (%s->%s_set == 1) {' % (structname, self.Name()),
' %s_free(%s->%s_data);' % (
self._refname, structname, self.Name()),
' %s->%s_data = NULL;' % (structname, self.Name()),
' %s->%s_set = 0;' % (structname, self.Name()),
'}'
]
return code
def CodeNew(self, name):
code = ['%s->%s_data = NULL;' % (name, self._name)]
return code
def CodeFree(self, name):
code = ['if (%s->%s_data != NULL)' % (name, self._name),
' %s_free(%s->%s_data); ' % (
self._refname, name, self._name)]
return code
def Declaration(self):
dcl = ['%s %s_data;' % (self._ctype, self._name)]
return dcl
class EntryVarBytes(Entry):
def __init__(self, type, name, tag):
# Init base class
Entry.__init__(self, type, name, tag)
self._ctype = 'uint8_t *'
def GetDeclaration(self, funcname):
code = [ 'int %s(struct %s *, %s *, uint32_t *);' % (
funcname, self._struct.Name(), self._ctype ) ]
return code
def AssignDeclaration(self, funcname):
code = [ 'int %s(struct %s *, const %s, uint32_t);' % (
funcname, self._struct.Name(), self._ctype ) ]
return code
def CodeAssign(self):
name = self._name
code = [ 'int',
'%s_%s_assign(struct %s *msg, '
'const %s value, uint32_t len)' % (
self._struct.Name(), name,
self._struct.Name(), self._ctype),
'{',
' if (msg->%s_data != NULL)' % name,
' free (msg->%s_data);' % name,
' msg->%s_data = malloc(len);' % name,
' if (msg->%s_data == NULL)' % name,
' return (-1);',
' msg->%s_set = 1;' % name,
' msg->%s_length = len;' % name,
' memcpy(msg->%s_data, value, len);' % name,
' return (0);',
'}' ]
return code
def CodeGet(self):
name = self._name
code = [ 'int',
'%s_%s_get(struct %s *msg, %s *value, uint32_t *plen)' % (
self._struct.Name(), name,
self._struct.Name(), self._ctype),
'{',
' if (msg->%s_set != 1)' % name,
' return (-1);',
' *value = msg->%s_data;' % name,
' *plen = msg->%s_length;' % name,
' return (0);',
'}' ]
return code
def CodeUnmarshal(self, buf, tag_name, var_name):
code = ['if (evtag_payload_length(%s, &%s->%s_length) == -1)' % (
buf, var_name, self._name),
' return (-1);',
# We do not want DoS opportunities
'if (%s->%s_length > EVBUFFER_LENGTH(%s))' % (
var_name, self._name, buf),
' return (-1);',
'if ((%s->%s_data = malloc(%s->%s_length)) == NULL)' % (
var_name, self._name, var_name, self._name),
' return (-1);',
'if (evtag_unmarshal_fixed(%s, %s, %s->%s_data, '
'%s->%s_length) == -1) {' % (
buf, tag_name, var_name, self._name, var_name, self._name),
' event_warnx("%%s: failed to unmarshal %s", __func__);' % (
self._name ),
' return (-1);',
'}'
]
return code
def CodeMarshal(self, buf, tag_name, var_name):
code = ['evtag_marshal(%s, %s, %s->%s_data, %s->%s_length);' % (
buf, tag_name, var_name, self._name, var_name, self._name)]
return code
def CodeClear(self, structname):
code = [ 'if (%s->%s_set == 1) {' % (structname, self.Name()),
' free (%s->%s_data);' % (structname, self.Name()),
' %s->%s_data = NULL;' % (structname, self.Name()),
' %s->%s_length = 0;' % (structname, self.Name()),
' %s->%s_set = 0;' % (structname, self.Name()),
'}'
]
return code
def CodeNew(self, name):
code = ['%s->%s_data = NULL;' % (name, self._name),
'%s->%s_length = 0;' % (name, self._name) ]
return code
def CodeFree(self, name):
code = ['if (%s->%s_data != NULL)' % (name, self._name),
' free (%s->%s_data); ' % (name, self._name)]
return code
def Declaration(self):
dcl = ['uint8_t *%s_data;' % self._name,
'uint32_t %s_length;' % self._name]
return dcl
class EntryArray(Entry):
def __init__(self, entry):
# Init base class
Entry.__init__(self, entry._type, entry._name, entry._tag)
self._entry = entry
self._refname = entry._refname
self._ctype = 'struct %s *' % self._refname
def GetDeclaration(self, funcname):
"""Allows direct access to elements of the array."""
translate = self.GetTranslation()
translate["funcname"] = funcname
code = [
'int %(funcname)s(struct %(parent_name)s *, int, %(ctype)s *);' %
translate ]
return code
def AssignDeclaration(self, funcname):
code = [ 'int %s(struct %s *, int, const %s);' % (
funcname, self._struct.Name(), self._ctype ) ]
return code
def AddDeclaration(self, funcname):
code = [ '%s %s(struct %s *);' % (
self._ctype, funcname, self._struct.Name() ) ]
return code
def CodeGet(self):
code = """int
%(parent_name)s_%(name)s_get(struct %(parent_name)s *msg, int offset,
%(ctype)s *value)
{
if (!msg->%(name)s_set || offset < 0 || offset >= msg->%(name)s_length)
return (-1);
*value = msg->%(name)s_data[offset];
return (0);
}""" % self.GetTranslation()
return code.split('\n')
def CodeAssign(self):
code = """int
%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg, int off,
const %(ctype)s value)
{
struct evbuffer *tmp = NULL;
if (!msg->%(name)s_set || off < 0 || off >= msg->%(name)s_length)
return (-1);
%(refname)s_clear(msg->%(name)s_data[off]);
if ((tmp = evbuffer_new()) == NULL) {
event_warn("%%s: evbuffer_new()", __func__);
goto error;
}
%(refname)s_marshal(tmp, value);
if (%(refname)s_unmarshal(msg->%(name)s_data[off], tmp) == -1) {
event_warnx("%%s: %(refname)s_unmarshal", __func__);
goto error;
}
evbuffer_free(tmp);
return (0);
error:
if (tmp != NULL)
evbuffer_free(tmp);
%(refname)s_clear(msg->%(name)s_data[off]);
return (-1);
}""" % self.GetTranslation()
return code.split('\n')
def CodeAdd(self):
code = \
"""%(ctype)s
%(parent_name)s_%(name)s_add(struct %(parent_name)s *msg)
{
if (++msg->%(name)s_length >= msg->%(name)s_num_allocated) {
int tobe_allocated = msg->%(name)s_num_allocated;
%(ctype)s* new_data = NULL;
tobe_allocated = !tobe_allocated ? 1 : tobe_allocated << 1;
new_data = (%(ctype)s*) realloc(msg->%(name)s_data,
tobe_allocated * sizeof(%(ctype)s));
if (new_data == NULL)
goto error;
msg->%(name)s_data = new_data;
msg->%(name)s_num_allocated = tobe_allocated;
}
msg->%(name)s_data[msg->%(name)s_length - 1] = %(refname)s_new();
if (msg->%(name)s_data[msg->%(name)s_length - 1] == NULL)
goto error;
msg->%(name)s_set = 1;
return (msg->%(name)s_data[msg->%(name)s_length - 1]);
error:
--msg->%(name)s_length;
return (NULL);
}
""" % self.GetTranslation()
return code.split('\n')
def CodeComplete(self, structname):
code = []
translate = self.GetTranslation()
if self.Optional():
code.append( 'if (%(structname)s->%(name)s_set)' % translate)
translate["structname"] = structname
tmp = """{
int i;
for (i = 0; i < %(structname)s->%(name)s_length; ++i) {
if (%(refname)s_complete(%(structname)s->%(name)s_data[i]) == -1)
return (-1);
}
}""" % translate
code.extend(tmp.split('\n'))
return code
def CodeUnmarshal(self, buf, tag_name, var_name):
translate = self.GetTranslation()
translate["var_name"] = var_name
translate["buf"] = buf
translate["tag_name"] = tag_name
code = """if (%(parent_name)s_%(name)s_add(%(var_name)s) == NULL)
return (-1);
if (evtag_unmarshal_%(refname)s(%(buf)s, %(tag_name)s,
%(var_name)s->%(name)s_data[%(var_name)s->%(name)s_length - 1]) == -1) {
--%(var_name)s->%(name)s_length;
event_warnx("%%s: failed to unmarshal %(name)s", __func__);
return (-1);
}""" % translate
return code.split('\n')
def CodeMarshal(self, buf, tag_name, var_name):
code = ['{',
' int i;',
' for (i = 0; i < %s->%s_length; ++i) {' % (
var_name, self._name),
' evtag_marshal_%s(%s, %s, %s->%s_data[i]);' % (
self._refname, buf, tag_name, var_name, self._name),
' }',
'}'
]
return code
def CodeClear(self, structname):
code = [ 'if (%s->%s_set == 1) {' % (structname, self.Name()),
' int i;',
' for (i = 0; i < %s->%s_length; ++i) {' % (
structname, self.Name()),
' %s_free(%s->%s_data[i]);' % (
self._refname, structname, self.Name()),
' }',
' free(%s->%s_data);' % (structname, self.Name()),
' %s->%s_data = NULL;' % (structname, self.Name()),
' %s->%s_set = 0;' % (structname, self.Name()),
' %s->%s_length = 0;' % (structname, self.Name()),
' %s->%s_num_allocated = 0;' % (structname, self.Name()),
'}'
]
return code
def CodeNew(self, name):
code = ['%s->%s_data = NULL;' % (name, self._name),
'%s->%s_length = 0;' % (name, self._name),
'%s->%s_num_allocated = 0;' % (name, self._name)]
return code
def CodeFree(self, name):
code = ['if (%s->%s_data != NULL) {' % (name, self._name),
' int i;',
' for (i = 0; i < %s->%s_length; ++i) {' % (
name, self._name),
' %s_free(%s->%s_data[i]); ' % (
self._refname, name, self._name),
' %s->%s_data[i] = NULL;' % (name, self._name),
' }',
' free(%s->%s_data);' % (name, self._name),
' %s->%s_data = NULL;' % (name, self._name),
' %s->%s_length = 0;' % (name, self._name),
' %s->%s_num_allocated = 0;' % (name, self._name),
'}'
]
return code
def Declaration(self):
dcl = ['struct %s **%s_data;' % (self._refname, self._name),
'int %s_length;' % self._name,
'int %s_num_allocated;' % self._name ]
return dcl
def NormalizeLine(line):
global white
global cppcomment
line = cppcomment.sub('', line)
line = line.strip()
line = white.sub(' ', line)
return line
def ProcessOneEntry(newstruct, entry):
optional = 0
array = 0
entry_type = ''
name = ''
tag = ''
tag_set = None
separator = ''
fixed_length = ''
tokens = entry.split(' ')
while tokens:
token = tokens[0]
tokens = tokens[1:]
if not entry_type:
if not optional and token == 'optional':
optional = 1
continue
if not array and token == 'array':
array = 1
continue
if not entry_type:
entry_type = token
continue
if not name:
res = re.match(r'^([^\[\]]+)(\[.*\])?$', token)
if not res:
print >>sys.stderr, 'Cannot parse name: \"%s\" around %d' % (
entry, line_count)
sys.exit(1)
name = res.group(1)
fixed_length = res.group(2)
if fixed_length:
fixed_length = fixed_length[1:-1]
continue
if not separator:
separator = token
if separator != '=':
print >>sys.stderr, 'Expected "=" after name \"%s\" got %s' % (
name, token)
sys.exit(1)
continue
if not tag_set:
tag_set = 1
if not re.match(r'^(0x)?[0-9]+$', token):
print >>sys.stderr, 'Expected tag number: \"%s\"' % entry
sys.exit(1)
tag = int(token, 0)
continue
print >>sys.stderr, 'Cannot parse \"%s\"' % entry
sys.exit(1)
if not tag_set:
print >>sys.stderr, 'Need tag number: \"%s\"' % entry
sys.exit(1)
# Create the right entry
if entry_type == 'bytes':
if fixed_length:
newentry = EntryBytes(entry_type, name, tag, fixed_length)
else:
newentry = EntryVarBytes(entry_type, name, tag)
elif entry_type == 'int' and not fixed_length:
newentry = EntryInt(entry_type, name, tag)
elif entry_type == 'string' and not fixed_length:
newentry = EntryString(entry_type, name, tag)
else:
res = re.match(r'^struct\[(%s)\]$' % _STRUCT_RE,
entry_type, re.IGNORECASE)
if res:
# References another struct defined in our file
newentry = EntryStruct(entry_type, name, tag, res.group(1))
else:
print >>sys.stderr, 'Bad type: "%s" in "%s"' % (entry_type, entry)
sys.exit(1)
structs = []
if optional:
newentry.MakeOptional()
if array:
newentry.MakeArray()
newentry.SetStruct(newstruct)
newentry.SetLineCount(line_count)
newentry.Verify()
if array:
# We need to encapsulate this entry into a struct
newname = newentry.Name()+ '_array'
# Now borgify the new entry.
newentry = EntryArray(newentry)
newentry.SetStruct(newstruct)
newentry.SetLineCount(line_count)
newentry.MakeArray()
newstruct.AddEntry(newentry)
return structs
def ProcessStruct(data):
tokens = data.split(' ')
# First three tokens are: 'struct' 'name' '{'
newstruct = Struct(tokens[1])
inside = ' '.join(tokens[3:-1])
tokens = inside.split(';')
structs = []
for entry in tokens:
entry = NormalizeLine(entry)
if not entry:
continue
# It's possible that new structs get defined in here
structs.extend(ProcessOneEntry(newstruct, entry))
structs.append(newstruct)
return structs
def GetNextStruct(file):
global line_count
global cppdirect
got_struct = 0
processed_lines = []
have_c_comment = 0
data = ''
while 1:
line = file.readline()
if not line:
break
line_count += 1
line = line[:-1]
if not have_c_comment and re.search(r'/\*', line):
if re.search(r'/\*.*\*/', line):
line = re.sub(r'/\*.*\*/', '', line)
else:
line = re.sub(r'/\*.*$', '', line)
have_c_comment = 1
if have_c_comment:
if not re.search(r'\*/', line):
continue
have_c_comment = 0
line = re.sub(r'^.*\*/', '', line)
line = NormalizeLine(line)
if not line:
continue
if not got_struct:
if re.match(r'#include ["<].*[>"]', line):
cppdirect.append(line)
continue
if re.match(r'^#(if( |def)|endif)', line):
cppdirect.append(line)
continue
if re.match(r'^#define', line):
headerdirect.append(line)
continue
if not re.match(r'^struct %s {$' % _STRUCT_RE,
line, re.IGNORECASE):
print >>sys.stderr, 'Missing struct on line %d: %s' % (
line_count, line)
sys.exit(1)
else:
got_struct = 1
data += line
continue
# We are inside the struct
tokens = line.split('}')
if len(tokens) == 1:
data += ' ' + line
continue
if len(tokens[1]):
print >>sys.stderr, 'Trailing garbage after struct on line %d' % (
line_count )
sys.exit(1)
# We found the end of the struct
data += ' %s}' % tokens[0]
break
# Remove any comments, that might be in there
data = re.sub(r'/\*.*\*/', '', data)
return data
def Parse(file):
"""
Parses the input file and returns C code and corresponding header file.
"""
entities = []
while 1:
# Just gets the whole struct nicely formatted
data = GetNextStruct(file)
if not data:
break
entities.extend(ProcessStruct(data))
return entities
def GuardName(name):
name = '_'.join(name.split('.'))
name = '_'.join(name.split('/'))
guard = '_'+name.upper()+'_'
return guard
def HeaderPreamble(name):
guard = GuardName(name)
pre = (
'/*\n'
' * Automatically generated from %s\n'
' */\n\n'
'#ifndef %s\n'
'#define %s\n\n' ) % (
name, guard, guard)
# insert stdint.h - let's hope everyone has it
pre += (
'#include <event-config.h>\n'
'#ifdef _EVENT_HAVE_STDINT_H\n'
'#include <stdint.h>\n'
'#endif\n' )
for statement in headerdirect:
pre += '%s\n' % statement
if headerdirect:
pre += '\n'
pre += (
'#define EVTAG_HAS(msg, member) ((msg)->member##_set == 1)\n'
'#ifdef __GNUC__\n'
'#define EVTAG_ASSIGN(msg, member, args...) '
'(*(msg)->base->member##_assign)(msg, ## args)\n'
'#define EVTAG_GET(msg, member, args...) '
'(*(msg)->base->member##_get)(msg, ## args)\n'
'#else\n'
'#define EVTAG_ASSIGN(msg, member, ...) '
'(*(msg)->base->member##_assign)(msg, ## __VA_ARGS__)\n'
'#define EVTAG_GET(msg, member, ...) '
'(*(msg)->base->member##_get)(msg, ## __VA_ARGS__)\n'
'#endif\n'
'#define EVTAG_ADD(msg, member) (*(msg)->base->member##_add)(msg)\n'
'#define EVTAG_LEN(msg, member) ((msg)->member##_length)\n'
)
return pre
def HeaderPostamble(name):
guard = GuardName(name)
return '#endif /* %s */' % guard
def BodyPreamble(name):
global _NAME
global _VERSION
header_file = '.'.join(name.split('.')[:-1]) + '.gen.h'
pre = ( '/*\n'
' * Automatically generated from %s\n'
' * by %s/%s. DO NOT EDIT THIS FILE.\n'
' */\n\n' ) % (name, _NAME, _VERSION)
pre += ( '#include <sys/types.h>\n'
'#include <sys/time.h>\n'
'#include <stdlib.h>\n'
'#include <string.h>\n'
'#include <assert.h>\n'
'#include <event.h>\n\n' )
for statement in cppdirect:
pre += '%s\n' % statement
pre += '\n#include "%s"\n\n' % header_file
pre += 'void event_err(int eval, const char *fmt, ...);\n'
pre += 'void event_warn(const char *fmt, ...);\n'
pre += 'void event_errx(int eval, const char *fmt, ...);\n'
pre += 'void event_warnx(const char *fmt, ...);\n\n'
return pre
def main(argv):
if len(argv) < 2 or not argv[1]:
print >>sys.stderr, 'Need RPC description file as first argument.'
sys.exit(1)
filename = argv[1]
ext = filename.split('.')[-1]
if ext != 'rpc':
print >>sys.stderr, 'Unrecognized file extension: %s' % ext
sys.exit(1)
print >>sys.stderr, 'Reading \"%s\"' % filename
fp = open(filename, 'r')
entities = Parse(fp)
fp.close()
header_file = '.'.join(filename.split('.')[:-1]) + '.gen.h'
impl_file = '.'.join(filename.split('.')[:-1]) + '.gen.c'
print >>sys.stderr, '... creating "%s"' % header_file
header_fp = open(header_file, 'w')
print >>header_fp, HeaderPreamble(filename)
# Create forward declarations: allows other structs to reference
# each other
for entry in entities:
entry.PrintForwardDeclaration(header_fp)
print >>header_fp, ''
for entry in entities:
entry.PrintTags(header_fp)
entry.PrintDeclaration(header_fp)
print >>header_fp, HeaderPostamble(filename)
header_fp.close()
print >>sys.stderr, '... creating "%s"' % impl_file
impl_fp = open(impl_file, 'w')
print >>impl_fp, BodyPreamble(filename)
for entry in entities:
entry.PrintCode(impl_fp)
impl_fp.close()
if __name__ == '__main__':
main(sys.argv)
|
fmeynadier/scidavis | refs/heads/master | scidavis/scidavisrc.py | 1 | ############################################################################
# #
# File : scidavisrc.py #
# Project : SciDAVis #
# Description : default configuration file of SciDAVis' Python #
# environment #
# Copyright : (C) 2006-2009 Knut Franke (knut.franke*gmx.de) #
# (C) 2007 Ion Vasilief (ion_vasilief*yahoo.fr) #
# (C) 2008 Tilman Benkert (thzs*gmx.net) #
# (replace * with @ in the email address) #
# #
############################################################################
# #
# This program is free software; you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation; either version 2 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 51 Franklin Street, Fifth Floor, #
# Boston, MA 02110-1301 USA #
# #
############################################################################
import __main__
def import_to_global(modname, attrs=None, math=False):
"""
import_to_global(modname, (a,b,c,...), math): like "from modname import a,b,c,...",
but imports to global namespace (__main__).
If math==True, also registers functions with SciDAVis' math function list.
"""
mod = __import__(modname)
for submod in modname.split(".")[1:]:
mod = getattr(mod, submod)
if attrs==None: attrs=dir(mod)
for name in attrs:
f = getattr(mod, name)
setattr(__main__, name, f)
# make functions available in SciDAVis' math function list
if math and callable(f): __main__.scidavis.mathFunctions[name] = f
# Import standard math functions and constants into global namespace.
import_to_global("math", None, True)
# Import selected parts of scipy.special (if available) into global namespace.
# See www.scipy.org for information on SciPy and how to get it.
have_scipy = False
try:
special_functions = [
# Airy Functions
"airy", "airye", "ai_zeros", "bi_zeros",
# Elliptic Functions and Integrals
"ellipj", "ellipk", "ellipkinc", "ellipe", "ellipeinc",
# Bessel Functions
"jn", "jv", "jve",
"yn", "yv", "yve",
"kn", "kv", "kve",
"iv", "ive",
"hankel1", "hankel1e", "hankel2", "hankel2e",
"lmbda",
"jnjnp_zeros", "jnyn_zeros",
"jn_zeros", "jnp_zeros",
"yn_zeros", "ynp_zeros",
"y0_zeros", "y1_zeros", "y1p_zeros",
"j0", "j1", "y0", "y1", "i0", "i0e", "i1", "i1e", "k0", "k0e", "k1", "k1e",
# Integrals of Bessel Functions
"itj0y0", "it2j0y0", "iti0k0", "it2i0k0", "besselpoly",
# Derivatives of Bessel Functions
"jvp", "yvp", "kvp", "ivp", "h1vp", "h2vp",
# Spherical Bessel Functions
"sph_jn", "sph_yn", "sph_jnyn", "sph_in", "sph_kn", "sph_inkn",
# Ricatti-Bessel Functions
"riccati_jn", "riccati_yn",
# Struve Functions
"struve", "modstruve", "itstruve0", "it2struve0", "itmodstruve0",
# Gamma and Related Functions
"gamma", "gammaln", "gammainc", "gammaincinv", "gammaincc", "gammainccinv",
"beta", "betaln", "betainc", "betaincinv",
"psi", "rgamma", "polygamma",
# Error Function and Fresnel Integrals
"erf", "erfc", "erfinv", "erfcinv", "erf_zeros",
"fresnel", "fresnel_zeros", "fresnelc_zeros", "fresnels_zeros", "modfresnelp", "modfresnelm",
# Legendre Functions
"lpn", "lqn", "lpmn", "lqmn", "lpmv", "sph_harm",
# Orthogonal polynomials
"legendre", "sh_legendre",
"chebyt", "chebyu", "chebyc", "chebys", "sh_chebyt", "sh_chebyu",
"jacobi", "sh_jacobi",
"laguerre", "genlaguerre",
"hermite", "hermitenorm",
"gegenbauer",
# HyperGeometric Functions
"hyp2f1",
"hyp1f1", "hyperu", "hyp0f1",
"hyp2f0", "hyp1f2", "hyp3f0",
# Parabolic Cylinder Functions
"pbdv", "pbvv", "pbwa", "pbdv_seq", "pbvv_seq", "pbdn_seq",
# Mathieu and related Functions (and derivatives)
"mathieu_a", "mathieu_b", "mathieu_even_coef", "mathieu_odd_coef",
"mathieu_cem", "mathieu_sem", "mathieu_modcem1", "mathieu_modcem2", "mathieu_modsem1", "mathieu_modsem2",
# Spheroidal Wave Functions
"pro_ang1", "pro_rad1", "pro_rad2",
"obl_ang1", "obl_rad1", "obl_rad2",
"pro_cv", "obl_cv", "pro_cv_seq", "obl_cv_seq",
"pro_ang1_cv", "pro_rad1_cv", "pro_rad2_cv",
"obl_ang1_cv", "obl_rad1_cv", "obl_rad2_cv",
# Kelvin Functions
"kelvin", "kelvin_zeros",
"ber", "bei", "berp", "beip", "ker", "kei", "kerp", "keip",
"ber_zeros", "bei_zeros", "berp_zeros", "beip_zeros", "ker_zeros", "kei_zeros", "kerp_zeros", "keip_zeros",
# Other Special Functions
"expn", "exp1", "expi",
"wofz", "dawsn",
"shichi", "sici", "spence",
"zeta", "zetac",
# Convenience Functions
"cbrt", "exp10", "exp2",
"radian", "cosdg", "sindg", "tandg", "cotdg",
"log1p", "expm1", "cosm1",
"round",
]
import_to_global("scipy.special", special_functions, True)
have_scipy = True
print("Loaded %d special functions from scipy.special." % len(special_functions))
except(ImportError): pass
# Import selected parts of pygsl.sf (if available) into global namespace.
# See pygsl.sourceforge.net for information on pygsl and how to get it.
try:
# special functions not defined in SciPy
special_functions = [
# Restriction functions
"angle_restrict_pos_err", "angle_restrict_symm_err",
# Gamma and Related Functions
"choose", "fact", "doublefact",
"gammastar", "gammainv",
"lnfact", "lndoublefact",
"poch", "pochrel", "lnpoch", "lnpoch_sgn",
"psi_1_int", "psi_1piy", "psi_int", "psi_n",
# Fermi-Dirac integrals
"fermi_dirac_0", "fermi_dirac_half", "fermi_dirac_1",
"fermi_dirac_3half", "fermi_dirac_2",
"fermi_dirac_inc_0", "fermi_dirac_int", "fermi_dirac_m1",
"fermi_dirac_mhalf",
# Elliptic Functions and Integrals
"ellint_D", "ellint_F",
"ellint_RC", "ellint_RD", "ellint_RF", "ellint_RJ",
"elljac",
# Error Function and Fresnel Integrals
"log_erfc",
# Other Integrals
"atanint",
"expint_3", "expint_E1", "expint_E2", "expint_Ei",
# Legendre Functions and Spherical Harmonics
"conicalP_0", "conicalP_1", "conicalP_half", "conicalP_mhalf",
"conicalP_sph_reg", "conicalP_cyl_reg",
"legendre_H3d", "legendre_H3d_0", "legendre_H3d_1",
"legendre_Q0", "legendre_Q1", "legendre_Ql",
"legendre_sphPlm",
# Coulomb Functions
"hydrogenicR", "hydrogenicR_1",
"coulomb_CL", "coulomb_wave_FG",
# Lambert's W function
"lambert_W0", "lambert_Wm1",
# Synchrotron functions
"synchrotron_1", "synchrotron_2",
# Transport functions
"transport_2", "transport_3", "transport_4", "transport_5",
# Clausen function
"clausen",
# Coupling coefficients
"coupling_3j", "coupling_6j", "coupling_9j",
# Debye functions
"debye_1", "debye_2", "debye_3", "debye_4",
# Dilogarithm
"dilog",
# Zeta Functions
"eta", "eta_int",
"hzeta", "zeta_int",
# HyperGeometric Functions
"hyperg_1F1_int",
"hyperg_2F1_conj", "hyperg_2F1_conj_renorm", "hyperg_2F1_renorm",
"hyperg_U_e10", "hyperg_U_int", "hyperg_U_int_e10",
# Trigonometric Functions
"hypot", "sinc",
"lnsinh", "lncosh",
# Other Special Functions
"log_abs", "taylorcoeff",
]
# special functions also defined in SciPy
special_functions_doublets = [
# Airy functions
"airy_Ai", "airy_Ai_deriv", "airy_Ai_scaled", "airy_Ai_deriv_scaled",
"airy_Bi", "airy_Bi_deriv", "airy_Bi_scaled", "airy_Bi_deriv_scaled",
"airy_zero_Ai", "airy_zero_Ai_deriv", "airy_zero_Bi", "airy_zero_Bi_deriv",
# Bessel functions
"bessel_I0", "bessel_I1", "bessel_In", "bessel_Inu",
"bessel_I0_scaled", "bessel_I1_scaled", "bessel_In_scaled", "bessel_Inu_scaled",
"bessel_J0", "bessel_J1", "bessel_Jn", "bessel_Jnu",
"bessel_K0", "bessel_K1", "bessel_Kn", "bessel_Knu",
"bessel_K0_scaled", "bessel_K1_scaled", "bessel_Kn_scaled", "bessel_Knu_scaled",
"bessel_Y0", "bessel_Y1", "bessel_Yn", "bessel_Ynu",
"bessel_i0_scaled", "bessel_i1_scaled", "bessel_i2_scaled", "bessel_il_scaled",
"bessel_j0", "bessel_j1", "bessel_j2", "bessel_jl",
"bessel_k0_scaled", "bessel_k1_scaled", "bessel_k2_scaled", "bessel_kl_scaled",
"bessel_y0", "bessel_y1", "bessel_y2", "bessel_yl",
"bessel_lnKnu",
"bessel_zero_J0", "bessel_zero_J1", "bessel_zero_Jnu",
# Gamma and Related Functions
"beta", "beta_inc",
"gamma", "gamma_inc_P", "gamma_inc_Q",
"lnbeta", "lngamma",
"psi",
# Elliptic Functions and Integrals
"ellint_E", "ellint_Ecomp", "ellint_Kcomp", "ellint_P",
# Error Function and Fresnel Integrals
"erf", "erfc", "erf_Q", "erf_Z",
# Gegenbauer polynomials
"gegenpoly_1", "gegenpoly_2", "gegenpoly_3", "gegenpoly_n",
# HyperGeometric Functions
"hyperg_0F1", "hyperg_1F1", "hyperg_2F0", "hyperg_2F1",
"hyperg_U",
# Orthogonal Polynomials
"laguerre_1", "laguerre_2", "laguerre_3", "laguerre_n",
"legendre_P1", "legendre_P2", "legendre_P3",
"legendre_Pl", "legendre_Plm",
# Zeta Functions
"zeta",
# Other special functions
"Shi", "Chi", "Si", "Ci",
"dawson",
"log_1plusx", "log_1plusx_mx",
]
import_to_global("pygsl.sf", special_functions, True)
if have_scipy:
print("Loaded %d special functions from pygsl.sf." % len(special_functions))
else:
import_to_global("pygsl.sf", special_functions_doublets, True)
print("Loaded %d special functions from pygsl.sf." % (len(special_functions) + len(special_functions_doublets)))
except(ImportError): pass
# make Qt API available (it gets imported in any case by the scidavis module)
global QtGui
from PyQt4 import QtGui
global QtCore
from PyQt4 import QtCore
global Qt
from PyQt4.QtCore import Qt
# import SciDAVis' classes to the global namespace (particularly useful for fits)
for name in dir(__main__.scidavis):
setattr(__main__, name, getattr(__main__.scidavis, name))
# import selected methods of ApplicationWindow into the global namespace
appImports = (
"table", "newTable",
"matrix", "newMatrix",
"graph", "newGraph",
"note", "newNote",
"plot", "plotContour", "plotColorMap", "plotGrayScale",
"activeFolder", "rootFolder", "saveFolder",
"renameWindow", "clone",
"importImage"
)
for name in appImports:
setattr(__main__,name,getattr(__main__.scidavis.app,name))
# make Y columns indexable (using lookup in corresponding X column)
def __column_getitem(self, index):
if self.plotDesignation() != "Y":
return None
x = self.x()
for row in range(self.rowCount()):
if x.columnMode() == "Numeric":
xval = x.valueAt(row)
elif x.columnMode() == "Text":
xval = x.textAt(row)
else:
xval = x.dateTimeAt(row)
if xval == index:
if self.columnMode() == "Numeric":
return self.valueAt(row)
elif self.columnMode() == "Text":
return self.textAt(row)
else:
return self.dateTimeAt(row)
__main__.scidavis.Column.__getitem__ = __column_getitem
def __column_setitem(self, index, value):
if self.plotDesignation() != "Y":
return None
x = self.x()
for row in range(x.rowCount()):
if x.columnMode() == "Numeric":
xval = x.valueAt(row)
elif x.columnMode() == "Text":
xval = x.textAt(row)
else:
xval = x.dateTimeAt(row)
if xval == index:
if self.columnMode() == "Numeric":
return self.setValueAt(row, value)
elif self.columnMode() == "Text":
return self.setTextAt(row, value)
else:
return self.setDateTimeAt(row, value)
__main__.scidavis.Column.__setitem__ = __column_setitem
# import utility module
import sys
sys.path.append(".")
try:
import_to_global("scidavisUtil")
print "scidavisUtil successfully imported"
except(ImportError):
print "failed to import scidavisUtil"
|
smmribeiro/intellij-community | refs/heads/master | python/testData/override/simple.py | 83 | class A:
def doStuff(self, foo=True): pass
class B(A):
def otherMethod(self, foo, bar):
print foo, bar
|
mr-niels-christensen/finna-be-octo-archer | refs/heads/master | briefme/src/main/isodate/isostrf.py | 5 | ##############################################################################
# Copyright 2009, Gerhard Weis
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the authors nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT
##############################################################################
"""
This module provides an alternative strftime method.
The strftime method in this module allows only a subset of Python's strftime
format codes, plus a few additional. It supports the full range of date values
possible with standard Python date/time objects. Furthermore there are several
pr-defined format strings in this module to make ease producing of ISO 8601
conforming strings.
"""
import re
from datetime import date, timedelta
from isodate.duration import Duration
from isodate.isotzinfo import tz_isoformat
# Date specific format strings
DATE_BAS_COMPLETE = '%Y%m%d'
DATE_EXT_COMPLETE = '%Y-%m-%d'
DATE_BAS_WEEK_COMPLETE = '%YW%W%w'
DATE_EXT_WEEK_COMPLETE = '%Y-W%W-%w'
DATE_BAS_ORD_COMPLETE = '%Y%j'
DATE_EXT_ORD_COMPLETE = '%Y-%j'
DATE_BAS_WEEK = '%YW%W'
DATE_EXT_WEEK = '%Y-W%W'
DATE_MONTH = '%Y-%m'
DATE_YEAR = '%Y'
DATE_CENTURY = '%C'
# Time specific format strings
TIME_BAS_COMPLETE = '%H%M%S'
TIME_EXT_COMPLETE = '%H:%M:%S'
TIME_BAS_MINUTE = '%H%M'
TIME_EXT_MINUTE = '%H:%M'
TIME_HOUR = '%H'
# Time zone formats
TZ_BAS = '%z'
TZ_EXT = '%Z'
TZ_HOUR = '%h'
# DateTime formats
DT_EXT_COMPLETE = DATE_EXT_COMPLETE + 'T' + TIME_EXT_COMPLETE + TZ_EXT
DT_BAS_COMPLETE = DATE_BAS_COMPLETE + 'T' + TIME_BAS_COMPLETE + TZ_BAS
DT_EXT_ORD_COMPLETE = DATE_EXT_ORD_COMPLETE + 'T' + TIME_EXT_COMPLETE + TZ_EXT
DT_BAS_ORD_COMPLETE = DATE_BAS_ORD_COMPLETE + 'T' + TIME_BAS_COMPLETE + TZ_BAS
DT_EXT_WEEK_COMPLETE = (DATE_EXT_WEEK_COMPLETE + 'T' +
TIME_EXT_COMPLETE + TZ_EXT)
DT_BAS_WEEK_COMPLETE = (DATE_BAS_WEEK_COMPLETE + 'T' +
TIME_BAS_COMPLETE + TZ_BAS)
# Duration formts
D_DEFAULT = 'P%P'
D_WEEK = 'P%p'
D_ALT_EXT = 'P' + DATE_EXT_COMPLETE + 'T' + TIME_EXT_COMPLETE
D_ALT_BAS = 'P' + DATE_BAS_COMPLETE + 'T' + TIME_BAS_COMPLETE
D_ALT_EXT_ORD = 'P' + DATE_EXT_ORD_COMPLETE + 'T' + TIME_EXT_COMPLETE
D_ALT_BAS_ORD = 'P' + DATE_BAS_ORD_COMPLETE + 'T' + TIME_BAS_COMPLETE
STRF_DT_MAP = {'%d': lambda tdt, yds: '%02d' % tdt.day,
'%f': lambda tdt, yds: '%06d' % tdt.microsecond,
'%H': lambda tdt, yds: '%02d' % tdt.hour,
'%j': lambda tdt, yds: '%03d' % (tdt.toordinal() -
date(tdt.year,
1, 1).toordinal() +
1),
'%m': lambda tdt, yds: '%02d' % tdt.month,
'%M': lambda tdt, yds: '%02d' % tdt.minute,
'%S': lambda tdt, yds: '%02d' % tdt.second,
'%w': lambda tdt, yds: '%1d' % tdt.isoweekday(),
'%W': lambda tdt, yds: '%02d' % tdt.isocalendar()[1],
'%Y': lambda tdt, yds: (((yds != 4) and '+') or '') +
(('%%0%dd' % yds) % tdt.year),
'%C': lambda tdt, yds: (((yds != 4) and '+') or '') +
(('%%0%dd' % (yds - 2)) %
(tdt.year / 100)),
'%h': lambda tdt, yds: tz_isoformat(tdt, '%h'),
'%Z': lambda tdt, yds: tz_isoformat(tdt, '%Z'),
'%z': lambda tdt, yds: tz_isoformat(tdt, '%z'),
'%%': lambda tdt, yds: '%'}
STRF_D_MAP = {'%d': lambda tdt, yds: '%02d' % tdt.days,
'%f': lambda tdt, yds: '%06d' % tdt.microseconds,
'%H': lambda tdt, yds: '%02d' % (tdt.seconds / 60 / 60),
'%m': lambda tdt, yds: '%02d' % tdt.months,
'%M': lambda tdt, yds: '%02d' % ((tdt.seconds / 60) % 60),
'%S': lambda tdt, yds: '%02d' % (tdt.seconds % 60),
'%W': lambda tdt, yds: '%02d' % (abs(tdt.days / 7)),
'%Y': lambda tdt, yds: (((yds != 4) and '+') or '') +
(('%%0%dd' % yds) % tdt.years),
'%C': lambda tdt, yds: (((yds != 4) and '+') or '') +
(('%%0%dd' % (yds - 2)) %
(tdt.years / 100)),
'%%': lambda tdt, yds: '%'}
def _strfduration(tdt, format, yeardigits=4):
'''
this is the work method for timedelta and Duration instances.
see strftime for more details.
'''
def repl(match):
'''
lookup format command and return corresponding replacement.
'''
if match.group(0) in STRF_D_MAP:
return STRF_D_MAP[match.group(0)](tdt, yeardigits)
elif match.group(0) == '%P':
ret = []
if isinstance(tdt, Duration):
if tdt.years:
ret.append('%sY' % abs(tdt.years))
if tdt.months:
ret.append('%sM' % abs(tdt.months))
usecs = abs((tdt.days * 24 * 60 * 60 + tdt.seconds) * 1000000 +
tdt.microseconds)
seconds, usecs = divmod(usecs, 1000000)
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
if days:
ret.append('%sD' % days)
if hours or minutes or seconds or usecs:
ret.append('T')
if hours:
ret.append('%sH' % hours)
if minutes:
ret.append('%sM' % minutes)
if seconds or usecs:
if usecs:
ret.append(("%d.%06d" % (seconds, usecs)).rstrip('0'))
else:
ret.append("%d" % seconds)
ret.append('S')
# at least one component has to be there.
return ret and ''.join(ret) or '0D'
elif match.group(0) == '%p':
return str(abs(tdt.days // 7)) + 'W'
return match.group(0)
return re.sub('%d|%f|%H|%m|%M|%S|%W|%Y|%C|%%|%P|%p', repl,
format)
def _strfdt(tdt, format, yeardigits=4):
'''
this is the work method for time and date instances.
see strftime for more details.
'''
def repl(match):
'''
lookup format command and return corresponding replacement.
'''
if match.group(0) in STRF_DT_MAP:
return STRF_DT_MAP[match.group(0)](tdt, yeardigits)
return match.group(0)
return re.sub('%d|%f|%H|%j|%m|%M|%S|%w|%W|%Y|%C|%z|%Z|%h|%%', repl,
format)
def strftime(tdt, format, yeardigits=4):
'''Directive Meaning Notes
%d Day of the month as a decimal number [01,31].
%f Microsecond as a decimal number [0,999999], zero-padded
on the left (1)
%H Hour (24-hour clock) as a decimal number [00,23].
%j Day of the year as a decimal number [001,366].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61]. (3)
%w Weekday as a decimal number [0(Monday),6].
%W Week number of the year (Monday as the first day of the week)
as a decimal number [00,53]. All days in a new year preceding the
first Monday are considered to be in week 0. (4)
%Y Year with century as a decimal number. [0000,9999]
%C Century as a decimal number. [00,99]
%z UTC offset in the form +HHMM or -HHMM (empty string if the
object is naive). (5)
%Z Time zone name (empty string if the object is naive).
%P ISO8601 duration format.
%p ISO8601 duration format in weeks.
%% A literal '%' character.
'''
if isinstance(tdt, (timedelta, Duration)):
return _strfduration(tdt, format, yeardigits)
return _strfdt(tdt, format, yeardigits)
|
ismangil/pjproject | refs/heads/master | tests/pjsua/scripts-sipp/uac-srtp-dtls-reinv-sdes.py | 3 | # $Id$
#
import inc_const as const
PJSUA = ["--null-audio --max-calls=1 --auto-answer=200 --no-tcp --srtp-secure 0 --use-srtp 2 --srtp-keying=1"]
PJSUA_EXPECTS = [[0, "SRTP uses keying method DTLS-SRTP", ""],
[0, "SRTP uses keying method SDES", ""]
]
|
TheTimmy/spack | refs/heads/develop | var/spack/repos/builtin/packages/py-bottleneck/package.py | 3 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class PyBottleneck(PythonPackage):
"""A collection of fast NumPy array functions written in Cython."""
homepage = "https://pypi.python.org/pypi/Bottleneck/1.0.0"
url = "https://pypi.io/packages/source/B/Bottleneck/Bottleneck-1.0.0.tar.gz"
version('1.0.0', '380fa6f275bd24f27e7cf0e0d752f5d2')
depends_on('py-setuptools', type='build')
depends_on('py-numpy', type=('build', 'run'))
|
nkmk/python-snippets | refs/heads/master | notebook/opencv_warp_func.py | 1 | import cv2
import numpy as np
def warp(src, dst, src_pts, dst_pts, transform_func, warp_func, **kwargs):
src_pts_arr = np.array(src_pts, dtype=np.float32)
dst_pts_arr = np.array(dst_pts, dtype=np.float32)
src_rect = cv2.boundingRect(src_pts_arr)
dst_rect = cv2.boundingRect(dst_pts_arr)
src_crop = src[src_rect[1]:src_rect[1] + src_rect[3], src_rect[0]:src_rect[0] + src_rect[2]]
dst_crop = dst[dst_rect[1]:dst_rect[1] + dst_rect[3], dst_rect[0]:dst_rect[0] + dst_rect[2]]
src_pts_crop = src_pts_arr - src_rect[:2]
dst_pts_crop = dst_pts_arr - dst_rect[:2]
mat = transform_func(src_pts_crop.astype(np.float32), dst_pts_crop.astype(np.float32))
warp_img = warp_func(src_crop, mat, tuple(dst_rect[2:]), **kwargs)
mask = np.zeros_like(dst_crop, dtype=np.float32)
cv2.fillConvexPoly(mask, dst_pts_crop.astype(np.int), (1.0, 1.0, 1.0), cv2.LINE_AA)
dst_crop_merge = warp_img * mask + dst_crop * (1 - mask)
dst[dst_rect[1]:dst_rect[1] + dst_rect[3], dst_rect[0]:dst_rect[0] + dst_rect[2]] = dst_crop_merge
def warp_triangle(src, dst, src_pts, dst_pts, **kwargs):
warp(src, dst, src_pts, dst_pts,
cv2.getAffineTransform, cv2.warpAffine, **kwargs)
def warp_rectangle(src, dst, src_pts, dst_pts, **kwargs):
warp(src, dst, src_pts, dst_pts,
cv2.getPerspectiveTransform, cv2.warpPerspective, **kwargs)
src = cv2.imread('data/src/lena.jpg')
dst = cv2.imread('data/src/rocket.jpg')
src_pts = [[100, 80], [150, 200], [300, 20]]
dst_pts = [[280, 120], [320, 300], [400, 150]]
warp_triangle(src, dst, src_pts, dst_pts)
cv2.imwrite('data/dst/opencv_warp_triangle.jpg', dst)
# True
# 
src = cv2.imread('data/src/lena.jpg')
dst = cv2.imread('data/src/rocket.jpg')
src_pts = [[100, 80], [150, 200], [350, 160], [300, 20]]
dst_pts = [[280, 120], [200, 280], [500, 300], [400, 150]]
warp_rectangle(src, dst, src_pts, dst_pts, flags=cv2.INTER_CUBIC)
cv2.imwrite('data/dst/opencv_warp_rectangle.jpg', dst)
# True
# 
|
dstroppa/openstack-smartos-nova-grizzly | refs/heads/master | nova/tests/api/openstack/compute/contrib/test_consoles.py | 14 | # Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# 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.
import webob
from nova.compute import api as compute_api
from nova import exception
from nova.openstack.common import jsonutils
from nova import test
from nova.tests.api.openstack import fakes
def fake_get_vnc_console(self, _context, _instance, _console_type):
return {'url': 'http://fake'}
def fake_get_spice_console(self, _context, _instance, _console_type):
return {'url': 'http://fake'}
def fake_get_vnc_console_invalid_type(self, _context,
_instance, _console_type):
raise exception.ConsoleTypeInvalid(console_type=_console_type)
def fake_get_spice_console_invalid_type(self, _context,
_instance, _console_type):
raise exception.ConsoleTypeInvalid(console_type=_console_type)
def fake_get_vnc_console_not_ready(self, _context, instance, _console_type):
raise exception.InstanceNotReady(instance_id=instance["uuid"])
def fake_get_spice_console_not_ready(self, _context, instance, _console_type):
raise exception.InstanceNotReady(instance_id=instance["uuid"])
def fake_get_vnc_console_not_found(self, _context, instance, _console_type):
raise exception.InstanceNotFound(instance_id=instance["uuid"])
def fake_get_spice_console_not_found(self, _context, instance, _console_type):
raise exception.InstanceNotFound(instance_id=instance["uuid"])
def fake_get(self, context, instance_uuid):
return {'uuid': instance_uuid}
def fake_get_not_found(self, context, instance_uuid):
raise exception.InstanceNotFound(instance_id=instance_uuid)
class ConsolesExtensionTest(test.TestCase):
def setUp(self):
super(ConsolesExtensionTest, self).setUp()
self.stubs.Set(compute_api.API, 'get_vnc_console',
fake_get_vnc_console)
self.stubs.Set(compute_api.API, 'get_spice_console',
fake_get_spice_console)
self.stubs.Set(compute_api.API, 'get', fake_get)
self.flags(
osapi_compute_extension=[
'nova.api.openstack.compute.contrib.select_extensions'],
osapi_compute_ext_list=['Consoles'])
self.app = fakes.wsgi_app(init_only=('servers',))
def test_get_vnc_console(self):
body = {'os-getVNCConsole': {'type': 'novnc'}}
req = webob.Request.blank('/v2/fake/servers/1/action')
req.method = "POST"
req.body = jsonutils.dumps(body)
req.headers["content-type"] = "application/json"
res = req.get_response(self.app)
output = jsonutils.loads(res.body)
self.assertEqual(res.status_int, 200)
self.assertEqual(output,
{u'console': {u'url': u'http://fake', u'type': u'novnc'}})
def test_get_vnc_console_not_ready(self):
self.stubs.Set(compute_api.API, 'get_vnc_console',
fake_get_vnc_console_not_ready)
body = {'os-getVNCConsole': {'type': 'novnc'}}
req = webob.Request.blank('/v2/fake/servers/1/action')
req.method = "POST"
req.body = jsonutils.dumps(body)
req.headers["content-type"] = "application/json"
res = req.get_response(self.app)
output = jsonutils.loads(res.body)
self.assertEqual(res.status_int, 409)
def test_get_vnc_console_no_type(self):
self.stubs.Set(compute_api.API, 'get_vnc_console',
fake_get_vnc_console_invalid_type)
body = {'os-getVNCConsole': {}}
req = webob.Request.blank('/v2/fake/servers/1/action')
req.method = "POST"
req.body = jsonutils.dumps(body)
req.headers["content-type"] = "application/json"
res = req.get_response(self.app)
self.assertEqual(res.status_int, 400)
def test_get_vnc_console_no_instance(self):
self.stubs.Set(compute_api.API, 'get', fake_get_not_found)
body = {'os-getVNCConsole': {'type': 'novnc'}}
req = webob.Request.blank('/v2/fake/servers/1/action')
req.method = "POST"
req.body = jsonutils.dumps(body)
req.headers["content-type"] = "application/json"
res = req.get_response(self.app)
self.assertEqual(res.status_int, 404)
def test_get_vnc_console_no_instance_on_console_get(self):
self.stubs.Set(compute_api.API, 'get_vnc_console',
fake_get_vnc_console_not_found)
body = {'os-getVNCConsole': {'type': 'novnc'}}
req = webob.Request.blank('/v2/fake/servers/1/action')
req.method = "POST"
req.body = jsonutils.dumps(body)
req.headers["content-type"] = "application/json"
res = req.get_response(self.app)
self.assertEqual(res.status_int, 404)
def test_get_vnc_console_invalid_type(self):
body = {'os-getVNCConsole': {'type': 'invalid'}}
self.stubs.Set(compute_api.API, 'get_vnc_console',
fake_get_vnc_console_invalid_type)
req = webob.Request.blank('/v2/fake/servers/1/action')
req.method = "POST"
req.body = jsonutils.dumps(body)
req.headers["content-type"] = "application/json"
res = req.get_response(self.app)
self.assertEqual(res.status_int, 400)
def test_get_spice_console(self):
body = {'os-getSPICEConsole': {'type': 'spice-html5'}}
req = webob.Request.blank('/v2/fake/servers/1/action')
req.method = "POST"
req.body = jsonutils.dumps(body)
req.headers["content-type"] = "application/json"
res = req.get_response(self.app)
output = jsonutils.loads(res.body)
self.assertEqual(res.status_int, 200)
self.assertEqual(output,
{u'console': {u'url': u'http://fake', u'type': u'spice-html5'}})
def test_get_spice_console_not_ready(self):
self.stubs.Set(compute_api.API, 'get_spice_console',
fake_get_spice_console_not_ready)
body = {'os-getSPICEConsole': {'type': 'spice-html5'}}
req = webob.Request.blank('/v2/fake/servers/1/action')
req.method = "POST"
req.body = jsonutils.dumps(body)
req.headers["content-type"] = "application/json"
res = req.get_response(self.app)
output = jsonutils.loads(res.body)
self.assertEqual(res.status_int, 409)
def test_get_spice_console_no_type(self):
self.stubs.Set(compute_api.API, 'get_spice_console',
fake_get_spice_console_invalid_type)
body = {'os-getSPICEConsole': {}}
req = webob.Request.blank('/v2/fake/servers/1/action')
req.method = "POST"
req.body = jsonutils.dumps(body)
req.headers["content-type"] = "application/json"
res = req.get_response(self.app)
self.assertEqual(res.status_int, 400)
def test_get_spice_console_no_instance(self):
self.stubs.Set(compute_api.API, 'get', fake_get_not_found)
body = {'os-getSPICEConsole': {'type': 'spice-html5'}}
req = webob.Request.blank('/v2/fake/servers/1/action')
req.method = "POST"
req.body = jsonutils.dumps(body)
req.headers["content-type"] = "application/json"
res = req.get_response(self.app)
self.assertEqual(res.status_int, 404)
def test_get_spice_console_no_instance_on_console_get(self):
self.stubs.Set(compute_api.API, 'get_spice_console',
fake_get_spice_console_not_found)
body = {'os-getSPICEConsole': {'type': 'spice-html5'}}
req = webob.Request.blank('/v2/fake/servers/1/action')
req.method = "POST"
req.body = jsonutils.dumps(body)
req.headers["content-type"] = "application/json"
res = req.get_response(self.app)
self.assertEqual(res.status_int, 404)
def test_get_spice_console_invalid_type(self):
body = {'os-getSPICEConsole': {'type': 'invalid'}}
self.stubs.Set(compute_api.API, 'get_spice_console',
fake_get_spice_console_invalid_type)
req = webob.Request.blank('/v2/fake/servers/1/action')
req.method = "POST"
req.body = jsonutils.dumps(body)
req.headers["content-type"] = "application/json"
res = req.get_response(self.app)
self.assertEqual(res.status_int, 400)
|
Jusedawg/SickRage | refs/heads/develop | lib/sqlalchemy/sql/dml.py | 78 | # sql/dml.py
# Copyright (C) 2009-2014 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
Provide :class:`.Insert`, :class:`.Update` and :class:`.Delete`.
"""
from .base import Executable, _generative, _from_objects, DialectKWArgs
from .elements import ClauseElement, _literal_as_text, Null, and_, _clone
from .selectable import _interpret_as_from, _interpret_as_select, HasPrefixes
from .. import util
from .. import exc
class UpdateBase(DialectKWArgs, HasPrefixes, Executable, ClauseElement):
"""Form the base for ``INSERT``, ``UPDATE``, and ``DELETE`` statements.
"""
__visit_name__ = 'update_base'
_execution_options = \
Executable._execution_options.union({'autocommit': True})
_hints = util.immutabledict()
_prefixes = ()
def _process_colparams(self, parameters):
def process_single(p):
if isinstance(p, (list, tuple)):
return dict(
(c.key, pval)
for c, pval in zip(self.table.c, p)
)
else:
return p
if isinstance(parameters, (list, tuple)) and \
parameters and \
isinstance(parameters[0], (list, tuple, dict)):
if not self._supports_multi_parameters:
raise exc.InvalidRequestError(
"This construct does not support "
"multiple parameter sets.")
return [process_single(p) for p in parameters], True
else:
return process_single(parameters), False
def params(self, *arg, **kw):
"""Set the parameters for the statement.
This method raises ``NotImplementedError`` on the base class,
and is overridden by :class:`.ValuesBase` to provide the
SET/VALUES clause of UPDATE and INSERT.
"""
raise NotImplementedError(
"params() is not supported for INSERT/UPDATE/DELETE statements."
" To set the values for an INSERT or UPDATE statement, use"
" stmt.values(**parameters).")
def bind(self):
"""Return a 'bind' linked to this :class:`.UpdateBase`
or a :class:`.Table` associated with it.
"""
return self._bind or self.table.bind
def _set_bind(self, bind):
self._bind = bind
bind = property(bind, _set_bind)
@_generative
def returning(self, *cols):
"""Add a :term:`RETURNING` or equivalent clause to this statement.
e.g.::
stmt = table.update().\\
where(table.c.data == 'value').\\
values(status='X').\\
returning(table.c.server_flag, table.c.updated_timestamp)
for server_flag, updated_timestamp in connection.execute(stmt):
print(server_flag, updated_timestamp)
The given collection of column expressions should be derived from
the table that is
the target of the INSERT, UPDATE, or DELETE. While :class:`.Column`
objects are typical, the elements can also be expressions::
stmt = table.insert().returning(
(table.c.first_name + " " + table.c.last_name).label('fullname')
)
Upon compilation, a RETURNING clause, or database equivalent,
will be rendered within the statement. For INSERT and UPDATE,
the values are the newly inserted/updated values. For DELETE,
the values are those of the rows which were deleted.
Upon execution, the values of the columns to be returned
are made available via the result set and can be iterated
using :meth:`.ResultProxy.fetchone` and similar. For DBAPIs which do not
natively support returning values (i.e. cx_oracle),
SQLAlchemy will approximate this behavior at the result level
so that a reasonable amount of behavioral neutrality is
provided.
Note that not all databases/DBAPIs
support RETURNING. For those backends with no support,
an exception is raised upon compilation and/or execution.
For those who do support it, the functionality across backends
varies greatly, including restrictions on executemany()
and other statements which return multiple rows. Please
read the documentation notes for the database in use in
order to determine the availability of RETURNING.
.. seealso::
:meth:`.ValuesBase.return_defaults` - an alternative method tailored
towards efficient fetching of server-side defaults and triggers
for single-row INSERTs or UPDATEs.
"""
self._returning = cols
@_generative
def with_hint(self, text, selectable=None, dialect_name="*"):
"""Add a table hint for a single table to this
INSERT/UPDATE/DELETE statement.
.. note::
:meth:`.UpdateBase.with_hint` currently applies only to
Microsoft SQL Server. For MySQL INSERT/UPDATE/DELETE hints, use
:meth:`.UpdateBase.prefix_with`.
The text of the hint is rendered in the appropriate
location for the database backend in use, relative
to the :class:`.Table` that is the subject of this
statement, or optionally to that of the given
:class:`.Table` passed as the ``selectable`` argument.
The ``dialect_name`` option will limit the rendering of a particular
hint to a particular backend. Such as, to add a hint
that only takes effect for SQL Server::
mytable.insert().with_hint("WITH (PAGLOCK)", dialect_name="mssql")
.. versionadded:: 0.7.6
:param text: Text of the hint.
:param selectable: optional :class:`.Table` that specifies
an element of the FROM clause within an UPDATE or DELETE
to be the subject of the hint - applies only to certain backends.
:param dialect_name: defaults to ``*``, if specified as the name
of a particular dialect, will apply these hints only when
that dialect is in use.
"""
if selectable is None:
selectable = self.table
self._hints = self._hints.union(
{(selectable, dialect_name): text})
class ValuesBase(UpdateBase):
"""Supplies support for :meth:`.ValuesBase.values` to
INSERT and UPDATE constructs."""
__visit_name__ = 'values_base'
_supports_multi_parameters = False
_has_multi_parameters = False
select = None
def __init__(self, table, values, prefixes):
self.table = _interpret_as_from(table)
self.parameters, self._has_multi_parameters = \
self._process_colparams(values)
if prefixes:
self._setup_prefixes(prefixes)
@_generative
def values(self, *args, **kwargs):
"""specify a fixed VALUES clause for an INSERT statement, or the SET
clause for an UPDATE.
Note that the :class:`.Insert` and :class:`.Update` constructs support
per-execution time formatting of the VALUES and/or SET clauses,
based on the arguments passed to :meth:`.Connection.execute`. However,
the :meth:`.ValuesBase.values` method can be used to "fix" a particular
set of parameters into the statement.
Multiple calls to :meth:`.ValuesBase.values` will produce a new
construct, each one with the parameter list modified to include
the new parameters sent. In the typical case of a single
dictionary of parameters, the newly passed keys will replace
the same keys in the previous construct. In the case of a list-based
"multiple values" construct, each new list of values is extended
onto the existing list of values.
:param \**kwargs: key value pairs representing the string key
of a :class:`.Column` mapped to the value to be rendered into the
VALUES or SET clause::
users.insert().values(name="some name")
users.update().where(users.c.id==5).values(name="some name")
:param \*args: Alternatively, a dictionary, tuple or list
of dictionaries or tuples can be passed as a single positional
argument in order to form the VALUES or
SET clause of the statement. The single dictionary form
works the same as the kwargs form::
users.insert().values({"name": "some name"})
If a tuple is passed, the tuple should contain the same number
of columns as the target :class:`.Table`::
users.insert().values((5, "some name"))
The :class:`.Insert` construct also supports multiply-rendered VALUES
construct, for those backends which support this SQL syntax
(SQLite, Postgresql, MySQL). This mode is indicated by passing a list
of one or more dictionaries/tuples::
users.insert().values([
{"name": "some name"},
{"name": "some other name"},
{"name": "yet another name"},
])
In the case of an :class:`.Update`
construct, only the single dictionary/tuple form is accepted,
else an exception is raised. It is also an exception case to
attempt to mix the single-/multiple- value styles together,
either through multiple :meth:`.ValuesBase.values` calls
or by sending a list + kwargs at the same time.
.. note::
Passing a multiple values list is *not* the same
as passing a multiple values list to the :meth:`.Connection.execute`
method. Passing a list of parameter sets to :meth:`.ValuesBase.values`
produces a construct of this form::
INSERT INTO table (col1, col2, col3) VALUES
(col1_0, col2_0, col3_0),
(col1_1, col2_1, col3_1),
...
whereas a multiple list passed to :meth:`.Connection.execute`
has the effect of using the DBAPI
`executemany() <http://www.python.org/dev/peps/pep-0249/#id18>`_
method, which provides a high-performance system of invoking
a single-row INSERT statement many times against a series
of parameter sets. The "executemany" style is supported by
all database backends, as it does not depend on a special SQL
syntax.
.. versionadded:: 0.8
Support for multiple-VALUES INSERT statements.
.. seealso::
:ref:`inserts_and_updates` - SQL Expression
Language Tutorial
:func:`~.expression.insert` - produce an ``INSERT`` statement
:func:`~.expression.update` - produce an ``UPDATE`` statement
"""
if self.select is not None:
raise exc.InvalidRequestError(
"This construct already inserts from a SELECT")
if self._has_multi_parameters and kwargs:
raise exc.InvalidRequestError(
"This construct already has multiple parameter sets.")
if args:
if len(args) > 1:
raise exc.ArgumentError(
"Only a single dictionary/tuple or list of "
"dictionaries/tuples is accepted positionally.")
v = args[0]
else:
v = {}
if self.parameters is None:
self.parameters, self._has_multi_parameters = \
self._process_colparams(v)
else:
if self._has_multi_parameters:
self.parameters = list(self.parameters)
p, self._has_multi_parameters = self._process_colparams(v)
if not self._has_multi_parameters:
raise exc.ArgumentError(
"Can't mix single-values and multiple values "
"formats in one statement")
self.parameters.extend(p)
else:
self.parameters = self.parameters.copy()
p, self._has_multi_parameters = self._process_colparams(v)
if self._has_multi_parameters:
raise exc.ArgumentError(
"Can't mix single-values and multiple values "
"formats in one statement")
self.parameters.update(p)
if kwargs:
if self._has_multi_parameters:
raise exc.ArgumentError(
"Can't pass kwargs and multiple parameter sets "
"simultaenously")
else:
self.parameters.update(kwargs)
@_generative
def return_defaults(self, *cols):
"""Make use of a :term:`RETURNING` clause for the purpose
of fetching server-side expressions and defaults.
E.g.::
stmt = table.insert().values(data='newdata').return_defaults()
result = connection.execute(stmt)
server_created_at = result.returned_defaults['created_at']
When used against a backend that supports RETURNING, all column
values generated by SQL expression or server-side-default will be added
to any existing RETURNING clause, provided that
:meth:`.UpdateBase.returning` is not used simultaneously. The column values
will then be available on the result using the
:attr:`.ResultProxy.returned_defaults` accessor as a
dictionary, referring to values keyed to the :class:`.Column` object
as well as its ``.key``.
This method differs from :meth:`.UpdateBase.returning` in these ways:
1. :meth:`.ValuesBase.return_defaults` is only intended for use with
an INSERT or an UPDATE statement that matches exactly one row.
While the RETURNING construct in the general sense supports multiple
rows for a multi-row UPDATE or DELETE statement, or for special
cases of INSERT that return multiple rows (e.g. INSERT from SELECT,
multi-valued VALUES clause), :meth:`.ValuesBase.return_defaults`
is intended only
for an "ORM-style" single-row INSERT/UPDATE statement. The row
returned by the statement is also consumed implcitly when
:meth:`.ValuesBase.return_defaults` is used. By contrast,
:meth:`.UpdateBase.returning` leaves the RETURNING result-set intact
with a collection of any number of rows.
2. It is compatible with the existing logic to fetch auto-generated
primary key values, also known as "implicit returning". Backends that
support RETURNING will automatically make use of RETURNING in order
to fetch the value of newly generated primary keys; while the
:meth:`.UpdateBase.returning` method circumvents this behavior,
:meth:`.ValuesBase.return_defaults` leaves it intact.
3. It can be called against any backend. Backends that don't support
RETURNING will skip the usage of the feature, rather than raising
an exception. The return value of :attr:`.ResultProxy.returned_defaults`
will be ``None``
:meth:`.ValuesBase.return_defaults` is used by the ORM to provide
an efficient implementation for the ``eager_defaults`` feature of
:func:`.mapper`.
:param cols: optional list of column key names or :class:`.Column`
objects. If omitted, all column expressions evaulated on the server
are added to the returning list.
.. versionadded:: 0.9.0
.. seealso::
:meth:`.UpdateBase.returning`
:attr:`.ResultProxy.returned_defaults`
"""
self._return_defaults = cols or True
class Insert(ValuesBase):
"""Represent an INSERT construct.
The :class:`.Insert` object is created using the
:func:`~.expression.insert()` function.
.. seealso::
:ref:`coretutorial_insert_expressions`
"""
__visit_name__ = 'insert'
_supports_multi_parameters = True
def __init__(self,
table,
values=None,
inline=False,
bind=None,
prefixes=None,
returning=None,
return_defaults=False,
**dialect_kw):
"""Construct an :class:`.Insert` object.
Similar functionality is available via the
:meth:`~.TableClause.insert` method on
:class:`~.schema.Table`.
:param table: :class:`.TableClause` which is the subject of the insert.
:param values: collection of values to be inserted; see
:meth:`.Insert.values` for a description of allowed formats here.
Can be omitted entirely; a :class:`.Insert` construct will also
dynamically render the VALUES clause at execution time based on
the parameters passed to :meth:`.Connection.execute`.
:param inline: if True, SQL defaults will be compiled 'inline' into the
statement and not pre-executed.
If both `values` and compile-time bind parameters are present, the
compile-time bind parameters override the information specified
within `values` on a per-key basis.
The keys within `values` can be either :class:`~sqlalchemy.schema.Column`
objects or their string identifiers. Each key may reference one of:
* a literal data value (i.e. string, number, etc.);
* a Column object;
* a SELECT statement.
If a ``SELECT`` statement is specified which references this
``INSERT`` statement's table, the statement will be correlated
against the ``INSERT`` statement.
.. seealso::
:ref:`coretutorial_insert_expressions` - SQL Expression Tutorial
:ref:`inserts_and_updates` - SQL Expression Tutorial
"""
ValuesBase.__init__(self, table, values, prefixes)
self._bind = bind
self.select = self.select_names = None
self.inline = inline
self._returning = returning
self._validate_dialect_kwargs(dialect_kw)
self._return_defaults = return_defaults
def get_children(self, **kwargs):
if self.select is not None:
return self.select,
else:
return ()
@_generative
def from_select(self, names, select):
"""Return a new :class:`.Insert` construct which represents
an ``INSERT...FROM SELECT`` statement.
e.g.::
sel = select([table1.c.a, table1.c.b]).where(table1.c.c > 5)
ins = table2.insert().from_select(['a', 'b'], sel)
:param names: a sequence of string column names or :class:`.Column`
objects representing the target columns.
:param select: a :func:`.select` construct, :class:`.FromClause`
or other construct which resolves into a :class:`.FromClause`,
such as an ORM :class:`.Query` object, etc. The order of
columns returned from this FROM clause should correspond to the
order of columns sent as the ``names`` parameter; while this
is not checked before passing along to the database, the database
would normally raise an exception if these column lists don't
correspond.
.. note::
Depending on backend, it may be necessary for the :class:`.Insert`
statement to be constructed using the ``inline=True`` flag; this
flag will prevent the implicit usage of ``RETURNING`` when the
``INSERT`` statement is rendered, which isn't supported on a backend
such as Oracle in conjunction with an ``INSERT..SELECT`` combination::
sel = select([table1.c.a, table1.c.b]).where(table1.c.c > 5)
ins = table2.insert(inline=True).from_select(['a', 'b'], sel)
.. note::
A SELECT..INSERT construct in SQL has no VALUES clause. Therefore
:class:`.Column` objects which utilize Python-side defaults
(e.g. as described at :ref:`metadata_defaults_toplevel`)
will **not** take effect when using :meth:`.Insert.from_select`.
.. versionadded:: 0.8.3
"""
if self.parameters:
raise exc.InvalidRequestError(
"This construct already inserts value expressions")
self.parameters, self._has_multi_parameters = \
self._process_colparams(dict((n, Null()) for n in names))
self.select_names = names
self.select = _interpret_as_select(select)
def _copy_internals(self, clone=_clone, **kw):
# TODO: coverage
self.parameters = self.parameters.copy()
if self.select is not None:
self.select = _clone(self.select)
class Update(ValuesBase):
"""Represent an Update construct.
The :class:`.Update` object is created using the :func:`update()` function.
"""
__visit_name__ = 'update'
def __init__(self,
table,
whereclause=None,
values=None,
inline=False,
bind=None,
prefixes=None,
returning=None,
return_defaults=False,
**dialect_kw):
"""Construct an :class:`.Update` object.
E.g.::
from sqlalchemy import update
stmt = update(users).where(users.c.id==5).\\
values(name='user #5')
Similar functionality is available via the
:meth:`~.TableClause.update` method on
:class:`.Table`::
stmt = users.update().\\
where(users.c.id==5).\\
values(name='user #5')
:param table: A :class:`.Table` object representing the database
table to be updated.
:param whereclause: Optional SQL expression describing the ``WHERE``
condition of the ``UPDATE`` statement. Modern applications
may prefer to use the generative :meth:`~Update.where()`
method to specify the ``WHERE`` clause.
The WHERE clause can refer to multiple tables.
For databases which support this, an ``UPDATE FROM`` clause will
be generated, or on MySQL, a multi-table update. The statement
will fail on databases that don't have support for multi-table
update statements. A SQL-standard method of referring to
additional tables in the WHERE clause is to use a correlated
subquery::
users.update().values(name='ed').where(
users.c.name==select([addresses.c.email_address]).\\
where(addresses.c.user_id==users.c.id).\\
as_scalar()
)
.. versionchanged:: 0.7.4
The WHERE clause can refer to multiple tables.
:param values:
Optional dictionary which specifies the ``SET`` conditions of the
``UPDATE``. If left as ``None``, the ``SET``
conditions are determined from those parameters passed to the
statement during the execution and/or compilation of the
statement. When compiled standalone without any parameters,
the ``SET`` clause generates for all columns.
Modern applications may prefer to use the generative
:meth:`.Update.values` method to set the values of the
UPDATE statement.
:param inline:
if True, SQL defaults present on :class:`.Column` objects via
the ``default`` keyword will be compiled 'inline' into the statement
and not pre-executed. This means that their values will not
be available in the dictionary returned from
:meth:`.ResultProxy.last_updated_params`.
If both ``values`` and compile-time bind parameters are present, the
compile-time bind parameters override the information specified
within ``values`` on a per-key basis.
The keys within ``values`` can be either :class:`.Column`
objects or their string identifiers (specifically the "key" of the
:class:`.Column`, normally but not necessarily equivalent to
its "name"). Normally, the
:class:`.Column` objects used here are expected to be
part of the target :class:`.Table` that is the table
to be updated. However when using MySQL, a multiple-table
UPDATE statement can refer to columns from any of
the tables referred to in the WHERE clause.
The values referred to in ``values`` are typically:
* a literal data value (i.e. string, number, etc.)
* a SQL expression, such as a related :class:`.Column`,
a scalar-returning :func:`.select` construct,
etc.
When combining :func:`.select` constructs within the values
clause of an :func:`.update` construct,
the subquery represented by the :func:`.select` should be
*correlated* to the parent table, that is, providing criterion
which links the table inside the subquery to the outer table
being updated::
users.update().values(
name=select([addresses.c.email_address]).\\
where(addresses.c.user_id==users.c.id).\\
as_scalar()
)
.. seealso::
:ref:`inserts_and_updates` - SQL Expression
Language Tutorial
"""
ValuesBase.__init__(self, table, values, prefixes)
self._bind = bind
self._returning = returning
if whereclause is not None:
self._whereclause = _literal_as_text(whereclause)
else:
self._whereclause = None
self.inline = inline
self._validate_dialect_kwargs(dialect_kw)
self._return_defaults = return_defaults
def get_children(self, **kwargs):
if self._whereclause is not None:
return self._whereclause,
else:
return ()
def _copy_internals(self, clone=_clone, **kw):
# TODO: coverage
self._whereclause = clone(self._whereclause, **kw)
self.parameters = self.parameters.copy()
@_generative
def where(self, whereclause):
"""return a new update() construct with the given expression added to
its WHERE clause, joined to the existing clause via AND, if any.
"""
if self._whereclause is not None:
self._whereclause = and_(self._whereclause,
_literal_as_text(whereclause))
else:
self._whereclause = _literal_as_text(whereclause)
@property
def _extra_froms(self):
# TODO: this could be made memoized
# if the memoization is reset on each generative call.
froms = []
seen = set([self.table])
if self._whereclause is not None:
for item in _from_objects(self._whereclause):
if not seen.intersection(item._cloned_set):
froms.append(item)
seen.update(item._cloned_set)
return froms
class Delete(UpdateBase):
"""Represent a DELETE construct.
The :class:`.Delete` object is created using the :func:`delete()` function.
"""
__visit_name__ = 'delete'
def __init__(self,
table,
whereclause=None,
bind=None,
returning=None,
prefixes=None,
**dialect_kw):
"""Construct :class:`.Delete` object.
Similar functionality is available via the
:meth:`~.TableClause.delete` method on
:class:`~.schema.Table`.
:param table: The table to be updated.
:param whereclause: A :class:`.ClauseElement` describing the ``WHERE``
condition of the ``UPDATE`` statement. Note that the
:meth:`~Delete.where()` generative method may be used instead.
.. seealso::
:ref:`deletes` - SQL Expression Tutorial
"""
self._bind = bind
self.table = _interpret_as_from(table)
self._returning = returning
if prefixes:
self._setup_prefixes(prefixes)
if whereclause is not None:
self._whereclause = _literal_as_text(whereclause)
else:
self._whereclause = None
self._validate_dialect_kwargs(dialect_kw)
def get_children(self, **kwargs):
if self._whereclause is not None:
return self._whereclause,
else:
return ()
@_generative
def where(self, whereclause):
"""Add the given WHERE clause to a newly returned delete construct."""
if self._whereclause is not None:
self._whereclause = and_(self._whereclause,
_literal_as_text(whereclause))
else:
self._whereclause = _literal_as_text(whereclause)
def _copy_internals(self, clone=_clone, **kw):
# TODO: coverage
self._whereclause = clone(self._whereclause, **kw)
|
zimmermegan/MARDA | refs/heads/master | nltk-3.0.3/nltk/parse/malt.py | 5 | # Natural Language Toolkit: Interface to MaltParser
#
# Author: Dan Garrette <dhgarrette@gmail.com>
#
# Copyright (C) 2001-2015 NLTK Project
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
from __future__ import print_function
import os
import tempfile
import glob
from operator import add
from functools import reduce
import subprocess
from nltk.data import ZipFilePathPointer
from nltk.tokenize import word_tokenize
from nltk.internals import find_binary
from nltk.parse.api import ParserI
from nltk.parse.dependencygraph import DependencyGraph
class MaltParser(ParserI):
def __init__(self, tagger=None, mco=None, working_dir=None, additional_java_args=None):
"""
An interface for parsing with the Malt Parser.
:param mco: The name of the pre-trained model. If provided, training
will not be required, and MaltParser will use the model file in
${working_dir}/${mco}.mco.
:type mco: str
"""
self.config_malt()
self.mco = 'malt_temp' if mco is None else mco
self.working_dir = tempfile.gettempdir() if working_dir is None\
else working_dir
self.additional_java_args = [] if additional_java_args is None else additional_java_args
self._trained = mco is not None
if tagger is not None:
self.tagger = tagger
else:
from nltk.tag import RegexpTagger
self.tagger = RegexpTagger(
[(r'^-?[0-9]+(.[0-9]+)?$', 'CD'), # cardinal numbers
(r'(The|the|A|a|An|an)$', 'AT'), # articles
(r'.*able$', 'JJ'), # adjectives
(r'.*ness$', 'NN'), # nouns formed from adjectives
(r'.*ly$', 'RB'), # adverbs
(r'.*s$', 'NNS'), # plural nouns
(r'.*ing$', 'VBG'), # gerunds
(r'.*ed$', 'VBD'), # past tense verbs
(r'.*', 'NN') # nouns (default)
])
def config_malt(self, bin=None, verbose=False):
"""
Configure NLTK's interface to the ``malt`` package. This
searches for a directory containing the malt jar
:param bin: The full path to the ``malt`` binary. If not
specified, then nltk will search the system for a ``malt``
binary; and if one is not found, it will raise a
``LookupError`` exception.
:type bin: str
"""
#: A list of directories that should be searched for the malt
#: executables. This list is used by ``config_malt`` when searching
#: for the malt executables.
_malt_path = ['.',
'/usr/lib/malt-1*',
'/usr/share/malt-1*',
'/usr/local/bin',
'/usr/local/malt-1*',
'/usr/local/bin/malt-1*',
'/usr/local/malt-1*',
'/usr/local/share/malt-1*']
# Expand wildcards in _malt_path:
malt_path = reduce(add, map(glob.glob, _malt_path))
# Find the malt binary.
self._malt_bin = find_binary('malt.jar', bin,
searchpath=malt_path, env_vars=['MALT_PARSER'],
url='http://www.maltparser.org/',
verbose=verbose)
def parse_sents(self, sentences, verbose=False):
"""
Use MaltParser to parse multiple sentences. Takes multiple sentences as a
list where each sentence is a list of words.
Each sentence will be automatically tagged with this MaltParser instance's
tagger.
:param sentences: Input sentences to parse
:type sentence: list(list(str))
:return: iter(DependencyGraph)
"""
tagged_sentences = [self.tagger.tag(sentence) for sentence in sentences]
return iter(self.tagged_parse_sents(tagged_sentences, verbose))
def tagged_parse(self, sentence, verbose=False):
"""
Use MaltParser to parse a sentence. Takes a sentence as a list of
(word, tag) tuples; the sentence must have already been tokenized and
tagged.
:param sentence: Input sentence to parse
:type sentence: list(tuple(str, str))
:return: iter(DependencyGraph) the possible dependency graph representations of the sentence
"""
return next(self.tagged_parse_sents([sentence], verbose))
def tagged_parse_sents(self, sentences, verbose=False):
"""
Use MaltParser to parse multiple sentences. Takes multiple sentences
where each sentence is a list of (word, tag) tuples.
The sentences must have already been tokenized and tagged.
:param sentences: Input sentences to parse
:type sentence: list(list(tuple(str, str)))
:return: iter(iter(``DependencyGraph``)) the dependency graph representation
of each sentence
"""
if not self._malt_bin:
raise Exception("MaltParser location is not configured. Call config_malt() first.")
if not self._trained:
raise Exception("Parser has not been trained. Call train() first.")
input_file = tempfile.NamedTemporaryFile(prefix='malt_input.conll',
dir=self.working_dir,
delete=False)
output_file = tempfile.NamedTemporaryFile(prefix='malt_output.conll',
dir=self.working_dir,
delete=False)
try:
for sentence in sentences:
for (i, (word, tag)) in enumerate(sentence, start=1):
input_str = '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' %\
(i, word, '_', tag, tag, '_', '0', 'a', '_', '_')
input_file.write(input_str.encode("utf8"))
input_file.write(b'\n\n')
input_file.close()
cmd = ['java'] + self.additional_java_args + ['-jar', self._malt_bin,
'-w', self.working_dir,
'-c', self.mco, '-i', input_file.name,
'-o', output_file.name, '-m', 'parse']
ret = self._execute(cmd, verbose)
if ret != 0:
raise Exception("MaltParser parsing (%s) failed with exit "
"code %d" % (' '.join(cmd), ret))
# Must return iter(iter(Tree))
return (iter([dep_graph]) for dep_graph in DependencyGraph.load(output_file.name))
finally:
input_file.close()
os.remove(input_file.name)
output_file.close()
os.remove(output_file.name)
def train(self, depgraphs, verbose=False):
"""
Train MaltParser from a list of ``DependencyGraph`` objects
:param depgraphs: list of ``DependencyGraph`` objects for training input data
"""
input_file = tempfile.NamedTemporaryFile(prefix='malt_train.conll',
dir=self.working_dir,
delete=False)
try:
input_str = ('\n'.join(dg.to_conll(10) for dg in depgraphs))
input_file.write(input_str.encode("utf8"))
input_file.close()
self.train_from_file(input_file.name, verbose=verbose)
finally:
input_file.close()
os.remove(input_file.name)
def train_from_file(self, conll_file, verbose=False):
"""
Train MaltParser from a file
:param conll_file: str for the filename of the training input data
"""
if not self._malt_bin:
raise Exception("MaltParser location is not configured. Call config_malt() first.")
# If conll_file is a ZipFilePathPointer, then we need to do some extra
# massaging
if isinstance(conll_file, ZipFilePathPointer):
input_file = tempfile.NamedTemporaryFile(prefix='malt_train.conll',
dir=self.working_dir,
delete=False)
try:
conll_str = conll_file.open().read()
conll_file.close()
input_file.write(conll_str)
input_file.close()
return self.train_from_file(input_file.name, verbose=verbose)
finally:
input_file.close()
os.remove(input_file.name)
cmd = ['java', '-jar', self._malt_bin, '-w', self.working_dir,
'-c', self.mco, '-i', conll_file, '-m', 'learn']
ret = self._execute(cmd, verbose)
if ret != 0:
raise Exception("MaltParser training (%s) "
"failed with exit code %d" %
(' '.join(cmd), ret))
self._trained = True
@staticmethod
def _execute(cmd, verbose=False):
output = None if verbose else subprocess.PIPE
p = subprocess.Popen(cmd, stdout=output, stderr=output)
return p.wait()
def demo():
dg1 = DependencyGraph("""1 John _ NNP _ _ 2 SUBJ _ _
2 sees _ VB _ _ 0 ROOT _ _
3 a _ DT _ _ 4 SPEC _ _
4 dog _ NN _ _ 2 OBJ _ _
""")
dg2 = DependencyGraph("""1 John _ NNP _ _ 2 SUBJ _ _
2 walks _ VB _ _ 0 ROOT _ _
""")
verbose = False
maltParser = MaltParser()
maltParser.train([dg1,dg2], verbose=verbose)
maltParser.parse_one(['John','sees','Mary'], verbose=verbose).tree().pprint()
maltParser.parse_one(['a','man','runs'], verbose=verbose).tree().pprint()
next(maltParser.tagged_parse([('John','NNP'),('sees','VB'),('Mary','NNP')], verbose)).tree().pprint()
if __name__ == '__main__':
demo()
|
xflin/spark | refs/heads/master | examples/src/main/python/ml/chi_square_test_example.py | 45 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
from __future__ import print_function
from pyspark.sql import SparkSession
# $example on$
from pyspark.ml.linalg import Vectors
from pyspark.ml.stat import ChiSquareTest
# $example off$
"""
An example for Chi-square hypothesis testing.
Run with:
bin/spark-submit examples/src/main/python/ml/chi_square_test_example.py
"""
if __name__ == "__main__":
spark = SparkSession \
.builder \
.appName("ChiSquareTestExample") \
.getOrCreate()
# $example on$
data = [(0.0, Vectors.dense(0.5, 10.0)),
(0.0, Vectors.dense(1.5, 20.0)),
(1.0, Vectors.dense(1.5, 30.0)),
(0.0, Vectors.dense(3.5, 30.0)),
(0.0, Vectors.dense(3.5, 40.0)),
(1.0, Vectors.dense(3.5, 40.0))]
df = spark.createDataFrame(data, ["label", "features"])
r = ChiSquareTest.test(df, "features", "label").head()
print("pValues: " + str(r.pValues))
print("degreesOfFreedom: " + str(r.degreesOfFreedom))
print("statistics: " + str(r.statistics))
# $example off$
spark.stop()
|
aragos/tichu-tournament | refs/heads/master | python/openpyxl/chart/data_source.py | 3 | """
Collection of utility primitives for charts.
"""
from openpyxl.compat import unicode
from openpyxl.descriptors.serialisable import Serialisable
from openpyxl.descriptors import (
Bool,
Typed,
Alias,
String,
Integer,
Sequence,
)
from openpyxl.descriptors.excel import ExtensionList
from openpyxl.descriptors.nested import (
NestedString,
NestedText,
NestedInteger,
)
class NumFmt(Serialisable):
formatCode = String()
sourceLinked = Bool()
def __init__(self,
formatCode=None,
sourceLinked=False
):
self.formatCode = formatCode
self.sourceLinked = sourceLinked
class NumVal(Serialisable):
idx = Integer()
formatCode = NestedText(allow_none=True, expected_type=unicode)
v = NestedText(allow_none=True, expected_type=float)
def __init__(self,
idx=None,
formatCode=None,
v=None,
):
self.idx = idx
self.formatCode = formatCode
self.v = v
class NumData(Serialisable):
formatCode = NestedText(expected_type=str, allow_none=True)
ptCount = NestedInteger(allow_none=True)
pt = Sequence(expected_type=NumVal)
extLst = Typed(expected_type=ExtensionList, allow_none=True)
__elements__ = ('formatCode', 'ptCount', 'pt')
def __init__(self,
formatCode=None,
ptCount=None,
pt=(),
extLst=None,
):
self.formatCode = formatCode
self.ptCount = ptCount
self.pt = pt
class NumRef(Serialisable):
f = NestedText(expected_type=unicode)
ref = Alias('f')
numCache = Typed(expected_type=NumData, allow_none=True)
extLst = Typed(expected_type=ExtensionList, allow_none=True)
__elements__ = ('f', 'numCache')
def __init__(self,
f=None,
numCache=None,
extLst=None,
):
self.f = f
self.numCache = numCache
class StrVal(Serialisable):
tagname = "strVal"
idx = Integer()
v = NestedText(expected_type=unicode)
def __init__(self,
idx=0,
v=None,
):
self.idx = idx
self.v = v
class StrData(Serialisable):
tagname = "strData"
ptCount = NestedInteger(allow_none=True)
pt = Typed(expected_type=StrVal, allow_none=True)
extLst = Typed(expected_type=ExtensionList, allow_none=True)
__elements__ = ('ptCount', 'pt')
def __init__(self,
ptCount=None,
pt=None,
extLst=None,
):
self.ptCount = ptCount
self.pt = pt
class StrRef(Serialisable):
tagname = "strRef"
f = NestedText(expected_type=unicode, allow_none=True)
strCache = Typed(expected_type=StrData, allow_none=True)
extLst = Typed(expected_type=ExtensionList, allow_none=True)
__elements__ = ('f', 'strCache')
def __init__(self,
f=None,
strCache=None,
extLst=None,
):
self.f = f
self.strCache = strCache
class NumDataSource(Serialisable):
numRef = Typed(expected_type=NumRef, allow_none=True)
numLit = Typed(expected_type=NumData, allow_none=True)
def __init__(self,
numRef=None,
numLit=None,
):
self.numRef = numRef
self.numLit = numLit
class AxDataSource(Serialisable):
numRef = Typed(expected_type=NumRef, allow_none=True)
numLit = Typed(expected_type=NumData, allow_none=True)
strRef = Typed(expected_type=StrRef, allow_none=True)
strLit = Typed(expected_type=StrData, allow_none=True)
def __init__(self,
numRef=None,
numLit=None,
strRef=None,
strLit=None,
):
self.numRef = numRef
self.numLit = numLit
self.strRef = strRef
self.strLit = strLit
|
cxxgtxy/tensorflow | refs/heads/master | tensorflow/contrib/tensor_forest/hybrid/python/__init__.py | 183 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Initialize tensor_forest/hybrid/python."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.tensor_forest.hybrid.python import layers
from tensorflow.contrib.tensor_forest.hybrid.python import models
from tensorflow.contrib.tensor_forest.hybrid.python.ops import training_ops
|
neilalbrock/xhtml2pdf | refs/heads/master | demo/tgpisa/setup.py | 168 | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from turbogears.finddata import find_package_data
import os
execfile(os.path.join("tgpisa", "release.py"))
packages=find_packages()
package_data = find_package_data(where='tgpisa',
package='tgpisa')
if os.path.isdir('locales'):
packages.append('locales')
package_data.update(find_package_data(where='locales',
exclude=('*.po',), only_in_packages=False))
setup(
name="tgpisa",
version=version,
# uncomment the following lines if you fill them out in release.py
#description=description,
#author=author,
#author_email=email,
#url=url,
#download_url=download_url,
#license=license,
install_requires=[
"TurboGears >= 1.0.4.3",
"SQLObject>=0.8,<=0.10.0"
],
zip_safe=False,
packages=packages,
package_data=package_data,
keywords=[
# Use keywords if you'll be adding your package to the
# Python Cheeseshop
# if this has widgets, uncomment the next line
# 'turbogears.widgets',
# if this has a tg-admin command, uncomment the next line
# 'turbogears.command',
# if this has identity providers, uncomment the next line
# 'turbogears.identity.provider',
# If this is a template plugin, uncomment the next line
# 'python.templating.engines',
# If this is a full application, uncomment the next line
# 'turbogears.app',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Framework :: TurboGears',
# if this is an application that you'll distribute through
# the Cheeseshop, uncomment the next line
# 'Framework :: TurboGears :: Applications',
# if this is a package that includes widgets that you'll distribute
# through the Cheeseshop, uncomment the next line
# 'Framework :: TurboGears :: Widgets',
],
test_suite='nose.collector',
entry_points = {
'console_scripts': [
'start-tgpisa = tgpisa.commands:start',
],
},
# Uncomment next line and create a default.cfg file in your project dir
# if you want to package a default configuration in your egg.
#data_files = [('config', ['default.cfg'])],
)
|
craisins/nascarbot | refs/heads/master | plugins/validate.py | 22 | '''
Runs a given url through the w3c validator
by Vladi
'''
from util import hook, http
@hook.command
def validate(inp):
".validate <url> -- runs url through w3c markup validator"
if not inp.startswith('http://'):
inp = 'http://' + inp
url = 'http://validator.w3.org/check?uri=' + http.quote_plus(inp)
info = dict(http.open(url).info())
status = info['x-w3c-validator-status'].lower()
if status in ("valid", "invalid"):
errorcount = info['x-w3c-validator-errors']
warningcount = info['x-w3c-validator-warnings']
return "%s was found to be %s with %s errors and %s warnings." \
" see: %s" % (inp, status, errorcount, warningcount, url)
|
GeoNode/geonode | refs/heads/master | geonode/base/api/urls.py | 3 | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2020 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
from geonode.api.urls import router
from . import views
router.register(r'users', views.UserViewSet, 'users')
router.register(r'groups', views.GroupViewSet, 'group-profiles')
router.register(r'resources', views.ResourceBaseViewSet, 'base-resources')
router.register(r'owners', views.OwnerViewSet, 'owners')
router.register(r'categories', views.TopicCategoryViewSet, 'categories')
router.register(r'keywords', views.HierarchicalKeywordViewSet, 'keywords')
router.register(r'tkeywords', views.ThesaurusKeywordViewSet, 'tkeywords')
router.register(r'regions', views.RegionViewSet, 'regions')
urlpatterns = []
|
proxysh/Safejumper-for-Desktop | refs/heads/master | buildlinux/env64/local/lib/python2.7/encodings/mac_roman.py | 593 | """ Python Character Mapping Codec mac_roman generated from 'MAPPINGS/VENDORS/APPLE/ROMAN.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_table)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='mac-roman',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Table
decoding_table = (
u'\x00' # 0x00 -> CONTROL CHARACTER
u'\x01' # 0x01 -> CONTROL CHARACTER
u'\x02' # 0x02 -> CONTROL CHARACTER
u'\x03' # 0x03 -> CONTROL CHARACTER
u'\x04' # 0x04 -> CONTROL CHARACTER
u'\x05' # 0x05 -> CONTROL CHARACTER
u'\x06' # 0x06 -> CONTROL CHARACTER
u'\x07' # 0x07 -> CONTROL CHARACTER
u'\x08' # 0x08 -> CONTROL CHARACTER
u'\t' # 0x09 -> CONTROL CHARACTER
u'\n' # 0x0A -> CONTROL CHARACTER
u'\x0b' # 0x0B -> CONTROL CHARACTER
u'\x0c' # 0x0C -> CONTROL CHARACTER
u'\r' # 0x0D -> CONTROL CHARACTER
u'\x0e' # 0x0E -> CONTROL CHARACTER
u'\x0f' # 0x0F -> CONTROL CHARACTER
u'\x10' # 0x10 -> CONTROL CHARACTER
u'\x11' # 0x11 -> CONTROL CHARACTER
u'\x12' # 0x12 -> CONTROL CHARACTER
u'\x13' # 0x13 -> CONTROL CHARACTER
u'\x14' # 0x14 -> CONTROL CHARACTER
u'\x15' # 0x15 -> CONTROL CHARACTER
u'\x16' # 0x16 -> CONTROL CHARACTER
u'\x17' # 0x17 -> CONTROL CHARACTER
u'\x18' # 0x18 -> CONTROL CHARACTER
u'\x19' # 0x19 -> CONTROL CHARACTER
u'\x1a' # 0x1A -> CONTROL CHARACTER
u'\x1b' # 0x1B -> CONTROL CHARACTER
u'\x1c' # 0x1C -> CONTROL CHARACTER
u'\x1d' # 0x1D -> CONTROL CHARACTER
u'\x1e' # 0x1E -> CONTROL CHARACTER
u'\x1f' # 0x1F -> CONTROL CHARACTER
u' ' # 0x20 -> SPACE
u'!' # 0x21 -> EXCLAMATION MARK
u'"' # 0x22 -> QUOTATION MARK
u'#' # 0x23 -> NUMBER SIGN
u'$' # 0x24 -> DOLLAR SIGN
u'%' # 0x25 -> PERCENT SIGN
u'&' # 0x26 -> AMPERSAND
u"'" # 0x27 -> APOSTROPHE
u'(' # 0x28 -> LEFT PARENTHESIS
u')' # 0x29 -> RIGHT PARENTHESIS
u'*' # 0x2A -> ASTERISK
u'+' # 0x2B -> PLUS SIGN
u',' # 0x2C -> COMMA
u'-' # 0x2D -> HYPHEN-MINUS
u'.' # 0x2E -> FULL STOP
u'/' # 0x2F -> SOLIDUS
u'0' # 0x30 -> DIGIT ZERO
u'1' # 0x31 -> DIGIT ONE
u'2' # 0x32 -> DIGIT TWO
u'3' # 0x33 -> DIGIT THREE
u'4' # 0x34 -> DIGIT FOUR
u'5' # 0x35 -> DIGIT FIVE
u'6' # 0x36 -> DIGIT SIX
u'7' # 0x37 -> DIGIT SEVEN
u'8' # 0x38 -> DIGIT EIGHT
u'9' # 0x39 -> DIGIT NINE
u':' # 0x3A -> COLON
u';' # 0x3B -> SEMICOLON
u'<' # 0x3C -> LESS-THAN SIGN
u'=' # 0x3D -> EQUALS SIGN
u'>' # 0x3E -> GREATER-THAN SIGN
u'?' # 0x3F -> QUESTION MARK
u'@' # 0x40 -> COMMERCIAL AT
u'A' # 0x41 -> LATIN CAPITAL LETTER A
u'B' # 0x42 -> LATIN CAPITAL LETTER B
u'C' # 0x43 -> LATIN CAPITAL LETTER C
u'D' # 0x44 -> LATIN CAPITAL LETTER D
u'E' # 0x45 -> LATIN CAPITAL LETTER E
u'F' # 0x46 -> LATIN CAPITAL LETTER F
u'G' # 0x47 -> LATIN CAPITAL LETTER G
u'H' # 0x48 -> LATIN CAPITAL LETTER H
u'I' # 0x49 -> LATIN CAPITAL LETTER I
u'J' # 0x4A -> LATIN CAPITAL LETTER J
u'K' # 0x4B -> LATIN CAPITAL LETTER K
u'L' # 0x4C -> LATIN CAPITAL LETTER L
u'M' # 0x4D -> LATIN CAPITAL LETTER M
u'N' # 0x4E -> LATIN CAPITAL LETTER N
u'O' # 0x4F -> LATIN CAPITAL LETTER O
u'P' # 0x50 -> LATIN CAPITAL LETTER P
u'Q' # 0x51 -> LATIN CAPITAL LETTER Q
u'R' # 0x52 -> LATIN CAPITAL LETTER R
u'S' # 0x53 -> LATIN CAPITAL LETTER S
u'T' # 0x54 -> LATIN CAPITAL LETTER T
u'U' # 0x55 -> LATIN CAPITAL LETTER U
u'V' # 0x56 -> LATIN CAPITAL LETTER V
u'W' # 0x57 -> LATIN CAPITAL LETTER W
u'X' # 0x58 -> LATIN CAPITAL LETTER X
u'Y' # 0x59 -> LATIN CAPITAL LETTER Y
u'Z' # 0x5A -> LATIN CAPITAL LETTER Z
u'[' # 0x5B -> LEFT SQUARE BRACKET
u'\\' # 0x5C -> REVERSE SOLIDUS
u']' # 0x5D -> RIGHT SQUARE BRACKET
u'^' # 0x5E -> CIRCUMFLEX ACCENT
u'_' # 0x5F -> LOW LINE
u'`' # 0x60 -> GRAVE ACCENT
u'a' # 0x61 -> LATIN SMALL LETTER A
u'b' # 0x62 -> LATIN SMALL LETTER B
u'c' # 0x63 -> LATIN SMALL LETTER C
u'd' # 0x64 -> LATIN SMALL LETTER D
u'e' # 0x65 -> LATIN SMALL LETTER E
u'f' # 0x66 -> LATIN SMALL LETTER F
u'g' # 0x67 -> LATIN SMALL LETTER G
u'h' # 0x68 -> LATIN SMALL LETTER H
u'i' # 0x69 -> LATIN SMALL LETTER I
u'j' # 0x6A -> LATIN SMALL LETTER J
u'k' # 0x6B -> LATIN SMALL LETTER K
u'l' # 0x6C -> LATIN SMALL LETTER L
u'm' # 0x6D -> LATIN SMALL LETTER M
u'n' # 0x6E -> LATIN SMALL LETTER N
u'o' # 0x6F -> LATIN SMALL LETTER O
u'p' # 0x70 -> LATIN SMALL LETTER P
u'q' # 0x71 -> LATIN SMALL LETTER Q
u'r' # 0x72 -> LATIN SMALL LETTER R
u's' # 0x73 -> LATIN SMALL LETTER S
u't' # 0x74 -> LATIN SMALL LETTER T
u'u' # 0x75 -> LATIN SMALL LETTER U
u'v' # 0x76 -> LATIN SMALL LETTER V
u'w' # 0x77 -> LATIN SMALL LETTER W
u'x' # 0x78 -> LATIN SMALL LETTER X
u'y' # 0x79 -> LATIN SMALL LETTER Y
u'z' # 0x7A -> LATIN SMALL LETTER Z
u'{' # 0x7B -> LEFT CURLY BRACKET
u'|' # 0x7C -> VERTICAL LINE
u'}' # 0x7D -> RIGHT CURLY BRACKET
u'~' # 0x7E -> TILDE
u'\x7f' # 0x7F -> CONTROL CHARACTER
u'\xc4' # 0x80 -> LATIN CAPITAL LETTER A WITH DIAERESIS
u'\xc5' # 0x81 -> LATIN CAPITAL LETTER A WITH RING ABOVE
u'\xc7' # 0x82 -> LATIN CAPITAL LETTER C WITH CEDILLA
u'\xc9' # 0x83 -> LATIN CAPITAL LETTER E WITH ACUTE
u'\xd1' # 0x84 -> LATIN CAPITAL LETTER N WITH TILDE
u'\xd6' # 0x85 -> LATIN CAPITAL LETTER O WITH DIAERESIS
u'\xdc' # 0x86 -> LATIN CAPITAL LETTER U WITH DIAERESIS
u'\xe1' # 0x87 -> LATIN SMALL LETTER A WITH ACUTE
u'\xe0' # 0x88 -> LATIN SMALL LETTER A WITH GRAVE
u'\xe2' # 0x89 -> LATIN SMALL LETTER A WITH CIRCUMFLEX
u'\xe4' # 0x8A -> LATIN SMALL LETTER A WITH DIAERESIS
u'\xe3' # 0x8B -> LATIN SMALL LETTER A WITH TILDE
u'\xe5' # 0x8C -> LATIN SMALL LETTER A WITH RING ABOVE
u'\xe7' # 0x8D -> LATIN SMALL LETTER C WITH CEDILLA
u'\xe9' # 0x8E -> LATIN SMALL LETTER E WITH ACUTE
u'\xe8' # 0x8F -> LATIN SMALL LETTER E WITH GRAVE
u'\xea' # 0x90 -> LATIN SMALL LETTER E WITH CIRCUMFLEX
u'\xeb' # 0x91 -> LATIN SMALL LETTER E WITH DIAERESIS
u'\xed' # 0x92 -> LATIN SMALL LETTER I WITH ACUTE
u'\xec' # 0x93 -> LATIN SMALL LETTER I WITH GRAVE
u'\xee' # 0x94 -> LATIN SMALL LETTER I WITH CIRCUMFLEX
u'\xef' # 0x95 -> LATIN SMALL LETTER I WITH DIAERESIS
u'\xf1' # 0x96 -> LATIN SMALL LETTER N WITH TILDE
u'\xf3' # 0x97 -> LATIN SMALL LETTER O WITH ACUTE
u'\xf2' # 0x98 -> LATIN SMALL LETTER O WITH GRAVE
u'\xf4' # 0x99 -> LATIN SMALL LETTER O WITH CIRCUMFLEX
u'\xf6' # 0x9A -> LATIN SMALL LETTER O WITH DIAERESIS
u'\xf5' # 0x9B -> LATIN SMALL LETTER O WITH TILDE
u'\xfa' # 0x9C -> LATIN SMALL LETTER U WITH ACUTE
u'\xf9' # 0x9D -> LATIN SMALL LETTER U WITH GRAVE
u'\xfb' # 0x9E -> LATIN SMALL LETTER U WITH CIRCUMFLEX
u'\xfc' # 0x9F -> LATIN SMALL LETTER U WITH DIAERESIS
u'\u2020' # 0xA0 -> DAGGER
u'\xb0' # 0xA1 -> DEGREE SIGN
u'\xa2' # 0xA2 -> CENT SIGN
u'\xa3' # 0xA3 -> POUND SIGN
u'\xa7' # 0xA4 -> SECTION SIGN
u'\u2022' # 0xA5 -> BULLET
u'\xb6' # 0xA6 -> PILCROW SIGN
u'\xdf' # 0xA7 -> LATIN SMALL LETTER SHARP S
u'\xae' # 0xA8 -> REGISTERED SIGN
u'\xa9' # 0xA9 -> COPYRIGHT SIGN
u'\u2122' # 0xAA -> TRADE MARK SIGN
u'\xb4' # 0xAB -> ACUTE ACCENT
u'\xa8' # 0xAC -> DIAERESIS
u'\u2260' # 0xAD -> NOT EQUAL TO
u'\xc6' # 0xAE -> LATIN CAPITAL LETTER AE
u'\xd8' # 0xAF -> LATIN CAPITAL LETTER O WITH STROKE
u'\u221e' # 0xB0 -> INFINITY
u'\xb1' # 0xB1 -> PLUS-MINUS SIGN
u'\u2264' # 0xB2 -> LESS-THAN OR EQUAL TO
u'\u2265' # 0xB3 -> GREATER-THAN OR EQUAL TO
u'\xa5' # 0xB4 -> YEN SIGN
u'\xb5' # 0xB5 -> MICRO SIGN
u'\u2202' # 0xB6 -> PARTIAL DIFFERENTIAL
u'\u2211' # 0xB7 -> N-ARY SUMMATION
u'\u220f' # 0xB8 -> N-ARY PRODUCT
u'\u03c0' # 0xB9 -> GREEK SMALL LETTER PI
u'\u222b' # 0xBA -> INTEGRAL
u'\xaa' # 0xBB -> FEMININE ORDINAL INDICATOR
u'\xba' # 0xBC -> MASCULINE ORDINAL INDICATOR
u'\u03a9' # 0xBD -> GREEK CAPITAL LETTER OMEGA
u'\xe6' # 0xBE -> LATIN SMALL LETTER AE
u'\xf8' # 0xBF -> LATIN SMALL LETTER O WITH STROKE
u'\xbf' # 0xC0 -> INVERTED QUESTION MARK
u'\xa1' # 0xC1 -> INVERTED EXCLAMATION MARK
u'\xac' # 0xC2 -> NOT SIGN
u'\u221a' # 0xC3 -> SQUARE ROOT
u'\u0192' # 0xC4 -> LATIN SMALL LETTER F WITH HOOK
u'\u2248' # 0xC5 -> ALMOST EQUAL TO
u'\u2206' # 0xC6 -> INCREMENT
u'\xab' # 0xC7 -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\xbb' # 0xC8 -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\u2026' # 0xC9 -> HORIZONTAL ELLIPSIS
u'\xa0' # 0xCA -> NO-BREAK SPACE
u'\xc0' # 0xCB -> LATIN CAPITAL LETTER A WITH GRAVE
u'\xc3' # 0xCC -> LATIN CAPITAL LETTER A WITH TILDE
u'\xd5' # 0xCD -> LATIN CAPITAL LETTER O WITH TILDE
u'\u0152' # 0xCE -> LATIN CAPITAL LIGATURE OE
u'\u0153' # 0xCF -> LATIN SMALL LIGATURE OE
u'\u2013' # 0xD0 -> EN DASH
u'\u2014' # 0xD1 -> EM DASH
u'\u201c' # 0xD2 -> LEFT DOUBLE QUOTATION MARK
u'\u201d' # 0xD3 -> RIGHT DOUBLE QUOTATION MARK
u'\u2018' # 0xD4 -> LEFT SINGLE QUOTATION MARK
u'\u2019' # 0xD5 -> RIGHT SINGLE QUOTATION MARK
u'\xf7' # 0xD6 -> DIVISION SIGN
u'\u25ca' # 0xD7 -> LOZENGE
u'\xff' # 0xD8 -> LATIN SMALL LETTER Y WITH DIAERESIS
u'\u0178' # 0xD9 -> LATIN CAPITAL LETTER Y WITH DIAERESIS
u'\u2044' # 0xDA -> FRACTION SLASH
u'\u20ac' # 0xDB -> EURO SIGN
u'\u2039' # 0xDC -> SINGLE LEFT-POINTING ANGLE QUOTATION MARK
u'\u203a' # 0xDD -> SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
u'\ufb01' # 0xDE -> LATIN SMALL LIGATURE FI
u'\ufb02' # 0xDF -> LATIN SMALL LIGATURE FL
u'\u2021' # 0xE0 -> DOUBLE DAGGER
u'\xb7' # 0xE1 -> MIDDLE DOT
u'\u201a' # 0xE2 -> SINGLE LOW-9 QUOTATION MARK
u'\u201e' # 0xE3 -> DOUBLE LOW-9 QUOTATION MARK
u'\u2030' # 0xE4 -> PER MILLE SIGN
u'\xc2' # 0xE5 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX
u'\xca' # 0xE6 -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX
u'\xc1' # 0xE7 -> LATIN CAPITAL LETTER A WITH ACUTE
u'\xcb' # 0xE8 -> LATIN CAPITAL LETTER E WITH DIAERESIS
u'\xc8' # 0xE9 -> LATIN CAPITAL LETTER E WITH GRAVE
u'\xcd' # 0xEA -> LATIN CAPITAL LETTER I WITH ACUTE
u'\xce' # 0xEB -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX
u'\xcf' # 0xEC -> LATIN CAPITAL LETTER I WITH DIAERESIS
u'\xcc' # 0xED -> LATIN CAPITAL LETTER I WITH GRAVE
u'\xd3' # 0xEE -> LATIN CAPITAL LETTER O WITH ACUTE
u'\xd4' # 0xEF -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX
u'\uf8ff' # 0xF0 -> Apple logo
u'\xd2' # 0xF1 -> LATIN CAPITAL LETTER O WITH GRAVE
u'\xda' # 0xF2 -> LATIN CAPITAL LETTER U WITH ACUTE
u'\xdb' # 0xF3 -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX
u'\xd9' # 0xF4 -> LATIN CAPITAL LETTER U WITH GRAVE
u'\u0131' # 0xF5 -> LATIN SMALL LETTER DOTLESS I
u'\u02c6' # 0xF6 -> MODIFIER LETTER CIRCUMFLEX ACCENT
u'\u02dc' # 0xF7 -> SMALL TILDE
u'\xaf' # 0xF8 -> MACRON
u'\u02d8' # 0xF9 -> BREVE
u'\u02d9' # 0xFA -> DOT ABOVE
u'\u02da' # 0xFB -> RING ABOVE
u'\xb8' # 0xFC -> CEDILLA
u'\u02dd' # 0xFD -> DOUBLE ACUTE ACCENT
u'\u02db' # 0xFE -> OGONEK
u'\u02c7' # 0xFF -> CARON
)
### Encoding table
encoding_table=codecs.charmap_build(decoding_table)
|
darionyaphet/flink | refs/heads/master | flink-python/pyflink/common/tests/test_serialization_schemas.py | 17 | ################################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
################################################################################
from pyflink.common.serialization import JsonRowSerializationSchema, \
JsonRowDeserializationSchema, CsvRowSerializationSchema, CsvRowDeserializationSchema, \
SimpleStringSchema
from pyflink.common.typeinfo import Types
from pyflink.java_gateway import get_gateway
from pyflink.testing.test_case_utils import PyFlinkTestCase
class TestRowSerializationSchemas(PyFlinkTestCase):
def test_simple_string_schema(self):
expected_string = 'test string'
simple_string_schema = SimpleStringSchema()
self.assertEqual(expected_string.encode(encoding='utf-8'),
simple_string_schema._j_serialization_schema.serialize(expected_string))
self.assertEqual(expected_string, simple_string_schema._j_deserialization_schema
.deserialize(expected_string.encode(encoding='utf-8')))
def test_json_row_serialization_deserialization_schema(self):
jsons = ["{\"svt\":\"2020-02-24T12:58:09.209+0800\"}",
"{\"svt\":\"2020-02-24T12:58:09.209+0800\", "
"\"ops\":{\"id\":\"281708d0-4092-4c21-9233-931950b6eccf\"},\"ids\":[1, 2, 3]}",
"{\"svt\":\"2020-02-24T12:58:09.209+0800\"}"]
expected_jsons = ["{\"svt\":\"2020-02-24T12:58:09.209+0800\",\"ops\":null,\"ids\":null}",
"{\"svt\":\"2020-02-24T12:58:09.209+0800\","
"\"ops\":{\"id\":\"281708d0-4092-4c21-9233-931950b6eccf\"},"
"\"ids\":[1,2,3]}",
"{\"svt\":\"2020-02-24T12:58:09.209+0800\",\"ops\":null,\"ids\":null}"]
row_schema = Types.ROW_NAMED(["svt", "ops", "ids"],
[Types.STRING(),
Types.ROW_NAMED(['id'], [Types.STRING()]),
Types.PRIMITIVE_ARRAY(Types.INT())])
json_row_serialization_schema = JsonRowSerializationSchema.builder() \
.with_type_info(row_schema).build()
json_row_deserialization_schema = JsonRowDeserializationSchema.builder() \
.type_info(row_schema).build()
for i in range(len(jsons)):
j_row = json_row_deserialization_schema._j_deserialization_schema\
.deserialize(bytes(jsons[i], encoding='utf-8'))
result = str(json_row_serialization_schema._j_serialization_schema.serialize(j_row),
encoding='utf-8')
self.assertEqual(expected_jsons[i], result)
def test_csv_row_serialization_schema(self):
JRow = get_gateway().jvm.org.apache.flink.types.Row
j_row = JRow(3)
j_row.setField(0, "BEGIN")
j_row.setField(2, "END")
def field_assertion(field_info, csv_value, value, field_delimiter):
row_info = Types.ROW([Types.STRING(), field_info, Types.STRING()])
expected_csv = "BEGIN" + field_delimiter + csv_value + field_delimiter + "END\n"
j_row.setField(1, value)
csv_row_serialization_schema = CsvRowSerializationSchema.Builder(row_info)\
.set_escape_character('*').set_quote_character('\'')\
.set_array_element_delimiter(':').set_field_delimiter(';').build()
csv_row_deserialization_schema = CsvRowDeserializationSchema.Builder(row_info)\
.set_escape_character('*').set_quote_character('\'')\
.set_array_element_delimiter(':').set_field_delimiter(';').build()
serialized_bytes = csv_row_serialization_schema._j_serialization_schema.serialize(j_row)
self.assertEqual(expected_csv, str(serialized_bytes, encoding='utf-8'))
j_deserialized_row = csv_row_deserialization_schema._j_deserialization_schema\
.deserialize(expected_csv.encode("utf-8"))
self.assertTrue(j_row.equals(j_deserialized_row))
field_assertion(Types.STRING(), "'123''4**'", "123'4*", ";")
field_assertion(Types.STRING(), "'a;b''c'", "a;b'c", ";")
field_assertion(Types.INT(), "12", 12, ";")
test_j_row = JRow(2)
test_j_row.setField(0, "1")
test_j_row.setField(1, "hello")
field_assertion(Types.ROW([Types.STRING(), Types.STRING()]), "'1:hello'", test_j_row, ";")
test_j_row.setField(1, "hello world")
field_assertion(Types.ROW([Types.STRING(), Types.STRING()]), "'1:hello world'", test_j_row,
";")
field_assertion(Types.STRING(), "null", "null", ";")
|
Simran-B/arangodb | refs/heads/docs_3.0 | 3rdParty/V8-4.3.61/third_party/python_26/Lib/site-packages/win32comext/axdebug/stackframe.py | 17 | """Support for stack-frames.
Provides Implements a nearly complete wrapper for a stack frame.
"""
import sys
from util import _wrap, RaiseNotImpl
import expressions, gateways, axdebug, winerror
import pythoncom
from win32com.server.exception import COMException
import repr, string
from util import trace
#def trace(*args):
# pass
class EnumDebugStackFrames(gateways.EnumDebugStackFrames):
"""A class that given a debugger object, can return an enumerator
of DebugStackFrame objects.
"""
def __init__(self, debugger):
infos = []
frame = debugger.currentframe
# print "Stack check"
while frame:
# print " Checking frame", frame.f_code.co_filename, frame.f_lineno-1, frame.f_trace,
# Get a DebugCodeContext for the stack frame. If we fail, then it
# is not debuggable, and therefore not worth displaying.
cc = debugger.codeContainerProvider.FromFileName(frame.f_code.co_filename)
if cc is not None:
try:
address = frame.f_locals['__axstack_address__']
except KeyError:
# print "Couldnt find stack address for",frame.f_code.co_filename, frame.f_lineno-1
# Use this one, even tho it is wrong :-(
address = axdebug.GetStackAddress()
frameInfo = DebugStackFrame(frame, frame.f_lineno-1, cc), address, address+1, 0, None
infos.append(frameInfo)
# print "- Kept!"
# else:
# print "- rejected"
frame = frame.f_back
gateways.EnumDebugStackFrames.__init__(self, infos, 0)
# def __del__(self):
# print "EnumDebugStackFrames dieing"
def Next(self, count):
return gateways.EnumDebugStackFrames.Next(self, count)
# def _query_interface_(self, iid):
# from win32com.util import IIDToInterfaceName
# print "EnumDebugStackFrames QI with %s (%s)" % (IIDToInterfaceName(iid), str(iid))
# return 0
def _wrap(self, obj):
# This enum returns a tuple, with 2 com objects in it.
obFrame, min, lim, fFinal, obFinal = obj
obFrame = _wrap(obFrame, axdebug.IID_IDebugStackFrame)
if obFinal:
obFinal = _wrap(obFinal, pythoncom.IID_IUnknown)
return obFrame, min, lim, fFinal, obFinal
class DebugStackFrame(gateways.DebugStackFrame):
def __init__(self, frame, lineno, codeContainer):
self.frame = frame
self.lineno = lineno
self.codeContainer = codeContainer
self.expressionContext = None
# def __del__(self):
# print "DSF dieing"
def _query_interface_(self, iid):
if iid==axdebug.IID_IDebugExpressionContext:
if self.expressionContext is None:
self.expressionContext = _wrap(expressions.ExpressionContext(self.frame), axdebug.IID_IDebugExpressionContext)
return self.expressionContext
# from win32com.util import IIDToInterfaceName
# print "DebugStackFrame QI with %s (%s)" % (IIDToInterfaceName(iid), str(iid))
return 0
#
# The following need implementation
def GetThread(self):
""" Returns the thread associated with this stack frame.
Result must be a IDebugApplicationThread
"""
RaiseNotImpl("GetThread")
def GetCodeContext(self):
offset = self.codeContainer.GetPositionOfLine(self.lineno)
return self.codeContainer.GetCodeContextAtPosition(offset)
#
# The following are usefully implemented
def GetDescriptionString(self, fLong):
filename = self.frame.f_code.co_filename
s = ""
if 0: #fLong:
s = s + filename
if self.frame.f_code.co_name:
s = s + self.frame.f_code.co_name
else:
s = s + "<lambda>"
return s
def GetLanguageString(self, fLong):
if fLong:
return "Python ActiveX Scripting Engine"
else:
return "Python"
def GetDebugProperty(self):
return _wrap(StackFrameDebugProperty(self.frame), axdebug.IID_IDebugProperty)
class DebugStackFrameSniffer:
_public_methods_ = ["EnumStackFrames"]
_com_interfaces_ = [axdebug.IID_IDebugStackFrameSniffer]
def __init__(self, debugger):
self.debugger = debugger
trace("DebugStackFrameSniffer instantiated")
# def __del__(self):
# print "DSFS dieing"
def EnumStackFrames(self):
trace("DebugStackFrameSniffer.EnumStackFrames called")
return _wrap(EnumDebugStackFrames(self.debugger), axdebug.IID_IEnumDebugStackFrames)
# A DebugProperty for a stack frame.
class StackFrameDebugProperty:
_com_interfaces_ = [axdebug.IID_IDebugProperty]
_public_methods_ = ['GetPropertyInfo', 'GetExtendedInfo', 'SetValueAsString',
'EnumMembers', 'GetParent'
]
def __init__(self, frame):
self.frame = frame
def GetPropertyInfo(self, dwFieldSpec, nRadix):
RaiseNotImpl("StackFrameDebugProperty::GetPropertyInfo")
def GetExtendedInfo(self): ### Note - not in the framework.
RaiseNotImpl("StackFrameDebugProperty::GetExtendedInfo")
def SetValueAsString(self, value, radix):
#
RaiseNotImpl("DebugProperty::SetValueAsString")
def EnumMembers(self, dwFieldSpec, nRadix, iid):
print "EnumMembers", dwFieldSpec, nRadix, iid
import expressions
return expressions.MakeEnumDebugProperty(self.frame.f_locals, dwFieldSpec, nRadix, iid, self.frame)
def GetParent(self):
# return IDebugProperty
RaiseNotImpl("DebugProperty::GetParent")
|
msebire/intellij-community | refs/heads/master | python/testData/refactoring/introduceVariable/substringContainsEscapes.py | 83 | print(u"Hel<selection>lo \u00d6sterreich\\!\n</selection>\n") |
peterbraden/tensorflow | refs/heads/master | tensorflow/tools/docker/simple_console.py | 52 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Start a simple interactive console with TensorFlow available."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import code
import sys
def main(_):
"""Run an interactive console."""
code.interact()
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
|
spitfire88/upm | refs/heads/master | examples/python/tcs37727.py | 6 | #!/usr/bin/python
# Author: Norbert Wesp <nwesp@phytec.de>
# Copyright (c) 2017 Phytec Messtechnik GmbH.
#
# based on: tcs3414cs.py
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from __future__ import print_function
import time, sys, signal, atexit
from upm import pyupm_tcs37727 as TCS37727
def main():
# Instantiate the color sensor on I2C on bus 1
mySensor = TCS37727.TCS37727(1)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# This lets you run code on exit,
# including functions from mySensor
def exitHandler():
print("Exiting")
sys.exit(0)
# Register exit handlers
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
data = TCS37727.tcs37727_data_t()
# activate periodic measurements
mySensor.setActive();
# Print out the red, green, blue, clear, lux and color-temperature value
# every 0.5 seconds
while(1):
mySensor.getData(data, True)
print(data.red, data.green, data.blue, data.clear, data.lux, data.ct)
time.sleep(.5)
if __name__ == '__main__':
main()
|
alex/readthedocs.org | refs/heads/master | readthedocs/projects/migrations/0005_add_build_skipping.py | 16 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Project.skip'
db.add_column('projects_project', 'skip', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False)
def backwards(self, orm):
# Deleting field 'Project.skip'
db.delete_column('projects_project', 'skip')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'projects.file': {
'Meta': {'ordering': "('denormalized_path',)", 'object_name': 'File'},
'content': ('django.db.models.fields.TextField', [], {}),
'denormalized_path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'heading': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'ordering': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '1'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['projects.File']"}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'files'", 'to': "orm['projects.Project']"}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'}),
'status': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '1'})
},
'projects.filerevision': {
'Meta': {'ordering': "('-revision_number',)", 'object_name': 'FileRevision'},
'comment': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'diff': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'file': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'revisions'", 'to': "orm['projects.File']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_reverted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'revision_number': ('django.db.models.fields.IntegerField', [], {})
},
'projects.project': {
'Meta': {'ordering': "('-modified_date', 'name')", 'object_name': 'Project'},
'copyright': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'docs_directory': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'extensions': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'project_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
'pub_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'repo': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'repo_type': ('django.db.models.fields.CharField', [], {'default': "'git'", 'max_length': '10'}),
'skip': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'}),
'status': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '1'}),
'suffix': ('django.db.models.fields.CharField', [], {'default': "'.rst'", 'max_length': '10'}),
'theme': ('django.db.models.fields.CharField', [], {'default': "'default'", 'max_length': '20'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'projects'", 'to': "orm['auth.User']"}),
'version': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'whitelisted': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
}
}
complete_apps = ['projects']
|
tayfun/django | refs/heads/master | django/contrib/gis/db/backends/postgis/introspection.py | 70 | from django.contrib.gis.gdal import OGRGeomType
from django.db.backends.postgresql_psycopg2.introspection import \
DatabaseIntrospection
class GeoIntrospectionError(Exception):
pass
class PostGISIntrospection(DatabaseIntrospection):
# Reverse dictionary for PostGIS geometry types not populated until
# introspection is actually performed.
postgis_types_reverse = {}
ignored_tables = DatabaseIntrospection.ignored_tables + [
'geography_columns',
'geometry_columns',
'raster_columns',
'spatial_ref_sys',
'raster_overviews',
]
# Overridden from parent to include raster indices in retrieval.
# Raster indices have pg_index.indkey value 0 because they are an
# expression over the raster column through the ST_ConvexHull function.
# So the default query has to be adapted to include raster indices.
_get_indexes_query = """
SELECT DISTINCT attr.attname, idx.indkey, idx.indisunique, idx.indisprimary
FROM pg_catalog.pg_class c, pg_catalog.pg_class c2,
pg_catalog.pg_index idx, pg_catalog.pg_attribute attr
LEFT JOIN pg_catalog.pg_type t ON t.oid = attr.atttypid
WHERE
c.oid = idx.indrelid
AND idx.indexrelid = c2.oid
AND attr.attrelid = c.oid
AND (
attr.attnum = idx.indkey[0] OR
(t.typname LIKE 'raster' AND idx.indkey = '0')
)
AND attr.attnum > 0
AND c.relname = %s"""
def get_postgis_types(self):
"""
Returns a dictionary with keys that are the PostgreSQL object
identification integers for the PostGIS geometry and/or
geography types (if supported).
"""
field_types = [
('geometry', 'GeometryField'),
# The value for the geography type is actually a tuple
# to pass in the `geography=True` keyword to the field
# definition.
('geography', ('GeometryField', {'geography': True})),
]
postgis_types = {}
# The OID integers associated with the geometry type may
# be different across versions; hence, this is why we have
# to query the PostgreSQL pg_type table corresponding to the
# PostGIS custom data types.
oid_sql = 'SELECT "oid" FROM "pg_type" WHERE "typname" = %s'
cursor = self.connection.cursor()
try:
for field_type in field_types:
cursor.execute(oid_sql, (field_type[0],))
for result in cursor.fetchall():
postgis_types[result[0]] = field_type[1]
finally:
cursor.close()
return postgis_types
def get_field_type(self, data_type, description):
if not self.postgis_types_reverse:
# If the PostGIS types reverse dictionary is not populated, do so
# now. In order to prevent unnecessary requests upon connection
# initialization, the `data_types_reverse` dictionary is not updated
# with the PostGIS custom types until introspection is actually
# performed -- in other words, when this function is called.
self.postgis_types_reverse = self.get_postgis_types()
self.data_types_reverse.update(self.postgis_types_reverse)
return super(PostGISIntrospection, self).get_field_type(data_type, description)
def get_geometry_type(self, table_name, geo_col):
"""
The geometry type OID used by PostGIS does not indicate the particular
type of field that a geometry column is (e.g., whether it's a
PointField or a PolygonField). Thus, this routine queries the PostGIS
metadata tables to determine the geometry type,
"""
cursor = self.connection.cursor()
try:
try:
# First seeing if this geometry column is in the `geometry_columns`
cursor.execute('SELECT "coord_dimension", "srid", "type" '
'FROM "geometry_columns" '
'WHERE "f_table_name"=%s AND "f_geometry_column"=%s',
(table_name, geo_col))
row = cursor.fetchone()
if not row:
raise GeoIntrospectionError
except GeoIntrospectionError:
cursor.execute('SELECT "coord_dimension", "srid", "type" '
'FROM "geography_columns" '
'WHERE "f_table_name"=%s AND "f_geography_column"=%s',
(table_name, geo_col))
row = cursor.fetchone()
if not row:
raise Exception('Could not find a geometry or geography column for "%s"."%s"' %
(table_name, geo_col))
# OGRGeomType does not require GDAL and makes it easy to convert
# from OGC geom type name to Django field.
field_type = OGRGeomType(row[2]).django
# Getting any GeometryField keyword arguments that are not the default.
dim = row[0]
srid = row[1]
field_params = {}
if srid != 4326:
field_params['srid'] = srid
if dim != 2:
field_params['dim'] = dim
finally:
cursor.close()
return field_type, field_params
|
guewen/odoo | refs/heads/master | addons/sale_mrp/tests/__init__.py | 114 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Business Applications
# Copyright (c) 2012-TODAY OpenERP S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from . import test_move_explode
checks = [
test_move_explode,
]
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
agati/chimera | refs/heads/master | src/chimera/controllers/site/__init__.py | 10 | #! /usr/bin/env python
# -*- coding: iso-8859-1 -*-
# chimera - observatory automation system
# Copyright (C) 2006-2007 P. Henrique Silva <henrique@astro.ufsc.br>
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
|
cntnboys/410Lab6 | refs/heads/master | v1/lib/python2.7/site-packages/distribute-0.6.24-py2.7.egg/setuptools/tests/__init__.py | 62 | """Tests for the 'setuptools' package"""
from unittest import TestSuite, TestCase, makeSuite, defaultTestLoader
import distutils.core, distutils.cmd
from distutils.errors import DistutilsOptionError, DistutilsPlatformError
from distutils.errors import DistutilsSetupError
import setuptools, setuptools.dist
from setuptools import Feature
from distutils.core import Extension
extract_constant, get_module_constant = None, None
from setuptools.depends import *
from distutils.version import StrictVersion, LooseVersion
from distutils.util import convert_path
import sys, os.path
def additional_tests():
import doctest, unittest
suite = unittest.TestSuite((
doctest.DocFileSuite(
os.path.join('tests', 'api_tests.txt'),
optionflags=doctest.ELLIPSIS, package='pkg_resources',
),
))
if sys.platform == 'win32':
suite.addTest(doctest.DocFileSuite('win_script_wrapper.txt'))
return suite
def makeSetup(**args):
"""Return distribution from 'setup(**args)', without executing commands"""
distutils.core._setup_stop_after = "commandline"
# Don't let system command line leak into tests!
args.setdefault('script_args',['install'])
try:
return setuptools.setup(**args)
finally:
distutils.core_setup_stop_after = None
class DependsTests(TestCase):
def testExtractConst(self):
if not extract_constant: return # skip on non-bytecode platforms
def f1():
global x,y,z
x = "test"
y = z
# unrecognized name
self.assertEqual(extract_constant(f1.func_code,'q', -1), None)
# constant assigned
self.assertEqual(extract_constant(f1.func_code,'x', -1), "test")
# expression assigned
self.assertEqual(extract_constant(f1.func_code,'y', -1), -1)
# recognized name, not assigned
self.assertEqual(extract_constant(f1.func_code,'z', -1), None)
def testFindModule(self):
self.assertRaises(ImportError, find_module, 'no-such.-thing')
self.assertRaises(ImportError, find_module, 'setuptools.non-existent')
f,p,i = find_module('setuptools.tests'); f.close()
def testModuleExtract(self):
if not get_module_constant: return # skip on non-bytecode platforms
from email import __version__
self.assertEqual(
get_module_constant('email','__version__'), __version__
)
self.assertEqual(
get_module_constant('sys','version'), sys.version
)
self.assertEqual(
get_module_constant('setuptools.tests','__doc__'),__doc__
)
def testRequire(self):
if not extract_constant: return # skip on non-bytecode platforms
req = Require('Email','1.0.3','email')
self.assertEqual(req.name, 'Email')
self.assertEqual(req.module, 'email')
self.assertEqual(req.requested_version, '1.0.3')
self.assertEqual(req.attribute, '__version__')
self.assertEqual(req.full_name(), 'Email-1.0.3')
from email import __version__
self.assertEqual(req.get_version(), __version__)
self.assert_(req.version_ok('1.0.9'))
self.assert_(not req.version_ok('0.9.1'))
self.assert_(not req.version_ok('unknown'))
self.assert_(req.is_present())
self.assert_(req.is_current())
req = Require('Email 3000','03000','email',format=LooseVersion)
self.assert_(req.is_present())
self.assert_(not req.is_current())
self.assert_(not req.version_ok('unknown'))
req = Require('Do-what-I-mean','1.0','d-w-i-m')
self.assert_(not req.is_present())
self.assert_(not req.is_current())
req = Require('Tests', None, 'tests', homepage="http://example.com")
self.assertEqual(req.format, None)
self.assertEqual(req.attribute, None)
self.assertEqual(req.requested_version, None)
self.assertEqual(req.full_name(), 'Tests')
self.assertEqual(req.homepage, 'http://example.com')
paths = [os.path.dirname(p) for p in __path__]
self.assert_(req.is_present(paths))
self.assert_(req.is_current(paths))
class DistroTests(TestCase):
def setUp(self):
self.e1 = Extension('bar.ext',['bar.c'])
self.e2 = Extension('c.y', ['y.c'])
self.dist = makeSetup(
packages=['a', 'a.b', 'a.b.c', 'b', 'c'],
py_modules=['b.d','x'],
ext_modules = (self.e1, self.e2),
package_dir = {},
)
def testDistroType(self):
self.assert_(isinstance(self.dist,setuptools.dist.Distribution))
def testExcludePackage(self):
self.dist.exclude_package('a')
self.assertEqual(self.dist.packages, ['b','c'])
self.dist.exclude_package('b')
self.assertEqual(self.dist.packages, ['c'])
self.assertEqual(self.dist.py_modules, ['x'])
self.assertEqual(self.dist.ext_modules, [self.e1, self.e2])
self.dist.exclude_package('c')
self.assertEqual(self.dist.packages, [])
self.assertEqual(self.dist.py_modules, ['x'])
self.assertEqual(self.dist.ext_modules, [self.e1])
# test removals from unspecified options
makeSetup().exclude_package('x')
def testIncludeExclude(self):
# remove an extension
self.dist.exclude(ext_modules=[self.e1])
self.assertEqual(self.dist.ext_modules, [self.e2])
# add it back in
self.dist.include(ext_modules=[self.e1])
self.assertEqual(self.dist.ext_modules, [self.e2, self.e1])
# should not add duplicate
self.dist.include(ext_modules=[self.e1])
self.assertEqual(self.dist.ext_modules, [self.e2, self.e1])
def testExcludePackages(self):
self.dist.exclude(packages=['c','b','a'])
self.assertEqual(self.dist.packages, [])
self.assertEqual(self.dist.py_modules, ['x'])
self.assertEqual(self.dist.ext_modules, [self.e1])
def testEmpty(self):
dist = makeSetup()
dist.include(packages=['a'], py_modules=['b'], ext_modules=[self.e2])
dist = makeSetup()
dist.exclude(packages=['a'], py_modules=['b'], ext_modules=[self.e2])
def testContents(self):
self.assert_(self.dist.has_contents_for('a'))
self.dist.exclude_package('a')
self.assert_(not self.dist.has_contents_for('a'))
self.assert_(self.dist.has_contents_for('b'))
self.dist.exclude_package('b')
self.assert_(not self.dist.has_contents_for('b'))
self.assert_(self.dist.has_contents_for('c'))
self.dist.exclude_package('c')
self.assert_(not self.dist.has_contents_for('c'))
def testInvalidIncludeExclude(self):
self.assertRaises(DistutilsSetupError,
self.dist.include, nonexistent_option='x'
)
self.assertRaises(DistutilsSetupError,
self.dist.exclude, nonexistent_option='x'
)
self.assertRaises(DistutilsSetupError,
self.dist.include, packages={'x':'y'}
)
self.assertRaises(DistutilsSetupError,
self.dist.exclude, packages={'x':'y'}
)
self.assertRaises(DistutilsSetupError,
self.dist.include, ext_modules={'x':'y'}
)
self.assertRaises(DistutilsSetupError,
self.dist.exclude, ext_modules={'x':'y'}
)
self.assertRaises(DistutilsSetupError,
self.dist.include, package_dir=['q']
)
self.assertRaises(DistutilsSetupError,
self.dist.exclude, package_dir=['q']
)
class FeatureTests(TestCase):
def setUp(self):
self.req = Require('Distutils','1.0.3','distutils')
self.dist = makeSetup(
features={
'foo': Feature("foo",standard=True,require_features=['baz',self.req]),
'bar': Feature("bar", standard=True, packages=['pkg.bar'],
py_modules=['bar_et'], remove=['bar.ext'],
),
'baz': Feature(
"baz", optional=False, packages=['pkg.baz'],
scripts = ['scripts/baz_it'],
libraries=[('libfoo','foo/foofoo.c')]
),
'dwim': Feature("DWIM", available=False, remove='bazish'),
},
script_args=['--without-bar', 'install'],
packages = ['pkg.bar', 'pkg.foo'],
py_modules = ['bar_et', 'bazish'],
ext_modules = [Extension('bar.ext',['bar.c'])]
)
def testDefaults(self):
self.assert_(not
Feature(
"test",standard=True,remove='x',available=False
).include_by_default()
)
self.assert_(
Feature("test",standard=True,remove='x').include_by_default()
)
# Feature must have either kwargs, removes, or require_features
self.assertRaises(DistutilsSetupError, Feature, "test")
def testAvailability(self):
self.assertRaises(
DistutilsPlatformError,
self.dist.features['dwim'].include_in, self.dist
)
def testFeatureOptions(self):
dist = self.dist
self.assert_(
('with-dwim',None,'include DWIM') in dist.feature_options
)
self.assert_(
('without-dwim',None,'exclude DWIM (default)') in dist.feature_options
)
self.assert_(
('with-bar',None,'include bar (default)') in dist.feature_options
)
self.assert_(
('without-bar',None,'exclude bar') in dist.feature_options
)
self.assertEqual(dist.feature_negopt['without-foo'],'with-foo')
self.assertEqual(dist.feature_negopt['without-bar'],'with-bar')
self.assertEqual(dist.feature_negopt['without-dwim'],'with-dwim')
self.assert_(not 'without-baz' in dist.feature_negopt)
def testUseFeatures(self):
dist = self.dist
self.assertEqual(dist.with_foo,1)
self.assertEqual(dist.with_bar,0)
self.assertEqual(dist.with_baz,1)
self.assert_(not 'bar_et' in dist.py_modules)
self.assert_(not 'pkg.bar' in dist.packages)
self.assert_('pkg.baz' in dist.packages)
self.assert_('scripts/baz_it' in dist.scripts)
self.assert_(('libfoo','foo/foofoo.c') in dist.libraries)
self.assertEqual(dist.ext_modules,[])
self.assertEqual(dist.require_features, [self.req])
# If we ask for bar, it should fail because we explicitly disabled
# it on the command line
self.assertRaises(DistutilsOptionError, dist.include_feature, 'bar')
def testFeatureWithInvalidRemove(self):
self.assertRaises(
SystemExit, makeSetup, features = {'x':Feature('x', remove='y')}
)
class TestCommandTests(TestCase):
def testTestIsCommand(self):
test_cmd = makeSetup().get_command_obj('test')
self.assert_(isinstance(test_cmd, distutils.cmd.Command))
def testLongOptSuiteWNoDefault(self):
ts1 = makeSetup(script_args=['test','--test-suite=foo.tests.suite'])
ts1 = ts1.get_command_obj('test')
ts1.ensure_finalized()
self.assertEqual(ts1.test_suite, 'foo.tests.suite')
def testDefaultSuite(self):
ts2 = makeSetup(test_suite='bar.tests.suite').get_command_obj('test')
ts2.ensure_finalized()
self.assertEqual(ts2.test_suite, 'bar.tests.suite')
def testDefaultWModuleOnCmdLine(self):
ts3 = makeSetup(
test_suite='bar.tests',
script_args=['test','-m','foo.tests']
).get_command_obj('test')
ts3.ensure_finalized()
self.assertEqual(ts3.test_module, 'foo.tests')
self.assertEqual(ts3.test_suite, 'foo.tests.test_suite')
def testConflictingOptions(self):
ts4 = makeSetup(
script_args=['test','-m','bar.tests', '-s','foo.tests.suite']
).get_command_obj('test')
self.assertRaises(DistutilsOptionError, ts4.ensure_finalized)
def testNoSuite(self):
ts5 = makeSetup().get_command_obj('test')
ts5.ensure_finalized()
self.assertEqual(ts5.test_suite, None)
|
rizumu/django | refs/heads/master | tests/m2m_multiple/tests.py | 227 | from __future__ import unicode_literals
from datetime import datetime
from django.test import TestCase
from .models import Article, Category
class M2MMultipleTests(TestCase):
def test_multiple(self):
c1, c2, c3, c4 = [
Category.objects.create(name=name)
for name in ["Sports", "News", "Crime", "Life"]
]
a1 = Article.objects.create(
headline="Parrot steals", pub_date=datetime(2005, 11, 27)
)
a1.primary_categories.add(c2, c3)
a1.secondary_categories.add(c4)
a2 = Article.objects.create(
headline="Parrot runs", pub_date=datetime(2005, 11, 28)
)
a2.primary_categories.add(c1, c2)
a2.secondary_categories.add(c4)
self.assertQuerysetEqual(
a1.primary_categories.all(), [
"Crime",
"News",
],
lambda c: c.name
)
self.assertQuerysetEqual(
a2.primary_categories.all(), [
"News",
"Sports",
],
lambda c: c.name
)
self.assertQuerysetEqual(
a1.secondary_categories.all(), [
"Life",
],
lambda c: c.name
)
self.assertQuerysetEqual(
c1.primary_article_set.all(), [
"Parrot runs",
],
lambda a: a.headline
)
self.assertQuerysetEqual(
c1.secondary_article_set.all(), []
)
self.assertQuerysetEqual(
c2.primary_article_set.all(), [
"Parrot steals",
"Parrot runs",
],
lambda a: a.headline
)
self.assertQuerysetEqual(
c2.secondary_article_set.all(), []
)
self.assertQuerysetEqual(
c3.primary_article_set.all(), [
"Parrot steals",
],
lambda a: a.headline
)
self.assertQuerysetEqual(
c3.secondary_article_set.all(), []
)
self.assertQuerysetEqual(
c4.primary_article_set.all(), []
)
self.assertQuerysetEqual(
c4.secondary_article_set.all(), [
"Parrot steals",
"Parrot runs",
],
lambda a: a.headline
)
|
Evervolv/android_external_chromium_org | refs/heads/kitkat | tools/telemetry/telemetry/page/page.py | 23 | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import re
import time
import urlparse
from telemetry.core import util
def _UrlPathJoin(*args):
"""Joins each path in |args| for insertion into a URL path.
This is distinct from os.path.join in that:
1. Forward slashes are always used.
2. Paths beginning with '/' are not treated as absolute.
For example:
_UrlPathJoin('a', 'b') => 'a/b'
_UrlPathJoin('a/', 'b') => 'a/b'
_UrlPathJoin('a', '/b') => 'a/b'
_UrlPathJoin('a/', '/b') => 'a/b'
"""
if not args:
return ''
if len(args) == 1:
return str(args[0])
else:
args = [str(arg).replace('\\', '/') for arg in args]
work = [args[0]]
for arg in args[1:]:
if not arg:
continue
if arg.startswith('/'):
work.append(arg[1:])
else:
work.append(arg)
joined = reduce(os.path.join, work)
return joined.replace('\\', '/')
class Page(object):
def __init__(self, url, page_set, attributes=None, base_dir=None):
parsed_url = urlparse.urlparse(url)
if not parsed_url.scheme:
abspath = os.path.abspath(os.path.join(base_dir, parsed_url.path))
if os.path.exists(abspath):
url = 'file://%s' % os.path.abspath(os.path.join(base_dir, url))
else:
raise Exception('URLs must be fully qualified: %s' % url)
self.url = url
self.page_set = page_set
self.base_dir = base_dir
# These attributes can be set dynamically by the page.
self.credentials = None
self.disabled = False
self.script_to_evaluate_on_commit = None
if attributes:
for k, v in attributes.iteritems():
setattr(self, k, v)
def __getattr__(self, name):
if self.page_set and hasattr(self.page_set, name):
return getattr(self.page_set, name)
raise AttributeError()
@property
def is_file(self):
parsed_url = urlparse.urlparse(self.url)
return parsed_url.scheme == 'file'
@property
def is_local(self):
parsed_url = urlparse.urlparse(self.url)
return parsed_url.scheme == 'file' or parsed_url.scheme == 'chrome'
@property
def serving_dirs_and_file(self):
parsed_url = urlparse.urlparse(self.url)
path = _UrlPathJoin(self.base_dir, parsed_url.netloc, parsed_url.path)
if hasattr(self.page_set, 'serving_dirs'):
url_base_dir = os.path.commonprefix(self.page_set.serving_dirs)
base_path = _UrlPathJoin(self.base_dir, url_base_dir)
return ([_UrlPathJoin(self.base_dir, d)
for d in self.page_set.serving_dirs],
path.replace(base_path, ''))
return os.path.split(path)
# A version of this page's URL that's safe to use as a filename.
@property
def url_as_file_safe_name(self):
# Just replace all special characters in the url with underscore.
return re.sub('[^a-zA-Z0-9]', '_', self.display_url)
@property
def display_url(self):
if not self.is_local:
return self.url
url_paths = ['/'.join(p.url.strip('/').split('/')[:-1])
for p in self.page_set if p.is_file]
common_prefix = os.path.commonprefix(url_paths)
return self.url[len(common_prefix):].strip('/')
@property
def archive_path(self):
return self.page_set.WprFilePathForPage(self)
def __str__(self):
return self.url
def WaitToLoad(self, tab, timeout, poll_interval=0.1):
Page.WaitForPageToLoad(self, tab, timeout, poll_interval)
# TODO(dtu): Remove this method when no page sets use a click interaction
# with a wait condition. crbug.com/168431
@staticmethod
def WaitForPageToLoad(obj, tab, timeout, poll_interval=0.1):
"""Waits for various wait conditions present in obj."""
if hasattr(obj, 'wait_seconds'):
time.sleep(obj.wait_seconds)
if hasattr(obj, 'wait_for_element_with_text'):
callback_code = 'function(element) { return element != null; }'
util.WaitFor(
lambda: util.FindElementAndPerformAction(
tab, obj.wait_for_element_with_text, callback_code),
timeout, poll_interval)
if hasattr(obj, 'wait_for_element_with_selector'):
util.WaitFor(lambda: tab.EvaluateJavaScript(
'document.querySelector(\'' + obj.wait_for_element_with_selector +
'\') != null'), timeout, poll_interval)
if hasattr(obj, 'post_navigate_javascript_to_execute'):
tab.EvaluateJavaScript(obj.post_navigate_javascript_to_execute)
if hasattr(obj, 'wait_for_javascript_expression'):
util.WaitFor(
lambda: tab.EvaluateJavaScript(obj.wait_for_javascript_expression),
timeout, poll_interval)
|
iabdalkader/micropython | refs/heads/master | tests/pyb/i2c.py | 16 | import pyb
from pyb import I2C
# test we can correctly create by id
for bus in (-1, 0, 1):
try:
I2C(bus)
print("I2C", bus)
except ValueError:
print("ValueError", bus)
i2c = I2C(1)
i2c.init(I2C.MASTER, baudrate=400000)
print(i2c.scan())
i2c.deinit()
|
rootstock/bitcoinj | refs/heads/master | examples/src/main/python/forwarding.py | 21 | # Copyright by the original author or authors.
#
# 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.
# An example of how to use Jython to implement the "Getting Started" tutorial app, which receives coins and simply
# sends them on (minus a fee).
__author__ = "richard 'ragmondo' green"
import sys
# Change this to point to where you have a copy of the bitcoinj.jar
sys.path.append(r"/path/to/bitcoinj-core-0.12-bundled.jar")
# This is the address to forward all payments to. Change this (unless you want to send me some testnet coins)
my_address_text = "mzEjmna15T7DXj4HC9MBEG2UJzgFfEYtFo"
# 0 for instant send, 1 for a more realistic example
# if the wallet has no btc in it, then set to 1.
# if it has a confirmed balance in it, then you can set it to 0.
confirm_wait = 1
from org.bitcoinj.core import *
import org.bitcoinj.crypto.KeyCrypterException
import org.bitcoinj.params.MainNetParams
from org.bitcoinj.kits import WalletAppKit
from com.google.common.util.concurrent import FutureCallback
from com.google.common.util.concurrent import Futures
import java.io.File
import sys
def loud_exceptions(*args):
def _trace(func):
def wrapper(*args, **kwargs):
try:
func(*args, **kwargs)
except Exception, e:
print "** python exception ",e
raise
except java.lang.Exception,e:
print "** java exception",e
raise
return wrapper
if len(args) == 1 and callable(args[0]):
return _trace(args[0])
else:
return _trace
@loud_exceptions
def forwardCoins(tx,w,pg,addr):
v = tx.getValueSentToMe(w)
amountToSend = v.subtract(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE)
sr = w.sendCoins(pg, addr, amountToSend)
class SenderListener(AbstractWalletEventListener):
def __init__(self,pg,address):
super(SenderListener,self). __init__()
self.peerGroup = pg
self.address = address
@loud_exceptions
def onCoinsReceived(self, w, tx, pb, nb):
print "tx received", tx
v = tx.getValueSentToMe(w)
class myFutureCallback(FutureCallback):
@loud_exceptions
def onSuccess(selfx, txn):
forwardCoins(tx,w,self.peerGroup, self.address)
print "creating %s confirm callback..." % (confirm_wait)
Futures.addCallback(tx.getConfidence().getDepthFuture(confirm_wait), myFutureCallback())
if __name__ == "__main__":
params = org.bitcoinj.params.TestNet3Params.get()
my_address = Address(params,my_address_text)
filePrefix = "forwarding-service-testnet"
f = java.io.File(".")
kit = WalletAppKit(params, f, filePrefix);
print "starting and initialising (please wait).."
kit.startAsync()
kit.awaitRunning()
pg = kit.peerGroup()
wallet = kit.wallet()
sendToAddress = kit.wallet().currentReceiveKey().toAddress(params)
print "send test coins to ", sendToAddress, "qrcode - http://qrickit.com/api/qr?d=%s" % (sendToAddress) # no affiliation with qrickit..
sl = SenderListener(pg,my_address)
wallet.addEventListener(sl)
print "finished initialising .. now in main event loop"
|
iut-ibk/DynaMind-UrbanSim | refs/heads/master | 3rdparty/opus/src/washtenaw/indicators/obsolete/create_multiple_year_indicators.py | 2 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
def get_multiple_year_indicators(config):
indicators = [
{'dataset':'alldata',
'image_type':'table',
'attribute':'Residential_Units = alldata.aggregate_all(urbansim.gridcell.residential_units,function=sum)'
},
{'dataset':'alldata',
'image_type':'table',
'attribute':'Commercial_SQFT = alldata.aggregate_all(urbansim.gridcell.commercial_sqft,function=sum)'
},
{'dataset':'alldata',
'image_type':'table',
'attribute':'Industrial_SQFT = alldata.aggregate_all(urbansim.gridcell.industrial_sqft,function=sum)'
},
{'dataset':'alldata',
'image_type':'table',
'attribute':'Developed_Cells = alldata.aggregate_all(urbansim.gridcell.is_developed,function=sum)'
},
{'dataset':'alldata',
'image_type':'table',
'attribute':{'indicator_name':'residential_vacancy_rate',
'operation':'divide',
'arguments':['alldata.aggregate_all(urbansim.gridcell.vacant_residential_units,function=sum)',
'alldata.aggregate_all(urbansim.gridcell.residential_units,function=sum)']
}
},
{'dataset':'alldata',
'image_type':'table',
'attribute':{'indicator_name':'commercial_vacancy_rate',
'operation':'divide',
'arguments':['alldata.aggregate_all(urbansim.gridcell.vacant_commercial_sqft,function=sum)',
'alldata.aggregate_all(urbansim.gridcell.commercial_sqft,function=sum)']
}
},
{'dataset':'alldata',
'image_type':'table',
'attribute':{'indicator_name':'industrial_vacancy_rate',
'operation':'divide',
'arguments':['alldata.aggregate_all(urbansim.gridcell.vacant_industrial_sqft,function=sum)',
'alldata.aggregate_all(urbansim.gridcell.industrial_sqft,function=sum)']
}
},
#{'dataset':'alldata',
#'image_type':'table',
#'attribute':'psrc.zone.employment_within_30_minutes_travel_time_hbw_am_transit_walk'
#},
#{'dataset':'alldata',
#'image_type':'table',
#'attribute':'psrc.zone.employment_within_30_minutes_travel_time_hbw_am_walk'
#},
#{'dataset':'zone',
#'image_type':'table',
#'attribute':'psrc.county.number_of_jobs'
#},
]
return indicators
if __name__ == '__main__':
import os
from indicator_config import config
from urbansim.indicators.indicator_factory import IndicatorFactory
config['years'] = range(2000,2001)
IndicatorFactory().create_indicators(config, get_multiple_year_indicators(config)) |
4eek/edx-platform | refs/heads/master | lms/djangoapps/verify_student/migrations/0008_auto__del_field_verificationcheckpoint_checkpoint_name__add_field_veri.py | 84 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Removing unique constraint on 'VerificationCheckpoint', fields ['course_id', 'checkpoint_name']
db.delete_unique('verify_student_verificationcheckpoint', ['course_id', 'checkpoint_name'])
# Deleting field 'VerificationCheckpoint.checkpoint_name'
db.delete_column('verify_student_verificationcheckpoint', 'checkpoint_name')
# Adding field 'VerificationCheckpoint.checkpoint_location'
db.add_column('verify_student_verificationcheckpoint', 'checkpoint_location',
self.gf('django.db.models.fields.CharField')(default='', max_length=255),
keep_default=False)
# Adding unique constraint on 'VerificationCheckpoint', fields ['course_id', 'checkpoint_location']
db.create_unique('verify_student_verificationcheckpoint', ['course_id', 'checkpoint_location'])
# Deleting field 'VerificationStatus.location_id'
db.delete_column('verify_student_verificationstatus', 'location_id')
def backwards(self, orm):
# Removing unique constraint on 'VerificationCheckpoint', fields ['course_id', 'checkpoint_location']
db.delete_unique('verify_student_verificationcheckpoint', ['course_id', 'checkpoint_location'])
# User chose to not deal with backwards NULL issues for 'VerificationCheckpoint.checkpoint_name'
raise RuntimeError("Cannot reverse this migration. 'VerificationCheckpoint.checkpoint_name' and its values cannot be restored.")
# The following code is provided here to aid in writing a correct migration # Adding field 'VerificationCheckpoint.checkpoint_name'
db.add_column('verify_student_verificationcheckpoint', 'checkpoint_name',
self.gf('django.db.models.fields.CharField')(max_length=32),
keep_default=False)
# Deleting field 'VerificationCheckpoint.checkpoint_location'
db.delete_column('verify_student_verificationcheckpoint', 'checkpoint_location')
# Adding unique constraint on 'VerificationCheckpoint', fields ['course_id', 'checkpoint_name']
db.create_unique('verify_student_verificationcheckpoint', ['course_id', 'checkpoint_name'])
# Adding field 'VerificationStatus.location_id'
db.add_column('verify_student_verificationstatus', 'location_id',
self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True),
keep_default=False)
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'reverification.midcoursereverificationwindow': {
'Meta': {'object_name': 'MidcourseReverificationWindow'},
'course_id': ('xmodule_django.models.CourseKeyField', [], {'max_length': '255', 'db_index': 'True'}),
'end_date': ('django.db.models.fields.DateTimeField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'start_date': ('django.db.models.fields.DateTimeField', [], {'default': 'None', 'null': 'True', 'blank': 'True'})
},
'verify_student.incoursereverificationconfiguration': {
'Meta': {'object_name': 'InCourseReverificationConfiguration'},
'change_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'on_delete': 'models.PROTECT'}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'verify_student.skippedreverification': {
'Meta': {'unique_together': "(('user', 'course_id'),)", 'object_name': 'SkippedReverification'},
'checkpoint': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'skipped_checkpoint'", 'to': "orm['verify_student.VerificationCheckpoint']"}),
'course_id': ('xmodule_django.models.CourseKeyField', [], {'max_length': '255', 'db_index': 'True'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'verify_student.softwaresecurephotoverification': {
'Meta': {'ordering': "['-created_at']", 'object_name': 'SoftwareSecurePhotoVerification'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'display': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}),
'error_code': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}),
'error_msg': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'face_image_url': ('django.db.models.fields.URLField', [], {'max_length': '255', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'photo_id_image_url': ('django.db.models.fields.URLField', [], {'max_length': '255', 'blank': 'True'}),
'photo_id_key': ('django.db.models.fields.TextField', [], {'max_length': '1024'}),
'receipt_id': ('django.db.models.fields.CharField', [], {'default': "'4ae40fdd-c39a-4a23-a593-41beec90013b'", 'max_length': '255', 'db_index': 'True'}),
'reviewing_service': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'reviewing_user': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'photo_verifications_reviewed'", 'null': 'True', 'to': "orm['auth.User']"}),
'status': ('model_utils.fields.StatusField', [], {'default': "'created'", 'max_length': '100', u'no_check_for_status': 'True'}),
'status_changed': ('model_utils.fields.MonitorField', [], {'default': 'datetime.datetime.now', u'monitor': "u'status'"}),
'submitted_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'window': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['reverification.MidcourseReverificationWindow']", 'null': 'True'})
},
'verify_student.verificationcheckpoint': {
'Meta': {'unique_together': "(('course_id', 'checkpoint_location'),)", 'object_name': 'VerificationCheckpoint'},
'checkpoint_location': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'course_id': ('xmodule_django.models.CourseKeyField', [], {'max_length': '255', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'photo_verification': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['verify_student.SoftwareSecurePhotoVerification']", 'symmetrical': 'False'})
},
'verify_student.verificationstatus': {
'Meta': {'object_name': 'VerificationStatus'},
'checkpoint': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'checkpoint_status'", 'to': "orm['verify_student.VerificationCheckpoint']"}),
'error': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'response': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}),
'timestamp': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
}
}
complete_apps = ['verify_student'] |
camptocamp/c2c-rd-addons | refs/heads/8.0 | c2c_managment_board/__openerp__.py | 4 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
# $Id$
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{ 'sequence': 500,
'name': 'Dashboard for Management',
'version': '1.0',
'category': 'Board/Management Dashboard',
'description': """
This module implements a dashboard for management
* financial development last 13 weeks
* Sale orders
* Purchase Orders
* Invoices
* Financial status (For short term bank+cash accounts use user_type.code = cash)
ToDo: make it multicompany ready
""",
'author': 'ChriCar Beteiligungs- und Beratungs- GmbH',
'depends': ['board', 'sale', 'purchase', 'account'],
'data': ['management_board.xml','management_board_graph.xml','security/ir.model.access.csv'],
'demo_xml': [],
'installable': False,
'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
datenbetrieb/odoo | refs/heads/8.0 | addons/l10n_ar/__init__.py | 2120 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2011 Cubic ERP - Teradata SAC. (http://cubicerp.com).
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
##############################################################################
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
hehongliang/tensorflow | refs/heads/master | tensorflow/contrib/tensor_forest/python/ops/data_ops.py | 90 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Ops for preprocessing data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.tensor_forest.python.ops import tensor_forest_ops
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import sparse_ops
from tensorflow.python.platform import tf_logging as logging
# Data column types for indicating categorical or other non-float values.
DATA_FLOAT = 0
DATA_CATEGORICAL = 1
DTYPE_TO_FTYPE = {
dtypes.string: DATA_CATEGORICAL,
dtypes.int32: DATA_CATEGORICAL,
dtypes.int64: DATA_CATEGORICAL,
dtypes.float32: DATA_FLOAT,
dtypes.float64: DATA_FLOAT
}
def CastToFloat(tensor):
if tensor.dtype == dtypes.string:
return tensor_forest_ops.reinterpret_string_to_float(tensor)
elif tensor.dtype.is_integer:
return math_ops.to_float(tensor)
else:
return tensor
# TODO(gilberth): If protos are ever allowed in dynamically loaded custom
# op libraries, convert this to a proto like a sane person.
class TensorForestDataSpec(object):
def __init__(self):
self.sparse = DataColumnCollection()
self.dense = DataColumnCollection()
self.dense_features_size = 0
def SerializeToString(self):
return 'dense_features_size: %d dense: [%s] sparse: [%s]' % (
self.dense_features_size, self.dense.SerializeToString(),
self.sparse.SerializeToString())
class DataColumnCollection(object):
"""Collection of DataColumns, meant to mimic a proto repeated field."""
def __init__(self):
self.cols = []
def add(self): # pylint: disable=invalid-name
self.cols.append(DataColumn())
return self.cols[-1]
def size(self): # pylint: disable=invalid-name
return len(self.cols)
def SerializeToString(self):
ret = ''
for c in self.cols:
ret += '{%s}' % c.SerializeToString()
return ret
class DataColumn(object):
def __init__(self):
self.name = ''
self.original_type = ''
self.size = 0
def SerializeToString(self):
return 'name: {0} original_type: {1} size: {2}'.format(self.name,
self.original_type,
self.size)
def GetColumnName(column_key, col_num):
if isinstance(column_key, str):
return column_key
else:
return getattr(column_key, 'column_name', str(col_num))
def ParseDataTensorOrDict(data):
"""Return a tensor to use for input data.
The incoming features can be a dict where keys are the string names of the
columns, which we turn into a single 2-D tensor.
Args:
data: `Tensor` or `dict` of `Tensor` objects.
Returns:
A 2-D tensor for input to tensor_forest, a keys tensor for the
tf.Examples if they exist, and a list of the type of each column
(e.g. continuous float, categorical).
"""
data_spec = TensorForestDataSpec()
if isinstance(data, dict):
dense_features_size = 0
dense_features = []
sparse_features = []
for k in sorted(data.keys()):
is_sparse = isinstance(data[k], sparse_tensor.SparseTensor)
if is_sparse:
# TODO(gilberth): support sparse continuous.
if data[k].dtype == dtypes.float32:
logging.info('TensorForest does not support sparse continuous.')
continue
elif data_spec.sparse.size() == 0:
col_spec = data_spec.sparse.add()
col_spec.original_type = DATA_CATEGORICAL
col_spec.name = 'all_sparse'
col_spec.size = -1
sparse_features.append(
sparse_tensor.SparseTensor(data[
k].indices, CastToFloat(data[k].values), data[k].dense_shape))
else:
col_spec = data_spec.dense.add()
col_spec.original_type = DTYPE_TO_FTYPE[data[k].dtype]
col_spec.name = GetColumnName(k, len(dense_features))
# the second dimension of get_shape should always be known.
shape = data[k].get_shape()
if len(shape) == 1:
col_spec.size = 1
else:
col_spec.size = shape[1].value
dense_features_size += col_spec.size
dense_features.append(CastToFloat(data[k]))
processed_dense_features = None
processed_sparse_features = None
if dense_features:
processed_dense_features = array_ops.concat(dense_features, 1)
data_spec.dense_features_size = dense_features_size
if sparse_features:
processed_sparse_features = sparse_ops.sparse_concat(1, sparse_features)
logging.info(data_spec.SerializeToString())
return processed_dense_features, processed_sparse_features, data_spec
elif isinstance(data, sparse_tensor.SparseTensor):
col_spec = data_spec.sparse.add()
col_spec.name = 'sparse_features'
col_spec.original_type = DTYPE_TO_FTYPE[data.dtype]
col_spec.size = -1
data_spec.dense_features_size = 0
return None, data, data_spec
else:
data = ops.convert_to_tensor(data)
col_spec = data_spec.dense.add()
col_spec.name = 'dense_features'
col_spec.original_type = DTYPE_TO_FTYPE[data.dtype]
col_spec.size = data.get_shape()[1]
data_spec.dense_features_size = col_spec.size
return data, None, data_spec
def ParseLabelTensorOrDict(labels):
"""Return a tensor to use for input labels to tensor_forest.
The incoming targets can be a dict where keys are the string names of the
columns, which we turn into a single 1-D tensor for classification or
2-D tensor for regression.
Converts sparse tensors to dense ones.
Args:
labels: `Tensor` or `dict` of `Tensor` objects.
Returns:
A 2-D tensor for labels/outputs.
"""
if isinstance(labels, dict):
return math_ops.to_float(
array_ops.concat(
[
sparse_ops.sparse_tensor_to_dense(
labels[k], default_value=-1) if isinstance(
labels, sparse_tensor.SparseTensor) else labels[k]
for k in sorted(labels.keys())
],
1))
else:
if isinstance(labels, sparse_tensor.SparseTensor):
return math_ops.to_float(sparse_ops.sparse_tensor_to_dense(
labels, default_value=-1))
else:
return math_ops.to_float(labels)
|
awacha/credolib | refs/heads/master | credolib/plotting.py | 1 | __all__=['plotsascurve','guinierplot','kratkyplot']
from .io import getsascurve
import matplotlib.pyplot as plt
from sastool.libconfig import qunit, dunit
def plotsascurve(samplename, *args, **kwargs):
if 'dist' not in kwargs:
kwargs['dist'] = None
data1d, dist = getsascurve(samplename, kwargs['dist'])
del kwargs['dist']
if 'factor' in kwargs:
factor=kwargs['factor']
del kwargs['factor']
else:
factor=1
if 'label' not in kwargs:
if isinstance(dist, str):
kwargs['label'] = samplename + ' ' + dist
else:
kwargs['label'] = samplename + ' %g mm' % dist
if 'errorbar' in kwargs:
errorbars = bool(kwargs['errorbar'])
del kwargs['errorbar']
else:
errorbars = False
if errorbars:
ret = (data1d*factor).errorbar(*args, **kwargs)
plt.xscale('log')
plt.yscale('log')
else:
ret = (data1d*factor).loglog(*args, **kwargs)
plt.xlabel('q (' + qunit() + ')')
plt.ylabel('$d\\Sigma/d\\Omega$ (cm$^{-1}$ sr$^{-1}$)')
plt.legend(loc='best')
plt.grid(True, which='both')
plt.axis('tight')
return ret
def guinierplot(*args, **kwargs):
"""Make a Guinier plot. This is simply a wrapper around plotsascurve()."""
ret=plotsascurve(*args, **kwargs)
plt.xscale('power',exponent=2)
plt.yscale('log')
return ret
def kratkyplot(samplename, *args, **kwargs):
if 'dist' not in kwargs:
kwargs['dist'] = None
data1d, dist = getsascurve(samplename, kwargs['dist'])
del kwargs['dist']
if 'factor' in kwargs:
factor=kwargs['factor']
del kwargs['factor']
else:
factor=1
if 'label' not in kwargs:
if isinstance(dist, str):
kwargs['label'] = samplename + ' ' + dist
else:
kwargs['label'] = samplename + ' %g mm' % dist
if 'errorbar' in kwargs:
errorbars = bool(kwargs['errorbar'])
del kwargs['errorbar']
else:
errorbars = False
data1dscaled=data1d*factor
if errorbars:
if hasattr(data1dscaled, 'dx'):
dx=data1dscaled.qError
dy=(data1dscaled.Error ** 2 * data1dscaled.q ** 4 +
data1dscaled.Intensity ** 2 * data1dscaled.qError ** 2
* data1dscaled.q ** 2 * 4) ** 0.5
else:
dx=None
dy=data1dscaled.Error
ret = plt.errorbar(data1dscaled.q,
data1dscaled.q ** 2 * data1dscaled.Intensity,
dy, dx, *args, **kwargs)
else:
ret = plt.plot(data1dscaled.q,
data1dscaled.Intensity * data1dscaled.q ** 2,
*args, **kwargs)
plt.xlabel('q (' + dunit() + ')')
plt.ylabel('$q^2 d\\Sigma/d\\Omega$ (' +
dunit() +
'$^{-2}$ cm$^{-1}$ sr$^{-1}$)')
plt.legend(loc='best')
plt.grid(True, which='both')
plt.axis('tight')
return ret
def porodplot(samplename, *args, **kwargs):
if 'dist' not in kwargs:
kwargs['dist'] = None
data1d, dist = getsascurve(samplename, kwargs['dist'])
del kwargs['dist']
if 'factor' in kwargs:
factor=kwargs['factor']
del kwargs['factor']
else:
factor=1
if 'label' not in kwargs:
if isinstance(dist, str):
kwargs['label'] = samplename + ' ' + dist
else:
kwargs['label'] = samplename + ' %g mm' % dist
if 'errorbar' in kwargs:
errorbars = bool(kwargs['errorbar'])
del kwargs['errorbar']
else:
errorbars = False
data1dscaled=data1d*factor
if errorbars:
if hasattr(data1dscaled, 'dx'):
dx=data1dscaled.qError
dy=(data1dscaled.Error ** 2 * data1dscaled.q ** 8 +
data1dscaled.Intensity ** 2 * data1dscaled.qError ** 2
* data1dscaled.q ** 6 * 14) ** 0.5
else:
dx=None
dy=data1dscaled.Error
ret = plt.errorbar(data1dscaled.q,
data1dscaled.q ** 4 * data1dscaled.Intensity,
dy, dx, *args, **kwargs)
else:
ret = plt.plot(data1dscaled.q,
data1dscaled.Intensity * data1dscaled.q ** 2,
*args, **kwargs)
plt.xlabel('q (' + dunit() + ')')
plt.ylabel('$q^4 d\\Sigma/d\\Omega$ (' +
dunit() +
'$^{-4}$ cm$^{-1}$ sr$^{-1}$)')
plt.legend(loc='best')
plt.xscale('power',exponent=4)
plt.yscale('linear')
plt.grid(True, which='both')
plt.axis('tight')
return ret
|
almichest/hue_app | refs/heads/master | src/twitter/__init__.py | 5 | __author__ = 'hira'
|
abstract-open-solutions/website | refs/heads/8.0 | website_backend_views/__openerp__.py | 7 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2015 Therp BV <http://therp.nl>.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
"name": "Backend views for website",
"version": "1.0",
"author": "Therp BV",
"license": "AGPL-3",
"category": "Dependency",
"summary": "Hook backend views into your website frontend",
"depends": [
'web',
'website',
],
"data": [
'view/templates.xml',
],
"demo": [
"view/demo.xml",
],
"test": [
],
"auto_install": False,
"installable": True,
"application": False,
"external_dependencies": {
'python': [],
},
}
|
mogoweb/chromium-crosswalk | refs/heads/master | chrome/test/functional/perf/endure_setup.py | 68 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Automate the setup process of Chrome Endure environment.
Usage:
python endure_setup.py [option]
We use <ENDURE_DIR> to refer to the root directory in which Chrome Endure
is set up. By default, <ENDURE_DIR> is the current working directory.
First, run:
>python endure_setup.py
This command will automatically setup Chrome Endure in <ENDURE_DIR>.
Next, run your first endure test by:
>TEST_LENGTH=30 LOCAL_PERF_DIR="<ENDURE_DIR>/chrome_graph" \\
python <ENDURE_DIR>/src/chrome/test/functional/perf_endure.py \\
perf_endure.ChromeEndureGmailTest.testGmailComposeDiscard \\
The above commands runs a Chrome Endure test for 30 seconds and saves
the results to <ENDURE_DIR>/chrome_graph.
Last, to view the graphs, run another script endure_server.py
within <ENDURE_DIR> to start a local HTTP server that serves
the graph directory, see endure_server.py for details.
Use python endure_setup.py --help for more options.
This script depends on the following modules
(which will be downloaded automatically):
depot_tools
src/chrome/test/pyautolib/fetch_prebuilt_pyauto.py
Supported platforms: Linux and Linux_x64.
"""
import logging
import optparse
import os
import platform
import shutil
import subprocess
import sys
import urllib
import urllib2
import zipfile
URLS = {'depot_tools': ('http://src.chromium.org'
'/chrome/trunk/tools/depot_tools'),
'pyauto': ('https://src.chromium.org/'
'chrome/trunk/src/chrome/test/functional.DEPS'),
'binary': ('http://commondatastorage.googleapis.com/'
'chromium-browser-continuous/{os_type}/{revision}'),
}
class SetupError(Exception):
"""Catch errors in setting up Chrome Endure."""
pass
class HelpFormatter(optparse.IndentedHelpFormatter):
"""Format the help message of this script."""
def format_description(self, description):
"""Override to keep the original format of the description."""
return description + '\n' if description else ''
def Main(argv):
"""Fetch Chrome Endure.
Usage:
python endure_setup.py [options]
Examples:
>python endure_setup.py
Fetch the latest version of Chrome Endure to the current
working directory.
>python endure_setup.py --endure-dir=/home/user/endure_dir
Fetch the latest version of Chrome Endure to /home/user/endure_dir.
"""
parser = optparse.OptionParser(
formatter=HelpFormatter(), description=Main.__doc__)
parser.add_option(
'-d', '--endure-dir', type='string', default=os.getcwd(),
help='Directory in which to setup or update. ' \
'Default value is the current working directory.')
# TODO(fdeng): remove this option once the Chrome Endure
# graphing code is checked into chrome tree.
parser.add_option(
'-g', '--graph-zip-url', type='string', default=None,
help='URL to a zip file containing the chrome graphs.')
os_type = GetCurrentOSType()
if not os_type.startswith('Linux'):
raise SetupError('Only support Linux or Linux_x64, %s found'
% os_type)
options, _ = parser.parse_args(argv)
endure_dir = os.path.abspath(options.endure_dir)
depot_dir = os.path.join(endure_dir, 'depot_tools')
gclient = os.path.join(depot_dir, 'gclient')
fetch_py = os.path.join(endure_dir, 'src', 'chrome',
'test', 'pyautolib',
'fetch_prebuilt_pyauto.py')
binary_dir = os.path.join(endure_dir, 'src', 'out', 'Release')
graph_zip_url = options.graph_zip_url
graph_dir = os.path.join(endure_dir, 'chrome_graph')
if not os.path.isdir(endure_dir):
os.makedirs(endure_dir)
logging.info('Fetching depot tools...')
FetchDepot(depot_dir)
logging.info('Fetching PyAuto (python code)...')
FetchPyAuto(gclient, endure_dir)
logging.info('Fetching binaries(chrome, pyautolib, chrome driver)...')
FetchBinaries(fetch_py, binary_dir, os_type)
# TODO(fdeng): remove this after it is checked into the chrome tree.
logging.info('Fetching chrome graphing files...')
FetchGraph(graph_zip_url, graph_dir)
return 0
def FetchDepot(depot_dir):
"""Fetch depot_tools.
Args:
depot_dir: The directory where depot_tools will be checked out.
Raises:
SetupError: If fail.
"""
if subprocess.call(['svn', 'co', URLS['depot_tools'], depot_dir]) != 0:
raise SetupError('Error found when checking out depot_tools.')
if not CheckDepot(depot_dir):
raise SetupError('Could not get depot_tools.')
def CheckDepot(depot_dir):
"""Check that some expected depot_tools files exist.
Args:
depot_dir: The directory where depot_tools are checked out.
Returns:
True if check passes otherwise False.
"""
gclient = os.path.join(depot_dir, 'gclient')
gclient_py = os.path.join(depot_dir, 'gclient.py')
files = [gclient, gclient_py]
for f in files:
if not os.path.exists(f):
return False
try:
subprocess.call([gclient, '--version'])
except OSError:
return False
return True
def FetchPyAuto(gclient, endure_dir):
"""Use gclient to fetch python code.
Args:
gclient: The path to the gclient executable.
endure_dir: Directory where Chrome Endure and
its dependencies will be checked out.
Raises:
SetupError: if fails.
"""
cur_dir = os.getcwd()
os.chdir(endure_dir)
config_cmd = [gclient, 'config', URLS['pyauto']]
if subprocess.call(config_cmd) != 0:
raise SetupError('Running "%s" failed.' % ' '.join(config_cmd))
sync_cmd = [gclient, 'sync']
if subprocess.call(sync_cmd) != 0:
raise SetupError('Running "%s" failed.' % ' '.join(sync_cmd))
CheckPyAuto(endure_dir)
logging.info('Sync PyAuto python code done.')
os.chdir(cur_dir)
def CheckPyAuto(endure_dir):
"""Sanity check for Chrome Endure code.
Args:
endure_dir: Directory of Chrome Endure and its dependencies.
Raises:
SetupError: If fails.
"""
fetch_py = os.path.join(endure_dir, 'src', 'chrome',
'test', 'pyautolib',
'fetch_prebuilt_pyauto.py')
pyauto_py = os.path.join(endure_dir, 'src',
'chrome', 'test',
'pyautolib', 'pyauto.py')
files = [fetch_py, pyauto_py]
for f in files:
if not os.path.exists(f):
raise SetupError('Checking %s failed.' % f)
def FetchBinaries(fetch_py, binary_dir, os_type):
"""Get the prebuilt binaries from continuous build archive.
Args:
fetch_py: Path to the script which fetches pre-built binaries.
binary_dir: Directory of the pre-built binaries.
os_type: 'Mac', 'Win', 'Linux', 'Linux_x64'.
Raises:
SetupError: If fails.
"""
revision = GetLatestRevision(os_type)
logging.info('Cleaning %s', binary_dir)
if os.path.exists(binary_dir):
shutil.rmtree(binary_dir)
logging.info('Downloading binaries...')
cmd = [fetch_py, '-d', binary_dir,
URLS['binary'].format(
os_type=os_type, revision=revision)]
if subprocess.call(cmd) == 0 and os.path.exists(binary_dir):
logging.info('Binaries at revision %s', revision)
else:
raise SetupError('Running "%s" failed.' % ' '.join(cmd))
def FetchGraph(graph_zip_url, graph_dir):
"""Fetch graph code.
Args:
graph_zip_url: The url to a zip file containing the chrome graphs.
graph_dir: Directory of the chrome graphs.
Raises:
SetupError: if unable to retrive the zip file.
"""
# TODO(fdeng): remove this function once chrome graph
# is checked into chrome tree.
if not graph_zip_url:
logging.info(
'Skip fetching chrome graphs' +
' since --graph-zip-url is not set.')
return
graph_zip = urllib.urlretrieve(graph_zip_url)[0]
if graph_zip is None or not os.path.exists(graph_zip):
raise SetupError('Unable to retrieve %s' % graph_zip_url)
if not os.path.exists(graph_dir):
os.mkdir(graph_dir)
UnzipFilenameToDir(graph_zip, graph_dir)
logging.info('Graph code is downloaded to %s', graph_dir)
def GetCurrentOSType():
"""Get a string representation for the current OS.
Returns:
'Mac', 'Win', 'Linux', or 'Linux_64'.
Raises:
RuntimeError: if OS can't be identified.
"""
if sys.platform == 'darwin':
os_type = 'Mac'
if sys.platform == 'win32':
os_type = 'Win'
if sys.platform.startswith('linux'):
os_type = 'Linux'
if platform.architecture()[0] == '64bit':
os_type += '_x64'
else:
raise RuntimeError('Unknown platform')
return os_type
def GetLatestRevision(os_type):
"""Figure out the latest revision number of the prebuilt binary archive.
Args:
os_type: 'Mac', 'Win', 'Linux', or 'Linux_64'.
Returns:
A string of latest revision number.
Raises:
SetupError: If unable to get the latest revision number.
"""
last_change_url = ('http://commondatastorage.googleapis.com/'
'chromium-browser-continuous/%s/LAST_CHANGE' % os_type)
response = urllib2.urlopen(last_change_url)
last_change = response.read()
if not last_change:
raise SetupError('Unable to get the latest revision number from %s' %
last_change_url)
return last_change
def UnzipFilenameToDir(filename, directory):
"""Unzip |filename| to directory |directory|.
This works with as low as python2.4 (used on win).
(Code is adapted from fetch_prebuilt_pyauto.py)
"""
# TODO(fdeng): remove this function as soon as the Chrome Endure
# graphing code is checked into the chrome tree.
zf = zipfile.ZipFile(filename)
pushd = os.getcwd()
if not os.path.isdir(directory):
os.mkdir(directory)
os.chdir(directory)
# Extract files.
for info in zf.infolist():
name = info.filename
if name.endswith('/'): # dir
if not os.path.isdir(name):
os.makedirs(name)
else: # file
directory = os.path.dirname(name)
if directory and not os.path.isdir(directory):
os.makedirs(directory)
out = open(name, 'wb')
out.write(zf.read(name))
out.close()
# Set permissions. Permission info in external_attr is shifted 16 bits.
os.chmod(name, info.external_attr >> 16L)
os.chdir(pushd)
if '__main__' == __name__:
logging.basicConfig(format='[%(levelname)s] %(message)s', level=logging.DEBUG)
sys.exit(Main(sys.argv[1:]))
|
o5k/openerp-oemedical-v0.1 | refs/heads/master | openerp/addons/hr_holidays/wizard/__init__.py | 442 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import hr_holidays_summary_department
import hr_holidays_summary_employees
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.