commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
e884fa6de130efae630f827921345bedc95af276 | Update utils.py | pathakvaidehi2391/WorkSpace,pathakvaidehi2391/WorkSpace | azurecloudify/utils.py | azurecloudify/utils.py | from cloudify import ctx
from cloudify.exceptions import NonRecoverableError
import random
import string
def get_resource_group_name():
if ctx.node.properties['exsisting_resource_group_name']:
return ctx.node.properties['exsisting_resource_group_name']
def get_storage_account_name():
if ctx.node.properties['exsisting_storage_account_name']:
return ctx.node.properties['exsisting_storage_account_name']
def get_nic_name():
if ctx.node.properties['exsisting_nic_name']:
return ctx.node.properties['exsisting_nic_name']
def get_vnet_name():
if ctx.node.properties['exsisting_vnet_name']:
return ctx.node.properties['exsisting_vnet_name']
def get_public_ip_name():
if ctx.node.properties['exsisting_public_ip_name']:
return ctx.node.properties['exsisting_public_ip_name']
def get_public_ip_name():
if ctx.node.properties['exsisting_vm_name']:
return ctx.node.properties['exsisting_vm_name']
def use_external_resource(ctx_node_properties):
"""Checks if use_external_resource node property is true,
logs the ID and answer to the debug log,
and returns boolean False (if not external) or True.
:param node_properties: The ctx node properties for a node.
:param ctx: The Cloudify ctx context.
:returns boolean: False if not external.
"""
if not ctx_node_properties['use_external_resource']:
ctx.logger.debug(
'Using Cloudify resource_name: {0}.'
.format(ctx_node_properties['resource_name']))
return False
else:
ctx.logger.debug(
'Using external resource_name: {0}.'
.format(ctx_node_properties['resource_name']))
return True
def set_external_resource_name(value, ctx_instance, external=True):
"""Sets the EXTERNAL_RESOURCE_NAME runtime_property for a Node-Instance.
:param value: the desired EXTERNAL_RESOURCE_NAME runtime_property
:param ctx: The Cloudify ctx context.
:param external: Boolean representing if it is external resource or not.
"""
value = constants.value
if not external:
resource_type = 'Cloudify'
else:
resource_type = 'external'
ctx.logger.info('Using {0} resource: {1}'.format(resource_type, value))
ctx.instance.runtime_properties['resource_name'] = value
def random_suffix_generator(size=3, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
| from cloudify import ctx
from cloudify.exceptions import NonRecoverableError
import random
import string
def get_resource_group_name():
if ctx.node.properties['exsisting_resource_group_name']:
return ctx.node.properties['exsisting_resource_group_name']
def get_resource_name():
if ctx.node.properties['resource_name']:
return ctx.node.properties['resource_name']
def use_external_resource(ctx_node_properties):
"""Checks if use_external_resource node property is true,
logs the ID and answer to the debug log,
and returns boolean False (if not external) or True.
:param node_properties: The ctx node properties for a node.
:param ctx: The Cloudify ctx context.
:returns boolean: False if not external.
"""
if not ctx_node_properties['use_external_resource']:
ctx.logger.debug(
'Using Cloudify resource_name: {0}.'
.format(ctx_node_properties['resource_name']))
return False
else:
ctx.logger.debug(
'Using external resource_name: {0}.'
.format(ctx_node_properties['resource_name']))
return True
def set_external_resource_name(value, ctx_instance, external=True):
"""Sets the EXTERNAL_RESOURCE_NAME runtime_property for a Node-Instance.
:param value: the desired EXTERNAL_RESOURCE_NAME runtime_property
:param ctx: The Cloudify ctx context.
:param external: Boolean representing if it is external resource or not.
"""
value = constants.value
if not external:
resource_type = 'Cloudify'
else:
resource_type = 'external'
ctx.logger.info('Using {0} resource: {1}'.format(resource_type, value))
ctx.instance.runtime_properties['resource_name'] = value
def random_suffix_generator(size=3, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
| apache-2.0 | Python |
d3ee9b6afc1d90f647335e15a4a48c36b84c3037 | add --docker-root option | Netflix/aminator,kvick/aminator,bmoyles/aminator,coryb/aminator | aminator/plugins/volume/docker.py | aminator/plugins/volume/docker.py | # -*- coding: utf-8 -*-
#
#
# Copyright 2014 Netflix, Inc.
#
# 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.
#
#
"""
aminator.plugins.volume.docker
=============================
docker volume allocator
"""
import logging
from aminator.plugins.volume.base import BaseVolumePlugin
from aminator.config import conf_action
__all__ = ('DockerVolumePlugin',)
log = logging.getLogger(__name__)
class DockerVolumePlugin(BaseVolumePlugin):
_name = 'docker'
def add_plugin_args(self, *args, **kwargs):
context = self._config.context
docker = self._parser.add_argument_group(title='Docker')
docker.add_argument('-b', '--docker-root', dest='docker_root',
action=conf_action(config=context.cloud), default="/var/lib/docker",
help='The base directory for docker containers')
return docker
def __enter__(self):
self._cloud.allocate_base_volume()
self._cloud.attach_volume(self._blockdevice)
container = self._config.context.cloud["container"]
# FIXME this path should be configurable
mountpoint = "{}/aufs/mnt/{}".format(self._config.context.cloud["docker_root"], container)
self._config.context.volume["mountpoint"] = mountpoint
return mountpoint
def __exit__(self, exc_type, exc_value, trace):
if exc_type: log.exception("Exception: {0}: {1}".format(exc_type.__name__,exc_value))
if exc_type and self._config.context.get("preserve_on_error", False):
return False
self._cloud.detach_volume(self._blockdevice)
self._cloud.delete_volume()
return False
| # -*- coding: utf-8 -*-
#
#
# Copyright 2014 Netflix, Inc.
#
# 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.
#
#
"""
aminator.plugins.volume.docker
=============================
docker volume allocator
"""
import logging
from aminator.plugins.volume.base import BaseVolumePlugin
__all__ = ('DockerVolumePlugin',)
log = logging.getLogger(__name__)
class DockerVolumePlugin(BaseVolumePlugin):
_name = 'docker'
def __enter__(self):
self._cloud.allocate_base_volume()
self._cloud.attach_volume(self._blockdevice)
container = self._config.context.cloud["container"]
# FIXME this path should be configurable
mountpoint = "/var/lib/docker/aufs/mnt/{}".format(container)
self._config.context.volume["mountpoint"] = mountpoint
return mountpoint
def __exit__(self, exc_type, exc_value, trace):
if exc_type: log.exception("Exception: {0}: {1}".format(exc_type.__name__,exc_value))
if exc_type and self._config.context.get("preserve_on_error", False):
return False
self._cloud.detach_volume(self._blockdevice)
self._cloud.delete_volume()
return False
| apache-2.0 | Python |
c84fb1e8f00f7341234965fcf2a1f7aca9a01cde | Add documentation to utils.stripspecialchars() | 9h37/pompadour-wiki,9h37/pompadour-wiki,9h37/pompadour-wiki | pompadour_wiki/pompadour_wiki/apps/utils/__init__.py | pompadour_wiki/pompadour_wiki/apps/utils/__init__.py | # -*- coding: utf-8 -*-
import os
import re
def urljoin(*args):
""" Like os.path.join but for URLs """
if len(args) == 0:
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 arg.startswith("/"):
work.append(arg[1:])
else:
work.append(arg)
joined = reduce(os.path.join, work)
return joined.replace("\\", "/")
def breadcrumbify(path):
""" Generates breadcrumb from a path """
breadcrumb_list = path.split('/')
breadcrumb_urls = []
for breadcrumb in breadcrumb_list:
parts = breadcrumb_urls + [breadcrumb]
url = urljoin(*parts)
breadcrumb_urls.append(url)
return zip(breadcrumb_list, breadcrumb_urls)
def decode_unicode_references(data):
""" Replace '&#<unicode id>' by the unicode character """
def _callback(matches):
id = matches.group(1)
try:
return unichr(int(id))
except:
return id
return re.sub("&#(\d+)(;|(?=\s))", _callback, data)
def stripspecialchars(input_str):
""" Remove special chars in UTF-8 string """
import unicodedata
# will decompose UTF-8 entities ('é' becomes 'e\u0301')
nfkd_form = unicodedata.normalize('NFKD', unicode(input_str))
# unicodedata.combining() returns 0 if the character is a normal character,
# so this loop help us converting the string in ASCII-format
return ''.join([c for c in nfkd_form if not unicodedata.combining(c)]) | # -*- coding: utf-8 -*-
import os
import re
def urljoin(*args):
""" Like os.path.join but for URLs """
if len(args) == 0:
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 arg.startswith("/"):
work.append(arg[1:])
else:
work.append(arg)
joined = reduce(os.path.join, work)
return joined.replace("\\", "/")
def breadcrumbify(path):
""" Generates breadcrumb from a path """
breadcrumb_list = path.split('/')
breadcrumb_urls = []
for breadcrumb in breadcrumb_list:
parts = breadcrumb_urls + [breadcrumb]
url = urljoin(*parts)
breadcrumb_urls.append(url)
return zip(breadcrumb_list, breadcrumb_urls)
def decode_unicode_references(data):
""" Replace '&#<unicode id>' by the unicode character """
def _callback(matches):
id = matches.group(1)
try:
return unichr(int(id))
except:
return id
return re.sub("&#(\d+)(;|(?=\s))", _callback, data)
def stripspecialchars(input_str):
""" Remove special chars in UTF-8 string """
import unicodedata
nfkd_form = unicodedata.normalize('NFKD', unicode(input_str))
return ''.join([c for c in nfkd_form if not unicodedata.combining(c)]) | mit | Python |
729a5c2e1276f9789733fc46fb7f48d0ac7e3178 | Use requests to fetch emoji list | le1ia/slackmoji | src/slackmoji.py | src/slackmoji.py | # pylint: disable = C0103, C0111
# Standard Library
import json
import mimetypes
from os import makedirs
# Third Party
import requests
def list_emojis(domain, token):
url = r'https://%s.slack.com/api/emoji.list' % domain
data = [('token', token)]
response = requests.post(url, data=data)
print "\nGot list of emojis from %s Slack domain!" % domain
emojis = json.loads(response.text)["emoji"]
return emojis
def download_emojis(emojis, folder):
count = 0
makedirs(folder)
print "\nDownloading emojis to %s folder..." % folder
for name, url in emojis.iteritems():
if 'alias' in url:
continue
else:
res = requests.get(url)
cont = res.headers['content-type']
ext = mimetypes.guess_extension(cont)
if ext == '.jpe':
ext = '.jpg'
output = folder + '/' + name + ext
with open(output, 'wb') as fd:
for chunk in res.iter_content(chunk_size=1024):
fd.write(chunk)
count = count + 1
print "\nFinished downloading %s emojis!" % count
| # pylint: disable = C0103, C0111
# Standard Library
import json
import mimetypes
from os import makedirs
from subprocess import check_output
# Third Party
import requests
def list_emojis(domain, token):
script = ['bin/list_emojis.sh {0} {1}'.format(domain, token)]
response = check_output(script, shell=True)
print "\nGot list of emojis from %s Slack domain!" % domain
return response
def download_emojis(emojis, folder):
count = 0
makedirs(folder)
emojis = json.loads(emojis)["emoji"]
print "\nDownloading emojis from list..."
for name, url in emojis.iteritems():
if 'alias' in url:
continue
else:
res = requests.get(url)
cont = res.headers['content-type']
ext = mimetypes.guess_extension(cont)
if ext == '.jpe':
ext = '.jpg'
output = folder + '/' + name + ext
with open(output, 'wb') as fd:
for chunk in res.iter_content(chunk_size=1024):
fd.write(chunk)
count = count + 1
print "\nFinished downloading %s emojis!" % count
| mit | Python |
4d3d5c97b9ff49c553cae1900af70c12c2cee83c | adjust responder to python 3 | goFrendiAsgard/chimera-framework,goFrendiAsgard/chimera-framework,goFrendiAsgard/chimera-framework,goFrendiAsgard/chimera-framework,goFrendiAsgard/chimera-framework,goFrendiAsgard/chimera-framework | project-template/chains/programs/sample.responder.py | project-template/chains/programs/sample.responder.py | import sys, json
# get request and config from the framework
req = json.loads(sys.argv[1])
config = json.loads(sys.argv[2])
params = req['params']
# create response
title = 'sample.responder.py'
name = 'Kimi no na wa?'
if 'name' in params:
name = params['name']
response = {'title': title, 'name': name}
# show time
print (json.dumps(response))
| import sys, json
# get request and config from the framework
req = json.loads(sys.argv[1])
config = json.loads(sys.argv[2])
params = req['params']
# create response
title = 'sample.responder.py'
name = 'Kimi no na wa?'
if 'name' in params:
name = params['name']
response = {'title': title, 'name': name}
# show time
print json.dumps(response)
| mit | Python |
48b7880fec255c7a021361211e56980be2bd4c6b | Add "since" parameter to this command | HelsinkiHacklab/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum | project/creditor/management/commands/addrecurring.py | project/creditor/management/commands/addrecurring.py | # -*- coding: utf-8 -*-
import datetime
import itertools
import dateutil.parser
from creditor.models import RecurringTransaction
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
from asylum.utils import datetime_proxy, months
class Command(BaseCommand):
help = 'Gets all RecurringTransactions and runs conditional_add_transaction()'
def add_arguments(self, parser):
parser.add_argument('since', type=str, nargs='?', default=datetime_proxy(), help='Run for each month since the date, defaults to yesterday midnight')
def handle(self, *args, **options):
since_parsed = timezone.make_aware(dateutil.parser.parse(options['since']))
if options['verbosity'] > 2:
print("Processing since %s" % since_parsed.isoformat())
for t in RecurringTransaction.objects.all():
if options['verbosity'] > 2:
print("Processing: %s" % t)
for month in months(since_parsed, timezone.now()):
if options['verbosity'] > 2:
print(" month %s" % month.isoformat())
ret = t.conditional_add_transaction(month)
if ret:
if options['verbosity'] > 1:
print("Created transaction %s" % ret)
| # -*- coding: utf-8 -*-
from creditor.models import RecurringTransaction
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = 'Gets all RecurringTransactions and runs conditional_add_transaction()'
def handle(self, *args, **options):
for t in RecurringTransaction.objects.all():
ret = t.conditional_add_transaction()
if ret:
if options['verbosity'] > 1:
print("Created transaction %s" % ret)
| mit | Python |
65f0520383dcb9a39fa4409b867574832a9c1b4f | Update version.py | mongolab/mongoctl | mongoctl/version.py | mongoctl/version.py | __author__ = 'abdul'
MONGOCTL_VERSION = '0.6.3'
| __author__ = 'abdul'
MONGOCTL_VERSION = '0.6.2' | mit | Python |
debc3f9c21af5666e53b84dd99c6d5c99abc2c66 | Rename entry class | Motoko11/MotoBot | motobot/database.py | motobot/database.py | from pickle import load, dump, HIGHEST_PROTOCOL
from os import replace
class DatabaseEntry:
def __init__(self, database, data={}):
self.__database = database
self.__data = data
def get_val(self, name, default=None):
return self.__data.get(name, default)
def set_val(self, name, value):
self.__data[name] = value
self.__database.changed = True
def is_empty(self):
return self.__data == {}
class Database:
def __init__(self, database_path=None):
self.database_path = database_path
self.data = {}
self.changed = False
self.load_database()
def load_database(self):
if self.database_path is not None:
try:
file = open(self.database_path, 'rb')
self.data = load(file)
except FileNotFoundError:
self.changed = True
self.write_database()
def write_database(self):
if self.database_path is not None and self.changed:
temp_path = self.database_path + '.temp'
file = open(temp_path, 'wb')
dump(self.data, file, HIGHEST_PROTOCOL)
file.close()
replace(temp_path, self.database_path)
self.changed = False
def get_entry(self, name):
if name not in self.data:
self.data[name] = DatabaseEntry(self)
return self.data[name]
| from pickle import load, dump, HIGHEST_PROTOCOL
from os import replace
class Entry:
def __init__(self, database, data={}):
self.__database = database
self.__data = data
def get_val(self, name, default=None):
return self.__data.get(name, default)
def set_val(self, name, value):
self.__data[name] = value
self.__database.changed = True
def is_empty(self):
return self.__data == {}
class Database:
def __init__(self, database_path=None):
self.database_path = database_path
self.data = {}
self.changed = False
self.load_database()
def load_database(self):
if self.database_path is not None:
try:
file = open(self.database_path, 'rb')
self.data = load(file)
except FileNotFoundError:
self.changed = True
self.write_database()
def write_database(self):
if self.database_path is not None and self.changed:
temp_path = self.database_path + '.temp'
file = open(temp_path, 'wb')
dump(self.data, file, HIGHEST_PROTOCOL)
file.close()
replace(temp_path, self.database_path)
self.changed = False
def get_entry(self, name):
if name not in self.data:
self.data[name] = Entry(self)
return self.data[name]
| mit | Python |
61454a9e271bf57e54453c9ef50fd8bb7e545b6d | Fix Group.__unicode__. | OddBloke/moore | wrestlers/models.py | wrestlers/models.py | # moore - a wrestling database
# Copyright (C) 2011 Daniel Watkins
#
# 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 django.db import models
from review.models import Review
class GroupManager(models.Manager):
def filter_wrestlers(self, l):
return self.filter(wrestlers=Wrestler.objects.filter(id__in=[w.id for w in l]))
class WrestlingEntity(Review):
bio = models.TextField(blank=True,null=True)
class Group(models.Model):
objects = GroupManager()
wrestlers = models.ManyToManyField("Persona")
group_name = models.CharField(max_length=128, null=True, blank=True)
@property
def name(self):
return self.group_name
def __unicode__(self):
if self.group_name is not None and self.group_name != '':
return self.group_name
else:
return " & ".join([w.name for w in self.wrestlers.all()])
class WrestlingTeam(WrestlingEntity, Group):
pass
class Wrestler(Review):
name = models.CharField(max_length=128)
bio = models.TextField(blank=True,null=True)
born_when = models.DateField(null=True, blank=True)
born_location = models.CharField(max_length=128,blank=True,null=True)
trained_by = models.ManyToManyField('Wrestler',blank=True)
def __unicode__(self):
return self.name
class Persona(WrestlingEntity):
billed_name = models.CharField(max_length=128)
wrestler = models.ForeignKey(Wrestler)
billed_height = models.DecimalField(null=True, blank=True,help_text="in metres",decimal_places=2,max_digits=10)
billed_weight = models.IntegerField(null=True, blank=True,help_text="in kilograms")
debut = models.DateField(null=True, blank=True)
@property
def name(self):
return self.billed_name
def __unicode__(self):
return self.billed_name
| # moore - a wrestling database
# Copyright (C) 2011 Daniel Watkins
#
# 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 django.db import models
from review.models import Review
class GroupManager(models.Manager):
def filter_wrestlers(self, l):
return self.filter(wrestlers=Wrestler.objects.filter(id__in=[w.id for w in l]))
class WrestlingEntity(Review):
bio = models.TextField(blank=True,null=True)
class Group(models.Model):
objects = GroupManager()
wrestlers = models.ManyToManyField("Persona")
group_name = models.CharField(max_length=128, null=True, blank=True)
@property
def name(self):
return self.group_name
def __unicode__(self):
if self.group_name is not None:
return self.group_name
else:
return ", ".join([w.name for w in self.wrestlers])
class WrestlingTeam(WrestlingEntity, Group):
pass
class Wrestler(Review):
name = models.CharField(max_length=128)
bio = models.TextField(blank=True,null=True)
born_when = models.DateField(null=True, blank=True)
born_location = models.CharField(max_length=128,blank=True,null=True)
trained_by = models.ManyToManyField('Wrestler',blank=True)
def __unicode__(self):
return self.name
class Persona(WrestlingEntity):
billed_name = models.CharField(max_length=128)
wrestler = models.ForeignKey(Wrestler)
billed_height = models.DecimalField(null=True, blank=True,help_text="in metres",decimal_places=2,max_digits=10)
billed_weight = models.IntegerField(null=True, blank=True,help_text="in kilograms")
debut = models.DateField(null=True, blank=True)
@property
def name(self):
return self.billed_name
def __unicode__(self):
return self.billed_name
| agpl-3.0 | Python |
e9484f9192ac93209dbdf377adff36f4b314167a | update test settings for djanog_jenkins | caktus/django-pagelets,caktus/django-pagelets,caktus/django-pagelets,caktus/django-pagelets | sample_project/hudson_test_settings.py | sample_project/hudson_test_settings.py | from sample_project.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'pagelets', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
INSTALLED_APPS = list(INSTALLED_APPS)
# disable south
# there seems to be an issue with south + django_jenkins
INSTALLED_APPS.remove('south')
INSTALLED_APPS.append('django_jenkins')
PROJECT_APPS = ('pagelets',)
| from sample_project.settings import *
INSTALLED_APPS += ('test_extensions',)
# COVERAGE_EXCLUDE_MODULES = ('django',)
# COVERAGE_INCLUDE_MODULES = ('pagelets',) | bsd-3-clause | Python |
8d498afc08d01a801044713ae430d85dfef7d8b6 | Fix url mapping | muffins-on-dope/bakery,muffins-on-dope/bakery,muffins-on-dope/bakery | bakery/cookies/urls.py | bakery/cookies/urls.py | # -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
urlpatterns = patterns('bakery.cookies.views',
url(r'^cookie/(?P<owner_name>[^/]+)/(?P<name>[^/]+)/$', 'detail', name='detail'),
)
| # -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
urlpatterns = patterns('bakery.cookies.views',
url(r'^cookie/(?P<owner_name>[^/]+)/(?P<name>[^/]+)$', 'detail', name='detail'),
)
| bsd-3-clause | Python |
ab97af9e23f5006ae8eaf6273c5c9194fc9d8d5f | Print before running reactor. | denispin/twisted-intro,shankisg/twisted-intro,s0lst1ce/twisted-intro,jdavisp3/twisted-intro,denispin/twisted-intro,shankig/twisted-intro,vaniakov/twisted-intro,leixinstar/twisted-intro,walkinreeds/twisted-intro,vaniakov/twisted-intro,shankig/twisted-intro,jakesyl/twisted-intro,jakesyl/twisted-intro,elenaoat/tests,walkinreeds/twisted-intro,jdavisp3/twisted-intro,leixinstar/twisted-intro,s0lst1ce/twisted-intro,shankisg/twisted-intro,elenaoat/tests | basic-twisted/hello.py | basic-twisted/hello.py |
def hello():
print 'Hello from the reactor loop!'
from twisted.internet import reactor
reactor.callWhenRunning(hello)
print 'Starting the reactor.'
reactor.run()
|
def hello():
print 'Hello from the reactor loop!'
from twisted.internet import reactor
reactor.callWhenRunning(hello)
reactor.run()
| mit | Python |
f1cfa2d7e03cbab089e856831d8066434f525c6f | fix timedelta add time error | HakureiClub/hakurei-site,HakureiClub/hakurei-site,HakureiClub/hakurei-site,HakureiClub/hakurei-site | hakureiclub_app/core_model/mongodb.py | hakureiclub_app/core_model/mongodb.py | from pymongo import MongoClient
from xpinyin import Pinyin
from mu_sanic import config
import urllib.request
import datetime
client = MongoClient(config.mongohost)
db = client['Hakurei-Site']
pin = Pinyin()
class BlogInfo:
def __init__(self):
self.blog = db['BlogInfo']
def init(self,title,markdown):
self.blog.create_index("url", unique=True)
url = pin.get_pinyin(str(title).replace('-',''))
raw = {
"url":url,
"title":title,
"markdown":markdown
}
self.blog.insert_one(raw)
return True
def new8th(self):
return self.blog.find().sort('$natural',-1).limit(7)
def find(self,url):
return self.blog.find_one({'url':urllib.request.unquote(url)})
class AuthInfo:
def __init__(self):
self.authi = db['authInfo']
def init(self,user,github):
raw = {
"user":user,
"github":github,
"user_auth":'True'
}
self.authi.insert_one(raw)
return True
def find_user(self,user):
return self.authi.find_one({'github':user})
class ActiInfo:
def __init__(self):
self.acti = db['ActiInfo']
def init(self,name,time,place):
time = datetime.datetime.strptime(time,"%Y.%m.%d")
expiretime = time + datetime.timedelta(days=1)
self.acti.create_index('expiretime',expireAfterSeconds=0)
raw = {
"expiretime":expiretime,
"name":name,
"time":time,
"place":place
}
self.acti.insert_one(raw)
return True
def all(self):
return self.acti.find()
def newest(self):
return self.acti.find().sort('time',1).limit(1)
| from pymongo import MongoClient
from xpinyin import Pinyin
from mu_sanic import config
import urllib.request
import datetime
client = MongoClient(config.mongohost)
db = client['Hakurei-Site']
pin = Pinyin()
class BlogInfo:
def __init__(self):
self.blog = db['BlogInfo']
def init(self,title,markdown):
self.blog.create_index("url", unique=True)
url = pin.get_pinyin(str(title).replace('-',''))
raw = {
"url":url,
"title":title,
"markdown":markdown
}
self.blog.insert_one(raw)
return True
def new8th(self):
return self.blog.find().sort('$natural',-1).limit(7)
def find(self,url):
return self.blog.find_one({'url':urllib.request.unquote(url)})
class AuthInfo:
def __init__(self):
self.authi = db['authInfo']
def init(self,user,github):
raw = {
"user":user,
"github":github,
"user_auth":'True'
}
self.authi.insert_one(raw)
return True
def find_user(self,user):
return self.authi.find_one({'github':user})
class ActiInfo:
def __init__(self):
self.acti = db['ActiInfo']
def init(self,name,time,place):
time = datetime.datetime.strptime(time,"%Y.%m.%d")
expiretime = datetime.datetime.strptime(time,"%Y.%m.%d") + datetime.timedelta(days=1)
self.acti.create_index('expiretime',expireAfterSeconds=0)
raw = {
"expiretime":expiretime,
"name":name,
"time":time,
"place":place
}
self.acti.insert_one(raw)
return True
def all(self):
return self.acti.find()
def newest(self):
return self.acti.find().sort('time',1).limit(1)
| mit | Python |
6e48e1cca6939b63d9391a435d90d439b46743a8 | Check if the url is a playlist | zuik/stuff,zuik/stuff,zuik/stuff,zuik/stuff,zuik/stuff,zuik/stuff | yufonium/youtube.py | yufonium/youtube.py | import json
import re
from youtube_dl import YoutubeDL
from youtube_dl.extractor.youtube import YoutubePlaylistIE
from yufonium.utils import save_test_json
ytplie = YoutubePlaylistIE()
ydl_opts = {
"noplaylist": True # For now, we will separate playlist and singles later
}
def get_info(url):
print("Getting info for {}".format(url))
with YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=False)
return info
def audio_urls(info):
"""
Extract the audio urls from the JSON blob that youtube_dl spits out
:param info: The JSON blob that youtube_dl spits out
:return: A list of tuples (filesize, format_id, url, ext ) of audio urls sorted by filesize
"""
# info = get_info(url)
# info = load_test_json('/Users/zui/kode/python/yufonium/yufonium/test_result.json')
audio_tracks = [i for i in info['formats'] if i['format_note'] == "DASH audio"]
print("Got {} tracks".format(len(audio_tracks)))
# Todo: Convert this to named tuple
return sorted([(i['filesize'],
i['format_id'],
i['url'],
i['ext'],
) for i in audio_tracks], key=lambda x: x[0])
# Todo: Merge this with the original extract method.
# There is no point to seperate this out.
# The only different of from the other extract method is that
# this doesn't have the extract playlist option.
def extract_playlist(url):
with YoutubeDL({"ignoreerrors": True}) as ydl:
info = ydl.extract_info(url, download=False)
return info
def is_playlist(url):
"""
Check if playlist
:param url: Url from the user
:return: playlist_id or False
"""
match = re.match(ytplie._VALID_URL, url)
if not match:
return False
playlist_id = match.group(1) or match.group(2)
return playlist_id
if __name__ == "__main__":
# Test playlist download
# This url has video id in it
url = "https://www.youtube.com/watch?v=mezYFe9DLRk&list=PLYxjne28x-DlSRzO8yvMwmCTyGBrVAhka"
print(is_playlist(url))
url = "https://www.youtube.com/playlist?list=PLYxjne28x-DlSRzO8yvMwmCTyGBrVAhka"
print(is_playlist(url))
url = "https://www.youtube.com/watch?v=mezYFe9DLRk"
print(is_playlist(url))
# save_test_json("test.json", json.dumps(extract_playlist(url)))
| import json
from youtube_dl import YoutubeDL
from yufonium.utils import save_test_json
ydl_opts = {
"noplaylist": True # For now, we will separate playlist and singles later
}
def get_info(url):
print("Getting info for {}".format(url))
with YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=False)
return info
def audio_urls(info):
"""
Extract the audio urls from the JSON blob that youtube_dl spits out
:param info: The JSON blob that youtube_dl spits out
:return: A list of tuples (filesize, format_id, url, ext ) of audio urls sorted by filesize
"""
# info = get_info(url)
# info = load_test_json('/Users/zui/kode/python/yufonium/yufonium/test_result.json')
audio_tracks = [i for i in info['formats'] if i['format_note'] == "DASH audio"]
print("Got {} tracks".format(len(audio_tracks)))
# Todo: Convert this to named tuple
return sorted([(i['filesize'],
i['format_id'],
i['url'],
i['ext'],
) for i in audio_tracks], key=lambda x: x[0])
# Todo: Merge this with the original extract method.
# There is no point to seperate this out.
# The only different of from the other extract method is that
# this doesn't have the extract playlist option.
def extract_playlist(url):
with YoutubeDL({"ignoreerrors": True}) as ydl:
info = ydl.extract_info(url, download=False)
return info
if __name__ == "__main__":
# Test playlist download
save_test_json("test.json", json.dumps(extract_playlist(
"https://www.youtube.com/watch?v=mezYFe9DLRk&list=PLYxjne28x-DnByKz30iY1d3m86KyhapVZ&index=6")))
| mit | Python |
9ca219094458cd2594fcef047090710689919f2c | Fix remaining issues | lindenlab/eventlet,lindenlab/eventlet,tempbottle/eventlet,collinstocks/eventlet,tempbottle/eventlet,collinstocks/eventlet,lindenlab/eventlet | tests/stdlib/all.py | tests/stdlib/all.py | """ Convenience module for running standard library tests with nose. The standard
tests are not especially homogeneous, but they mostly expose a test_main method that
does the work of selecting which tests to run based on what is supported by the
platform. On its own, Nose would run all possible tests and many would fail; therefore
we collect all of the test_main methods here in one module and Nose can run it.
Hopefully in the future the standard tests get rewritten to be more nosey.
Many of these tests make connections to external servers, and all.py tries to skip these
tests rather than failing them, so you can get some work done on a plane.
"""
from eventlet import debug
debug.hub_prevent_multiple_readers(False)
def restart_hub():
from eventlet import hubs
hub = hubs.get_hub()
hub_shortname = hub.__module__.split('.')[-1]
# don't restart the pyevent hub; it's not necessary
if hub_shortname != 'pyevent':
hub.abort()
hubs.use_hub(hub_shortname)
def assimilate_patched(name):
try:
modobj = __import__(name, globals(), locals(), ['test_main'])
restart_hub()
except ImportError:
print("Not importing %s, it doesn't exist in this installation/version of Python" % name)
return
else:
method_name = name + "_test_main"
try:
test_method = modobj.test_main
def test_main():
restart_hub()
test_method()
restart_hub()
globals()[method_name] = test_main
test_main.__name__ = name + '.test_main'
except AttributeError:
print("No test_main for %s, assuming it tests on import" % name)
import all_modules
for m in all_modules.get_modules():
assimilate_patched(m)
| """ Convenience module for running standard library tests with nose. The standard tests are not especially homogeneous, but they mostly expose a test_main method that does the work of selecting which tests to run based on what is supported by the platform. On its own, Nose would run all possible tests and many would fail; therefore we collect all of the test_main methods here in one module and Nose can run it. Hopefully in the future the standard tests get rewritten to be more nosey.
Many of these tests make connections to external servers, and all.py tries to skip these tests rather than failing them, so you can get some work done on a plane.
"""
from eventlet import debug
debug.hub_prevent_multiple_readers(False)
def restart_hub():
from eventlet import hubs
hub = hubs.get_hub()
hub_shortname = hub.__module__.split('.')[-1]
# don't restart the pyevent hub; it's not necessary
if hub_shortname != 'pyevent':
hub.abort()
hubs.use_hub(hub_shortname)
def assimilate_patched(name):
try:
modobj = __import__(name, globals(), locals(), ['test_main'])
restart_hub()
except ImportError:
print("Not importing %s, it doesn't exist in this installation/version of Python" % name)
return
else:
method_name = name + "_test_main"
try:
test_method = modobj.test_main
def test_main():
restart_hub()
test_method()
restart_hub()
globals()[method_name] = test_main
test_main.__name__ = name + '.test_main'
except AttributeError:
print("No test_main for %s, assuming it tests on import" % name)
import all_modules
for m in all_modules.get_modules():
assimilate_patched(m)
| mit | Python |
f7c75adb7f371bf347f47d984834c6275614ae37 | Remove deprecated random_cmap | astropy/photutils,larrybradley/photutils | photutils/utils/colormaps.py | photutils/utils/colormaps.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module provides tools for generating matplotlib colormaps.
"""
import numpy as np
from .check_random_state import check_random_state
__all__ = ['make_random_cmap']
def make_random_cmap(ncolors=256, random_state=None):
"""
Make a matplotlib colormap consisting of (random) muted colors.
A random colormap is very useful for plotting segmentation images.
Parameters
----------
ncolors : int, optional
The number of colors in the colormap. The default is 256.
random_state : int or `~numpy.random.mtrand.RandomState`, optional
The pseudo-random number generator state used for random
sampling. Separate function calls with the same
``random_state`` will generate the same colormap.
Returns
-------
cmap : `matplotlib.colors.ListedColormap`
The matplotlib colormap with random colors.
"""
from matplotlib import colors
prng = check_random_state(random_state)
hue = prng.uniform(low=0.0, high=1.0, size=ncolors)
sat = prng.uniform(low=0.2, high=0.7, size=ncolors)
val = prng.uniform(low=0.5, high=1.0, size=ncolors)
hsv = np.dstack((hue, sat, val))
rgb = np.squeeze(colors.hsv_to_rgb(hsv))
return colors.ListedColormap(rgb)
| # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module provides tools for generating matplotlib colormaps.
"""
from astropy.utils import deprecated
import numpy as np
from .check_random_state import check_random_state
__all__ = ['make_random_cmap']
@deprecated('0.7', alternative='make_random_cmap')
def random_cmap(ncolors=256, random_state=None):
"""
Make a matplotlib colormap consisting of (random) muted colors.
A random colormap is very useful for plotting segmentation images.
Parameters
----------
ncolors : int, optional
The number of colors in the colormap. The default is 256.
random_state : int or `~numpy.random.mtrand.RandomState`, optional
The pseudo-random number generator state used for random
sampling. Separate function calls with the same
``random_state`` will generate the same colormap.
Returns
-------
cmap : `matplotlib.colors.ListedColormap`
The matplotlib colormap with random colors.
"""
return make_random_cmap(ncolors=ncolors, random_state=random_state)
def make_random_cmap(ncolors=256, random_state=None):
"""
Make a matplotlib colormap consisting of (random) muted colors.
A random colormap is very useful for plotting segmentation images.
Parameters
----------
ncolors : int, optional
The number of colors in the colormap. The default is 256.
random_state : int or `~numpy.random.mtrand.RandomState`, optional
The pseudo-random number generator state used for random
sampling. Separate function calls with the same
``random_state`` will generate the same colormap.
Returns
-------
cmap : `matplotlib.colors.ListedColormap`
The matplotlib colormap with random colors.
"""
from matplotlib import colors
prng = check_random_state(random_state)
h = prng.uniform(low=0.0, high=1.0, size=ncolors)
s = prng.uniform(low=0.2, high=0.7, size=ncolors)
v = prng.uniform(low=0.5, high=1.0, size=ncolors)
hsv = np.dstack((h, s, v))
rgb = np.squeeze(colors.hsv_to_rgb(hsv))
return colors.ListedColormap(rgb)
| bsd-3-clause | Python |
09bdc51dacfe72597105c468baf356f0b1e81012 | Test modified a second time, to keep Travis happy. | FulcrumIT/skytap,mapledyne/skytap | tests/testLabels.py | tests/testLabels.py | import json
import sys
sys.path.append('..')
from skytap.Labels import Labels # noqa
labels = Labels()
def test_labels():
"""Peform tests relating to labels."""
return
#labels.create("barf", True)
for l in labels:
print l
| import json
import sys
sys.path.append('..')
from skytap.Labels import Labels # noqa
labels = Labels()
def test_labels():
"""Peform tests relating to labels."""
sys.exit()
#labels.create("barf", True)
for l in labels:
print l
| mit | Python |
c5f3f67a661f0614634163704d7ba61d67e59abc | fix the prod logging issue | kencochrane/scorinator,kencochrane/scorinator,kencochrane/scorinator | scorinator/scorinator/settings/prod.py | scorinator/scorinator/settings/prod.py | from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
)
DATABASES = {'default': dj_database_url.config()}
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}},
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s '
'%(process)d %(thread)d %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'null': {
'level':'DEBUG',
'class':'django.utils.log.NullHandler',
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose'
},
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django': {
'handlers': ['console', 'mail_admins'],
'level': 'DEBUG',
'propagate': True,
},
'django.request': {
'handlers': ['console', 'mail_admins'],
'level': 'ERROR',
'propagate': False,
},
'django.db.backends': {
'handlers': ['console', 'mail_admins'],
'level': 'INFO',
'propagate': False,
},
# Catch All Logger -- Captures any other logging
'': {
'handlers': ['console', 'mail_admins'],
'level': 'DEBUG',
'propagate': True,
}
}
}
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Allow all host headers
ALLOWED_HOSTS = ['*'] | from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
)
DATABASES = {'default': dj_database_url.config()}
LOGGING['root'] = {
'level': 'WARNING',
'handlers': ['opbeat']}
LOGGING['loggers']['opbeat'] = {
'level': 'DEBUG',
'handlers': ['console'],
'propagate': False}
LOGGING['loggers']['opbeat.errors'] = {
'level': 'DEBUG',
'handlers': ['console'],
'propagate': False}
LOGGING['handlers']['log_file']['filename'] = ''
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Allow all host headers
ALLOWED_HOSTS = ['*'] | apache-2.0 | Python |
0f6128c3694b08899220a3e2b8d73c27cda7eeee | Format new migration file with black | mociepka/saleor,mociepka/saleor,mociepka/saleor | saleor/product/migrations/0117_auto_20200423_0737.py | saleor/product/migrations/0117_auto_20200423_0737.py | # Generated by Django 3.0.5 on 2020-04-23 12:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("product", "0116_auto_20200225_0237"),
]
operations = [
migrations.AlterField(
model_name="producttranslation",
name="name",
field=models.CharField(max_length=250),
),
]
| # Generated by Django 3.0.5 on 2020-04-23 12:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0116_auto_20200225_0237'),
]
operations = [
migrations.AlterField(
model_name='producttranslation',
name='name',
field=models.CharField(max_length=250),
),
]
| bsd-3-clause | Python |
9cc85af40d05babbe9fc16e71d7dc2b475f3b5e9 | Remove format option to maintain python 2.6 compatibility | murphyke/avocado,murphyke/avocado,murphyke/avocado,murphyke/avocado | avocado/management/subcommands/cache.py | avocado/management/subcommands/cache.py | import sys
import time
import logging
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from avocado.management.base import DataFieldCommand
log = logging.getLogger(__name__)
_help = """\
Pre-caches data produced by various DataField methods that are data dependent.
Pass `--flush` to explicitly flush any existing cache for each property.
"""
CACHED_METHODS = ('size', 'values', 'labels', 'codes')
class Command(DataFieldCommand):
__doc__ = help = _help
option_list = BaseCommand.option_list + (
make_option('--flush', action='store_true',
help='Flushes existing cache for each cached property.'),
make_option('--method', action='append', dest='methods',
default=CACHED_METHODS,
help='Select which methods to pre-cache. Choices: {0}'.format(', '.join(CACHED_METHODS))),
)
def _progress(self):
sys.stdout.write('.')
sys.stdout.flush()
def handle_fields(self, fields, **options):
flush = options.get('flush')
methods = options.get('methods')
for method in methods:
if method not in CACHED_METHODS:
raise CommandError('Invalid method {0}. Choices are {1}'.format(method, ', '.join(CACHED_METHODS)))
fields = fields.filter(enumerable=True)
count = 0
for f in fields:
t0 = time.time()
for method in methods:
func = getattr(f, method)
if flush:
func.flush()
func()
self._progress()
count += 1
log.debug('{0} cache set took {1} seconds'.format(f, time.time() - t0))
print(u'{0} DataFields have been updated'.format(count))
| import sys
import time
import logging
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from avocado.management.base import DataFieldCommand
log = logging.getLogger(__name__)
_help = """\
Pre-caches data produced by various DataField methods that are data dependent.
Pass `--flush` to explicitly flush any existing cache for each property.
"""
CACHED_METHODS = ('size', 'values', 'labels', 'codes')
class Command(DataFieldCommand):
__doc__ = help = _help
option_list = BaseCommand.option_list + (
make_option('--flush', action='store_true',
help='Flushes existing cache for each cached property.'),
make_option('--method', action='append', dest='methods',
default=CACHED_METHODS,
help='Select which methods to pre-cache. Choices: {0}'.format(', '.join(CACHED_METHODS))),
)
def _progress(self):
sys.stdout.write('.')
sys.stdout.flush()
def handle_fields(self, fields, **options):
flush = options.get('flush')
methods = options.get('methods')
for method in methods:
if method not in CACHED_METHODS:
raise CommandError('Invalid method {0}. Choices are {1}'.format(method, ', '.join(CACHED_METHODS)))
fields = fields.filter(enumerable=True)
count = 0
for f in fields:
t0 = time.time()
for method in methods:
func = getattr(f, method)
if flush:
func.flush()
func()
self._progress()
count += 1
log.debug('{0} cache set took {1:,} seconds'.format(f, time.time() - t0))
print(u'{0} DataFields have been updated'.format(count))
| bsd-2-clause | Python |
3aa668460467683f72955cbfd8064a64e4c50b76 | Fix the doc typo | openstack/zaqar,openstack/zaqar,openstack/zaqar,openstack/zaqar | zaqar/common/schemas/flavors.py | zaqar/common/schemas/flavors.py | # Copyright (c) 2013 Rackspace Hosting, Inc.
#
# 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.
"""flavors: JSON schema for zaqar-queues flavors resources."""
# NOTE(flaper87): capabilities can be anything. These will be unique to
# each storage driver, so we don't perform any further validation at
# the transport layer.
patch_capabilities = {
'type': 'object',
'properties': {
'capabilities': {
'type': 'object'
}
}
}
# NOTE(flaper87): a string valid
patch_pool = {
'type': 'object',
'properties': {
'pool': {
'type': 'string'
},
'additionalProperties': False
}
}
create = {
'type': 'object',
'properties': {
'pool': patch_pool['properties']['pool'],
'capabilities': patch_capabilities['properties']['capabilities']
},
# NOTE(flaper87): capabilities need not be present. Storage drivers
# must provide reasonable defaults.
'required': ['pool'],
'additionalProperties': False
}
| # Copyright (c) 2013 Rackspace Hosting, Inc.
#
# 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.
"""flavors: JSON schema for marconi-queues flavors resources."""
# NOTE(flaper87): capabilities can be anything. These will be unique to
# each storage driver, so we don't perform any further validation at
# the transport layer.
patch_capabilities = {
'type': 'object',
'properties': {
'capabilities': {
'type': 'object'
}
}
}
# NOTE(flaper87): a string valid
patch_pool = {
'type': 'object',
'properties': {
'pool': {
'type': 'string'
},
'additionalProperties': False
}
}
create = {
'type': 'object',
'properties': {
'pool': patch_pool['properties']['pool'],
'capabilities': patch_capabilities['properties']['capabilities']
},
# NOTE(flaper87): capabilities need not be present. Storage drivers
# must provide reasonable defaults.
'required': ['pool'],
'additionalProperties': False
}
| apache-2.0 | Python |
42c667ab7e1ed9cdfc711a4d5eb815492d8b1e05 | Fix a test with generate_thumbnail | franek/sigal,jdn06/sigal,cbosdo/sigal,jasuarez/sigal,muggenhor/sigal,jdn06/sigal,kontza/sigal,franek/sigal,t-animal/sigal,t-animal/sigal,kontza/sigal,kontza/sigal,muggenhor/sigal,elaOnMars/sigal,cbosdo/sigal,jasuarez/sigal,jdn06/sigal,Ferada/sigal,saimn/sigal,saimn/sigal,cbosdo/sigal,saimn/sigal,xouillet/sigal,elaOnMars/sigal,Ferada/sigal,jasuarez/sigal,t-animal/sigal,xouillet/sigal,xouillet/sigal,Ferada/sigal | tests/test_image.py | tests/test_image.py | # -*- coding:utf-8 -*-
import os
from sigal.image import generate_image, generate_thumbnail
CURRENT_DIR = os.path.dirname(__file__)
TEST_IMAGE = 'exo20101028-b-full.jpg'
def test_image(tmpdir):
"Test the Image class."
srcfile = os.path.join(CURRENT_DIR, 'sample', 'dir2', TEST_IMAGE)
dstfile = str(tmpdir.join(TEST_IMAGE))
generate_thumbnail(srcfile, dstfile, (200, 150), None)
assert os.path.isfile(dstfile)
| # -*- coding:utf-8 -*-
import os
from sigal.image import generate_image, generate_thumbnail
CURRENT_DIR = os.path.dirname(__file__)
TEST_IMAGE = 'exo20101028-b-full.jpg'
def test_image(tmpdir):
"Test the Image class."
srcfile = os.path.join(CURRENT_DIR, 'sample', 'dir2', TEST_IMAGE)
dstfile = str(tmpdir.join(TEST_IMAGE))
generate_thumbnail(srcfile, dstfile, (200, 150))
assert os.path.isfile(dstfile)
| mit | Python |
ccfe12391050d598ec32861ed146b66f4e907943 | Use big company list for regex entity extraction | uf6/noodles,uf6/noodles | noodles/entities.py | noodles/entities.py | """
Find all company names in a piece of text
extractor = EntityExtractor()
entities = extractor.entities_from_text(text)
> ['acme incorporated', 'fubar limited', ...]
"""
COMPANY_SOURCE_FILE = '/tmp/companies_dev.csv'
import re
import csv
norm_reqs = (
('ltd.', 'limited'),
(' bv ', 'b.v.'),
)
def normalize(text):
text = text.lower()
for (rgx, replacement) in norm_reqs:
text = re.sub(rgx, replacement, text)
return text
def get_company_names():
rows = csv.reader(open(COMPANY_SOURCE_FILE, 'r'))
names = [normalize(row[0]) for row in rows]
return names
class EntityExtractor(object):
def __init__(self):
normed = [re.escape(normalize(x)) for x in get_company_names()]
joined = '|'.join(normed)
self.regex = re.compile('(' + joined + ')')
def entities_from_text(self, text):
return self.regex.findall(normalize(text))
| """
Find all company names in a piece of text
extractor = EntityExtractor()
entities = extractor.entities_from_text(text)
> ['acme incorporated', 'fubar limited', ...]
TODO:
- work out a standard form to normalize company names to
- import company names into the massive regex
"""
import re
norm_reqs = (
('ltd.', 'limited'),
(' bv ', 'b.v.'),
)
def normalize(text):
text = text.lower()
for (rgx, replacement) in norm_reqs:
text = re.sub(rgx, replacement, text)
return text
def get_company_names():
return ['ABC Inc', 'Joost Ltd.']
class EntityExtractor(object):
def __init__(self):
normed = [re.escape(normalize(x)) for x in get_company_names()]
joined = '|'.join(normed)
self.regex = re.compile('(' + joined + ')')
def entities_from_text(self, text):
return self.regex.findall(normalize(text))
| mit | Python |
f46f149783694a97919cd1cc372d848bd2a8dc74 | set default 300 max_size. | soasme/blackgate | blackgate/component.py | blackgate/component.py | # -*- coding: utf-8 -*-
import tornado.ioloop
from blackgate.http_proxy import HTTPProxy
from blackgate.executor import ExecutorPools
class Component(object):
def __init__(self):
self.urls = []
self.pools = ExecutorPools()
self.configurations = {}
@property
def config(self):
return self.configurations
def install(self):
self.install_executor_pool()
self.install_tornado_urls()
def install_executor_pool(self):
ioloop = tornado.ioloop.IOLoop.current()
for proxy in self.configurations.get('proxies', []):
max_size = proxy.get('pool_max_size') or 300
self.pools.register_pool(ioloop, proxy['name'], max_size)
def install_tornado_urls(self):
for proxy in self.configurations.get('proxies', []):
data = dict(
proxy=proxy,
pools=self.pools,
)
self.urls.append(
[proxy['request_path_regex'], HTTPProxy, data,]
)
| # -*- coding: utf-8 -*-
import tornado.ioloop
from blackgate.http_proxy import HTTPProxy
from blackgate.executor import ExecutorPools
class Component(object):
def __init__(self):
self.urls = []
self.pools = ExecutorPools()
self.configurations = {}
@property
def config(self):
return self.configurations
def install(self):
self.install_executor_pool()
self.install_tornado_urls()
def install_executor_pool(self):
ioloop = tornado.ioloop.IOLoop.current()
for proxy in self.configurations.get('proxies', []):
max_size = proxy.get('pool_max_size') or 100
self.pools.register_pool(ioloop, proxy['name'], max_size)
def install_tornado_urls(self):
for proxy in self.configurations.get('proxies', []):
data = dict(
proxy=proxy,
pools=self.pools,
)
self.urls.append(
[proxy['request_path_regex'], HTTPProxy, data,]
)
| mit | Python |
351cd20955a88567888f7c4c4876d2758c0ce9d1 | fix for posti test | aapa/pyfibot,huqa/pyfibot,aapa/pyfibot,huqa/pyfibot,EArmour/pyfibot,lepinkainen/pyfibot,rnyberg/pyfibot,lepinkainen/pyfibot,rnyberg/pyfibot,EArmour/pyfibot | tests/test_posti.py | tests/test_posti.py | # -*- coding: utf-8 -*-
# from nose.tools import eq_
import bot_mock
from pyfibot.modules.module_posti import command_posti
from utils import check_re
bot = bot_mock.BotMock()
def test_posti():
'''11d 1h 45m ago - Item delivered to the recipient. - TAALINTEHDAS 25900'''
regex = u'(\d+d\ )?(\d+h\ )?(\d+m )?ago - (.*?) - (.*?) (\d+)'
assert check_re(regex, command_posti(bot, 'example!example@example.com', '#example', 'JJFI')[1])
| # -*- coding: utf-8 -*-
# from nose.tools import eq_
import bot_mock
from pyfibot.modules.module_posti import command_posti
from utils import check_re
bot = bot_mock.BotMock()
def test_posti():
'''11d 1h 45m ago - Item delivered to the recipient. - TAALINTEHDAS 25900'''
regex = '(\d+d\ )?(\d+h\ )?(\d+m)? ago - (.*?) - (.*?) (\d+)'
assert check_re(regex, command_posti(bot, 'example!example@example.com', '#example', 'JJFI')[1])
| bsd-3-clause | Python |
fc47d6083a85a615a342b6d1596d73808e5c42e2 | Fix tests | Mark-Shine/django-qiniu-storage,glasslion/django-qiniu-storage,jeffrey4l/django-qiniu-storage,jackeyGao/django-qiniu-storage | tests/test_qiniu.py | tests/test_qiniu.py | import os
from os.path import dirname, join
import uuid
import qiniu.conf
import qiniu.io
import qiniu.rs
import qiniu.rsf
QINIU_ACCESS_KEY = os.environ.get('QINIU_ACCESS_KEY')
QINIU_SECRET_KEY = os.environ.get('QINIU_SECRET_KEY')
QINIU_BUCKET_NAME = os.environ.get('QINIU_BUCKET_NAME')
QINIU_BUCKET_DOMAIN = os.environ.get('QINIU_BUCKET_DOMAIN')
qiniu.conf.ACCESS_KEY = QINIU_ACCESS_KEY
qiniu.conf.SECRET_KEY = QINIU_SECRET_KEY
QINIU_PUT_POLICY= qiniu.rs.PutPolicy(QINIU_BUCKET_NAME)
def test_put_file():
ASSET_FILE_NAME = 'bootstrap.min.css'
with open(join(dirname(__file__),'assets', ASSET_FILE_NAME), 'rb') as assset_file:
text = assset_file.read()
print "Test text: %s" % text
token = QINIU_PUT_POLICY.token()
ret, err = qiniu.io.put(token, join(str(uuid.uuid4()), ASSET_FILE_NAME), text)
if err:
raise IOError(
"Error message: %s" % err) | import os
from os.path import dirname, join
import uuid
import qiniu.conf
import qiniu.io
import qiniu.rs
import qiniu.rsf
QINIU_ACCESS_KEY = os.environ.get('QINIU_ACCESS_KEY')
QINIU_SECRET_KEY = os.environ.get('QINIU_SECRET_KEY')
QINIU_BUCKET_NAME = os.environ.get('QINIU_BUCKET_NAME')
QINIU_BUCKET_DOMAIN = os.environ.get('QINIU_BUCKET_DOMAIN')
qiniu.conf.ACCESS_KEY = QINIU_ACCESS_KEY
qiniu.conf.SECRET_KEY = QINIU_SECRET_KEY
QINIU_PUT_POLICY= qiniu.rs.PutPolicy(QINIU_BUCKET_NAME)
def test_put_file():
ASSET_FILE_NAME = 'bootstrap.min.css'
with open(join(dirname(__file__),'assets', ASSET_FILE_NAME), 'rb') as assset_file:
text = assset_file.read()
print "Test text: %s" % text
ret, err = qiniu.io.put(token, join(str(uuid.uuid4()), ASSET_FILE_NAME), text)
if err:
raise IOError(
"Error message: %s" % err) | mit | Python |
0f17c8d3438b910c2fa6db7c588487b591fc3d77 | Test utils | eiginn/passpie,scorphus/passpie,marcwebbie/passpie,scorphus/passpie,marcwebbie/passpie,eiginn/passpie | tests/test_utils.py | tests/test_utils.py | try:
from mock import mock_open
except:
from unittest.mock import mock_open
import yaml
from passpie.utils import genpass, mkdir_open, load_config, get_version
from .helpers import MockerTestCase
class UtilsTests(MockerTestCase):
def test_genpass_generates_a_password_with_length_32(self):
password = genpass()
self.assertEqual(len(password), 32)
def test_mkdir_open_makedirs_on_path_dirname(self):
mock_os = self.patch("passpie.utils.os")
self.patch("passpie.utils.open", self.mock_open(), create=True)
path = "path/to/foo.pass"
with mkdir_open(path, "w"):
dirname = mock_os.path.dirname(path)
mock_os.makedirs.assert_called_once_with(dirname)
def test_mkdir_open_handle_oserror_for_file_exist(self):
mock_os = self.patch("passpie.utils.os")
self.patch("passpie.utils.open", self.mock_open(), create=True)
path = "path/to/foo.pass"
mock_os.makedirs.side_effect = OSError(17, "File Exists")
with mkdir_open(path, "w") as fd:
self.assertIsNotNone(fd)
mock_os.makedirs.side_effect = OSError(2, "File Not Found")
with self.assertRaises(OSError):
with mkdir_open(path, "w") as fd:
pass
def test_load_config_replaces_sets_user_config_element(mocker):
DEFAULT_CONFIG = {'path': 'default_path', 'short_commands': True}
USER_CONFIG = {'path': 'user_path'}
mocker.patch('passpie.utils.os.path.exists', return_value=True)
mocker.patch('passpie.utils.os.path.isfile', return_value=True)
mocker.patch('passpie.utils.open', mock_open(), create=True)
mocker.patch('passpie.utils.yaml.load', return_value=USER_CONFIG)
config = load_config(DEFAULT_CONFIG, 'configrc')
assert config.path == USER_CONFIG['path']
assert config.short_commands == DEFAULT_CONFIG['short_commands']
def test_load_config_logs_debug_message_when_malformed_config(mocker):
mocker.patch('passpie.utils.open', mock_open(), create=True)
mocker.patch('passpie.utils.os.path.exists', return_value=True)
mocker.patch('passpie.utils.os.path.isfile', return_value=True)
mocker.patch('passpie.utils.yaml.load',
side_effect=yaml.scanner.ScannerError)
mock_logging = mocker.patch('passpie.utils.logging')
load_config({}, {})
assert mock_logging.debug.called
def test_get_version_uses_get_distribution_to_find_version(mocker):
expected_version = '1.0'
mock_dist = mocker.patch('passpie.utils.get_distribution')()
mock_dist.location = '/Users/foo/applications'
mock_dist.version = expected_version
mocker.patch('passpie.utils.os.path.normcase')
version = get_version()
assert version == '1.0'
def test_get_version_returns_install_message_when_dist_not_found(mocker):
message = 'Please install this project with setup.py or pip'
mocker.patch('passpie.utils.get_distribution')
mocker.patch('passpie.utils.os.path.normcase',
side_effect=['path1', 'path2'])
version = get_version()
assert version == message
| from .helpers import MockerTestCase
from passpie.utils import genpass, mkdir_open
class UtilsTests(MockerTestCase):
def test_genpass_generates_a_password_with_length_32(self):
password = genpass()
self.assertEqual(len(password), 32)
def test_mkdir_open_makedirs_on_path_dirname(self):
mock_os = self.patch("passpie.utils.os")
self.patch("passpie.utils.open", self.mock_open(), create=True)
path = "path/to/foo.pass"
with mkdir_open(path, "w"):
dirname = mock_os.path.dirname(path)
mock_os.makedirs.assert_called_once_with(dirname)
def test_mkdir_open_handle_oserror_for_file_exist(self):
mock_os = self.patch("passpie.utils.os")
self.patch("passpie.utils.open", self.mock_open(), create=True)
path = "path/to/foo.pass"
mock_os.makedirs.side_effect = OSError(17, "File Exists")
with mkdir_open(path, "w") as fd:
self.assertIsNotNone(fd)
mock_os.makedirs.side_effect = OSError(2, "File Not Found")
with self.assertRaises(OSError):
with mkdir_open(path, "w") as fd:
pass
| mit | Python |
3dc6df3aa399fb403a0acbc494c5338e7be7f76c | clean up tests | danpoland/pyramid-restful-framework | tests/test_views.py | tests/test_views.py | from pyramid import testing
from pyramid.response import Response
from unittest import TestCase
from pyramid_restful.views import APIView
class TestView(APIView):
def get(self, request, *args, **kwargs):
return Response({'method': 'GET'})
def post(self, request, *args, **kwargs):
return Response({'method': 'POST', 'data': request.body})
class InitKwargsView(APIView):
def get(self, request, *args, **kwargs):
return Response({'name': self.name})
class ExceptionView(APIView):
def get(self, request, *args, **kwargs):
raise Exception('test exception')
class APIViewTests(TestCase):
def setUp(self):
self.test_view = TestView.as_view(name='TestView')
def test_implemented_method_dispatch(self):
request = testing.DummyRequest()
response = self.test_view(request)
expected = {'method': 'GET'}
assert response.status_code == 200
assert response.body == expected
def test_method_not_allowed(self):
request = testing.DummyRequest()
request.method = 'PUT'
response = self.test_view(request)
assert response.status_code == 405
def test_initkwargs(self):
view = InitKwargsView.as_view(name='test')
request = testing.DummyRequest()
response = view(request)
expected = {'name': 'test'}
assert response.body == expected
def test_raises_exception(self):
view = ExceptionView.as_view()
request = testing.DummyRequest()
self.assertRaises(Exception, view, request)
def test_invalid_method_exception(self):
request = testing.DummyRequest()
request.method = 'PUTZ'
response = self.test_view(request)
assert response.status_code == 405
def test_options_request(self):
request = testing.DummyRequest()
request.method = 'OPTIONS'
response = self.test_view(request)
assert response.headers.get('Allow') == ['GET', 'POST', 'OPTIONS']
| import pytest
from pyramid import testing
from pyramid.response import Response
from unittest import TestCase
from pyramid_restful.views import APIView
class GetView(APIView):
def get(self, request, *args, **kwargs):
return Response({'method': 'GET'})
class PostView(APIView):
def post(self, request, *args, **kwargs):
return Response({'method': 'POST', 'data': request.body})
class InitKwargsView(APIView):
def get(self, request, *args, **kwargs):
return Response({'name': self.name})
class ExceptionView(APIView):
def get(self, request, *args, **kwargs):
raise Exception('test exception')
class APIViewTests(TestCase):
def setUp(self):
self.get_view = GetView.as_view()
self.post_view = PostView.as_view()
self.init_view = InitKwargsView.as_view(name='test')
def test_implemented_method_dispatch(self):
request = testing.DummyRequest()
response = self.get_view(request)
expected = {'method': 'GET'}
assert response.status_code == 200
assert response.body == expected
def test_method_not_allowed(self):
request = testing.DummyRequest(post={'data': 'testing'})
response = self.get_view(request)
assert response.status_code == 405
def test_allowed_methods(self):
view = GetView()
expected = ['GET', 'OPTIONS']
assert expected == view.allowed_methods
def test_initkwargs(self):
request = testing.DummyRequest()
response = self.init_view(request)
expected = {'name': 'test'}
assert response.body == expected
def test_raises_exception(self):
view = ExceptionView().as_view()
request = testing.DummyRequest()
self.assertRaises(Exception, view, request)
def test_invalid_method_exception(self):
view = self.get_view
request = testing.DummyRequest()
request.method = 'PUTZ'
response = view(request)
assert response.status_code == 405
def test_options(self):
view = self.get_view
request = testing.DummyRequest()
request.method = 'OPTIONS'
response = view(request)
assert response.headers.get('Allow') == ['GET', 'OPTIONS']
| bsd-2-clause | Python |
bd53fe8df0642fd85d655994619fedaf4347e826 | Test create admission (database) with collection date and admission date | gems-uff/labsys,gems-uff/labsys,gems-uff/labsys | tests/test_views.py | tests/test_views.py | import unittest
import datetime
from flask import current_app, url_for, get_flashed_messages
from app import create_app, db
from app.models import *
class TestCreateAdmissionView(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
self.client = self.app.test_client(use_cookies=True)
self.valid_admission_form = {
'id_lvrs_intern': '011/2012',
'samples-0-collection_date': '12/12/2012',
'samples-0-admission_date': '13/12/2012',
}
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_context.pop()
def test_duplicate_id_lvrs_intern(self):
data = self.valid_admission_form
a = Admission(id_lvrs_intern=data['id_lvrs_intern'])
db.session.add(a)
db.session.commit()
duplicate_id_lvrs_intern = 'Número Interno já cadastrado!'
response = self.client.post(
url_for('main.create_admission'), data=data, follow_redirects=True)
self.assertTrue(
duplicate_id_lvrs_intern in response.get_data(as_text=True))
self.assertEqual(len(Admission.query.all()), 1)
def test_create_valid_admission(self):
data = self.valid_admission_form
self.assertEqual(len(Admission.query.all()), 0)
response = self.client.post(
url_for('main.create_admission'), data=data, follow_redirects=True)
self.assertTrue(response.status_code == 200)
admission = Admission.query.first()
self.assertEqual(admission.id_lvrs_intern, data['id_lvrs_intern'])
self.assertEqual(admission.samples.first().collection_date,
datetime.date(2012, 12, 12))
self.assertEqual(admission.samples.first().admission_date,
datetime.date(2012, 12, 13))
| import unittest
from flask import current_app, url_for, get_flashed_messages
from app import create_app, db
from app.models import *
class TestCreateAdmissionView(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
self.client = self.app.test_client(use_cookies=True)
self.valid_admission_form = {
'id_lvrs_intern': 1,
}
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_context.pop()
def test_duplicate_id_lvrs_intern(self):
a = Admission(id_lvrs_intern=1)
db.session.add(a)
db.session.commit()
data = {
'id_lvrs_intern': '1',
'samples-0-collection_date': '12/12/2012',
'samples-0-admission_date': '13/12/2012',
}
duplicate_id_lvrs_intern = 'Número Interno já cadastrado!'
response = self.client.post(
url_for('main.create_admission'), data=data, follow_redirects=True)
self.assertTrue(
duplicate_id_lvrs_intern in response.get_data(as_text=True))
self.assertTrue(
len(Admission.query.filter_by(id_lvrs_intern='1').all()), 1)
| mit | Python |
6a4a3388c39115982019a6581a6f0393e33d92e1 | patch the daily coupons url to only accept integers | rapidsms/rapidsms-legacy,rapidsms/rapidsms-legacy,rapidsms/rapidsms-legacy | apps/nigeria/urls.py | apps/nigeria/urls.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import os
from django.conf.urls.defaults import *
import apps.nigeria.views as views
urlpatterns = patterns('',
url(r'^locgen/?$', views.generate),
url(r'^reports/?$', views.index),
url(r'^reports/summary/(?P<locid>\d*)/?$', views.index),
url(r'^reports/logistics/summary/(?P<locid>\d*)/?$', views.logistics_summary),
url(r'^reports/bednets/summary/(?P<range>.*)/?(?P<from>.*)/?(?P<to>.*)/?$', views.bednets_summary),
url(r'^reports/coupons/summary/(?P<locid>\d*)/?$', views.coupons_summary),
url(r'^reports/supply/summary/(?P<range>.*)/?(?P<from>.*)/?(?P<to>.*)/?$', views.supply_summary),
url(r'^reports/bednets/daily/(?P<locid>\d*)/?$', views.bednets_daily),
url(r'^reports/bednets/weekly/(?P<locid>\d*)/?$', views.bednets_weekly),
url(r'^reports/bednet/monthly/(?P<locid>\d*)/?$', views.bednets_monthly),
url(r'^reports/coupons/daily/(?P<locid>\d*)/?$', views.coupons_daily),
url(r'^reports/coupons/weekly/(?P<locid>\d*)/?$', views.coupons_weekly),
url(r'^reports/coupons/monthly/(?P<locid>\d*)/?$', views.coupons_monthly),
url(r'^reports/supply/daily/(?P<locid>\d*)/?$', views.supply_daily),
url(r'^reports/supply/weekly/(?P<locid>\d*)/?$', views.supply_weekly),
url(r'^reports/supply/monthly/(?P<locid>\d*)/?$', views.supply_monthly),
url(r'^reports/test/?$', views.index),
(r'^static/nigeria/(?P<path>.*)$', "django.views.static.serve",
{"document_root": os.path.dirname(__file__) + "/static"}),
)
| #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import os
from django.conf.urls.defaults import *
import apps.nigeria.views as views
urlpatterns = patterns('',
url(r'^locgen/?$', views.generate),
url(r'^reports/?$', views.index),
url(r'^reports/summary/(?P<locid>\d*)/?$', views.index),
url(r'^reports/logistics/summary/(?P<locid>\d*)/?$', views.logistics_summary),
url(r'^reports/bednets/summary/(?P<range>.*)/?(?P<from>.*)/?(?P<to>.*)/?$', views.bednets_summary),
url(r'^reports/coupons/summary/(?P<locid>.*)/?$', views.coupons_summary),
url(r'^reports/supply/summary/(?P<range>.*)/?(?P<from>.*)/?(?P<to>.*)/?$', views.supply_summary),
url(r'^reports/bednets/daily/(?P<locid>\d*)/?$', views.bednets_daily),
url(r'^reports/bednets/weekly/(?P<locid>\d*)/?$', views.bednets_weekly),
url(r'^reports/bednet/monthly/(?P<locid>\d*)/?$', views.bednets_monthly),
url(r'^reports/coupons/daily/(?P<locid>\d*)/?$', views.coupons_daily),
url(r'^reports/coupons/weekly/(?P<locid>\d*)/?$', views.coupons_weekly),
url(r'^reports/coupons/monthly/(?P<locid>\d*)/?$', views.coupons_monthly),
url(r'^reports/supply/daily/(?P<locid>\d*)/?$', views.supply_daily),
url(r'^reports/supply/weekly/(?P<locid>\d*)/?$', views.supply_weekly),
url(r'^reports/supply/monthly/(?P<locid>\d*)/?$', views.supply_monthly),
url(r'^reports/test/?$', views.index),
(r'^static/nigeria/(?P<path>.*)$', "django.views.static.serve",
{"document_root": os.path.dirname(__file__) + "/static"}),
)
| bsd-3-clause | Python |
354ee85623b948ec3a439caa35b9646be081762d | Add some maths | Py101/py101-assignments-marcosco,Py101/py101-assignments-marcosco | 01/myfirstprogram.py | 01/myfirstprogram.py | '''
my first program in python
'''
import sys
numbers = sys.argv[1:]
a,b = int(numbers[0]),int(numbers[1])
print("the number you've passed are:")
print(a,b)
print("a+b=", a+b)
print("a**b=", a**b)
print("a/b=", a/b)
print("a//b=", a//b)
print("a%b=", a%b)
| '''
my first program in python
'''
import sys
numbers = sys.argv[1:]
a,b = int(numbers[0]),int(numbers[1])
print("the number you've passed are:")
print(a,b)
print("a+b=", a+b) | mit | Python |
b700e45dba6e6f4341fbe3b2a7ae08d5052c5f1f | Revert "weird json object settings notation" | BowdoinOrient/bongo,BowdoinOrient/bongo,BowdoinOrient/bongo,BowdoinOrient/bongo | bongo/settings/prod.py | bongo/settings/prod.py | from os import environ
from common import *
# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': SITE_NAME,
'USER': SITE_NAME,
'PASSWORD': environ.get("{}_POSTGRES_PASS".format(SITE_NAME.upper())),
'HOST': '127.0.0.1',
'PORT': '5432',
},
'archive': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DB02Orient',
'USER': 'root',
'PASSWORD': '',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = environ.get('{}_SECRET_KEY'.format(SITE_NAME.upper()), '')
# See: http://django-storages.readthedocs.org/en/latest/index.html
INSTALLED_APPS += (
'djsupervisor',
'raven.contrib.django.raven_compat',
)
# See: https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
ALLOWED_HOSTS = [
'.bjacobel.com',
'.bowdoinorient.com'
]
########## CACHE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#caches
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
########## END CACHE CONFIGURATION
#### RAVEN ###
RAVEN_CONFIG = {
'dsn': environ.get('{}_RAVEN_DSN'.format(SITE_NAME.upper())),
}
### END RAVEN #####
###### LOGENTRIES #####
from logentries import LogentriesHandler
import logging
'handlers': {
'logentries_handler': {
'token': environ.get('{}_LOGENTRIES_TOKEN'.format(SITE_NAME.upper())),
'class': 'logentries.LogentriesHandler'
},
}
'loggers': {
'logentries': {
'handlers': ['logentries_handler'],
'level': 'INFO',
},
} | from os import environ
from common import *
from logentries import LogentriesHandler
import logging
# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': SITE_NAME,
'USER': SITE_NAME,
'PASSWORD': environ.get("{}_POSTGRES_PASS".format(SITE_NAME.upper())),
'HOST': '127.0.0.1',
'PORT': '5432',
},
'archive': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DB02Orient',
'USER': 'root',
'PASSWORD': '',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = environ.get('{}_SECRET_KEY'.format(SITE_NAME.upper()), '')
# See: http://django-storages.readthedocs.org/en/latest/index.html
INSTALLED_APPS += (
'djsupervisor',
'raven.contrib.django.raven_compat',
)
# See: https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
ALLOWED_HOSTS = [
'.bjacobel.com',
'.bowdoinorient.com'
]
########## CACHE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#caches
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
########## END CACHE CONFIGURATION
#### RAVEN ###
RAVEN_CONFIG = {
'dsn': environ.get('{}_RAVEN_DSN'.format(SITE_NAME.upper())),
}
### END RAVEN #####
###### LOGENTRIES #####
LOGGING['handlers']['logentries_handler'] = {
'token': environ.get('{}_LOGENTRIES_TOKEN'.format(SITE_NAME.upper())),
'class': 'logentries.LogentriesHandler'
}
LOGGING['loggers']['logentries'] = {
'handlers': ['logentries_handler'],
'level': 'INFO',
} | mit | Python |
dafcb40078e78c03fd2938cf9a31818301830bce | Fix tweeting. | ChattanoogaPublicLibrary/booksforcha | booksforcha/twitter.py | booksforcha/twitter.py | # -*- coding: utf-8 -*-
import tweepy
import os
from entry import get_next_to_run, remove_from_runner, send_runner_to_queue
CONSUMER_KEY = os.environ['CONSUMER_KEY']
CONSUMER_SECRET = os.environ['CONSUMER_SECRET']
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
ACCESS_TOKEN_SECRET = os.environ['ACCESS_TOKEN_SECRET']
def message(info, url):
return (info + ' ' + url).encode('utf-8')
def send_tweet(info, url):
try:
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)
api.update_status(status=message(info, url))
return True
except tweepy.error.TweepError:
return False
def send_queued_tweet():
next_entry = get_next_to_run()
if send_tweet(next_entry.title, next_entry.link):
return remove_from_runner(next_entry)
else:
send_runner_to_queue(next_entry)
return False
| # -*- coding: utf-8 -*-
import tweepy
import os
from entry import get_next_to_run, remove_from_runner, send_runner_to_queue
CONSUMER_KEY = os.environ['CONSUMER_KEY']
CONSUMER_SECRET = os.environ['CONSUMER_SECRET']
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
ACCESS_TOKEN_SECRET = os.environ['ACCESS_TOKEN_SECRET']
def message(info, url):
return (info + ' ' + url).encode('utf-8')
def send_tweet(info, url):
try:
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)
api.update_status(message(info, url))
return True
except tweepy.error.TweepError:
return False
def send_queued_tweet():
next_entry = get_next_to_run()
if send_tweet(next_entry.title, next_entry.link):
return remove_from_runner(next_entry)
else:
send_runner_to_queue(next_entry)
return False
| mit | Python |
a4fd67c068954aae11c2eee4d71ccf578404cfee | update admin interface, http://bugzilla.pculture.org/show_bug.cgi?id=15311 | ReachingOut/unisubs,wevoice/wesub,norayr/unisubs,ujdhesa/unisubs,pculture/unisubs,ReachingOut/unisubs,norayr/unisubs,norayr/unisubs,eloquence/unisubs,ujdhesa/unisubs,ofer43211/unisubs,wevoice/wesub,wevoice/wesub,pculture/unisubs,ofer43211/unisubs,pculture/unisubs,eloquence/unisubs,pculture/unisubs,ujdhesa/unisubs,ReachingOut/unisubs,eloquence/unisubs,ReachingOut/unisubs,ofer43211/unisubs,ujdhesa/unisubs,ofer43211/unisubs,norayr/unisubs,wevoice/wesub,eloquence/unisubs | apps/videos/admin.py | apps/videos/admin.py | # Universal Subtitles, universalsubtitles.org
#
# Copyright (C) 2010 Participatory Culture Foundation
#
# 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/agpl-3.0.html.
from django.contrib import admin
from videos.models import Video, SubtitleLanguage, SubtitleVersion, Subtitle
from django.core.urlresolvers import reverse
class VideoAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'title', 'languages']
search_fields = ['video_id', 'title', 'videourl__url']
def languages(self, obj):
lang_qs = obj.subtitlelanguage_set.all()
link_tpl = '<a href="%s">%s</a>'
links = []
for item in lang_qs:
url = reverse('admin:videos_subtitlelanguage_change', args=[item.pk])
links.append(link_tpl % (url, item.get_language_display() or '[undefined]'))
return ', '.join(links)
languages.allow_tags = True
class SubtitleLanguageAdmin(admin.ModelAdmin):
list_display = ['video', 'is_original', 'language', 'is_complete', 'was_complete', 'versions']
list_filter = ['is_original', 'is_complete']
def versions(self, obj):
version_qs = obj.subtitleversion_set.all()
link_tpl = '<a href="%s">#%s</a>'
links = []
for item in version_qs:
url = reverse('admin:videos_subtitleversion_change', args=[item.pk])
links.append(link_tpl % (url, item.version_no))
return ', '.join(links)
versions.allow_tags = True
class SubtitleVersionAdmin(admin.ModelAdmin):
list_display = ['language', 'version_no', 'note', 'time_change', 'text_change']
list_filter = []
class SubtitleAdmin(admin.ModelAdmin):
list_display = ['version', 'subtitle_id', 'subtitle_order', 'subtitle_text', 'start_time', 'end_time']
#admin.site.register(Subtitle, SubtitleAdmin)
admin.site.register(SubtitleVersion, SubtitleVersionAdmin)
admin.site.register(Video, VideoAdmin)
admin.site.register(SubtitleLanguage, SubtitleLanguageAdmin)
| # Universal Subtitles, universalsubtitles.org
#
# Copyright (C) 2010 Participatory Culture Foundation
#
# 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/agpl-3.0.html.
from django.contrib import admin
from videos.models import Video, SubtitleLanguage, SubtitleVersion, Subtitle
from django.core.urlresolvers import reverse
class VideoAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'title', 'languages']
search_fields = ['video_id', 'title', 'videourl__url']
def languages(self, obj):
lang_qs = obj.subtitlelanguage_set.all()
link_tpl = '<a href="%s">%s</a>'
links = []
for item in lang_qs:
url = reverse('admin:videos_subtitlelanguage_change', args=[item.pk])
links.append(link_tpl % (url, item.get_language_display() or '[undefined]'))
return ', '.join(links)
languages.allow_tags = True
class SubtitleLanguageAdmin(admin.ModelAdmin):
list_display = ['video', 'is_original', 'language', 'is_complete', 'was_complete']
list_filter = ['is_original', 'is_complete']
class SubtitleVersionAdmin(admin.ModelAdmin):
list_display = ['language', 'version_no', 'note', 'time_change', 'text_change']
list_filter = []
class SubtitleAdmin(admin.ModelAdmin):
list_display = ['version', 'subtitle_id', 'subtitle_order', 'subtitle_text', 'start_time', 'end_time']
admin.site.register(Subtitle, SubtitleAdmin)
admin.site.register(SubtitleVersion, SubtitleVersionAdmin)
admin.site.register(Video, VideoAdmin)
admin.site.register(SubtitleLanguage, SubtitleLanguageAdmin)
| agpl-3.0 | Python |
a25dcc43dbebd91c845431a850c73f36b998ad6e | Increase version for release 0.3.1 | TissueMAPS/TmServer | tmserver/version.py | tmserver/version.py | # TmServer - TissueMAPS server application.
# Copyright (C) 2016 Markus D. Herrmann, University of Zurich and Robin Hafen
#
# 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/>.
__version__ = '0.3.1'
| # TmServer - TissueMAPS server application.
# Copyright (C) 2016 Markus D. Herrmann, University of Zurich and Robin Hafen
#
# 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/>.
__version__ = '0.3.1rc'
| agpl-3.0 | Python |
93e2ff0dd32a72efa90222988d4289c70bb55b98 | Add summary to book listing | c2corg/v6_api,c2corg/v6_api,c2corg/v6_api | c2corg_api/models/common/fields_book.py | c2corg_api/models/common/fields_book.py | DEFAULT_FIELDS = [
'locales.title',
'locales.summary',
'locales.description',
'locales.lang',
'author',
'editor',
'activities',
'url',
'isbn',
'book_types',
'publication_date',
'langs',
'nb_pages'
]
DEFAULT_REQUIRED = [
'locales',
'locales.title',
'book_types'
]
LISTING_FIELDS = [
'locales',
'locales.title',
'locales.summary',
'activities',
'author',
'quality',
'book_types'
]
fields_book = {
'fields': DEFAULT_FIELDS,
'required': DEFAULT_REQUIRED,
'listing': LISTING_FIELDS
}
| DEFAULT_FIELDS = [
'locales.title',
'locales.summary',
'locales.description',
'locales.lang',
'author',
'editor',
'activities',
'url',
'isbn',
'book_types',
'publication_date',
'langs',
'nb_pages'
]
DEFAULT_REQUIRED = [
'locales',
'locales.title',
'book_types'
]
LISTING_FIELDS = [
'locales',
'locales.title',
'activities',
'author',
'quality',
'book_types'
]
fields_book = {
'fields': DEFAULT_FIELDS,
'required': DEFAULT_REQUIRED,
'listing': LISTING_FIELDS
}
| agpl-3.0 | Python |
4683d651c1ed93d0813bffae5df34ca309ca099d | Update calc_inst_hr.py | MounikaVanka/bme590hrm,MounikaVanka/bme590hrm | Code/calc_inst_hr.py | Code/calc_inst_hr.py | import numpy as np
import scipy.signal
def calc_inst_hr(time, voltage):
""" calculate instantaneous HR from ECG data input
:param time: numpy array, seconds
:param voltage: numpy array, mV
:return: heart rate in bpm
"""
""" indices = peakutils.indexes(voltage,
thres = 0.95*np.max(voltage),
min_dist = 1000)
"""
# get sampling rate
fs = 1 / (time[1] - time[0])
rates = np.array([np.size(voltage)/200]) # search width
# find peaks
peaks = scipy.signal.find_peaks_cwt(voltage, fs / rates)
max_val = np.amax(voltage)
keep_peaks = np.array([])
for index in peaks:
if voltage[index] >= 0.7 * max_val:
keep_peaks = np.append(keep_peaks, index)
keep_peaks = keep_peaks.astype(int)
""" just take last two peaks to get instantaneous.
not that accurate obviously
"""
beat_diff = time[keep_peaks[1]] - time[keep_peaks[0]] # seconds per beat
bpm = int(1 / beat_diff * 60) # beats per minute
return bpm
| import numpy as np
import scipy.signal
def calc_inst_hr(time, voltage):
""" calculate instantaneous HR from ECG data input
:param time: numpy array, seconds
:param voltage: numpy array, mV
:return: heart rate in bpm
"""
# indices = peakutils.indexes(voltage, thres = 0.95*np.max(voltage), min_dist = 1000)
# get sampling rate
fs = 1 / (time[1] - time[0])
rates = np.array([np.size(voltage)/200]) # search width
# find peaks
peaks = scipy.signal.find_peaks_cwt(voltage, fs / rates)
max_val = np.amax(voltage)
keep_peaks = np.array([])
for index in peaks:
if voltage[index] >= 0.7 * max_val:
keep_peaks = np.append(keep_peaks, index)
keep_peaks = keep_peaks.astype(int)
# just take last two peaks to get instantaneous. not that accurate obviously
beat_diff = time[keep_peaks[1]] - time[keep_peaks[0]] # seconds per beat
bpm = int(1 / beat_diff * 60) # beats per minute
return bpm
| mit | Python |
51831743ab915eccd6144fdac16a9483fea84012 | Fix search in local dev | uq-eresearch/uqam,uq-eresearch/uqam,uq-eresearch/uqam,uq-eresearch/uqam | dev_settings.py | dev_settings.py | """
Extra Development settings
Will override any default settings if a 'development_mode' file exists.
"""
from default_settings import *
DEBUG = True
TEMPLATE_DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uqam.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INSTALLED_APPS += ('debug_toolbar',)
# Debug Toolbar configuration
INTERNAL_IPS = ('127.0.0.1','10.0.2.2')
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.version.VersionDebugPanel',
'debug_toolbar.panels.timer.TimerDebugPanel',
'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel',
'debug_toolbar.panels.headers.HeaderDebugPanel',
'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',
'debug_toolbar.panels.template.TemplateDebugPanel',
'debug_toolbar.panels.sql.SQLDebugPanel',
'debug_toolbar.panels.signals.SignalDebugPanel',
'debug_toolbar.panels.logger.LoggingPanel',
)
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False
}
MEDIA_ROOT = os.path.join(DIRNAME, 'media')
HAYSTACK_WHOOSH_PATH = '/home/omad/whoosh/cat_index'
| """
Extra Development settings
Will override any default settings if a 'development_mode' file exists.
"""
from default_settings import *
DEBUG = True
TEMPLATE_DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uqam.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INSTALLED_APPS += ('debug_toolbar',)
# Debug Toolbar configuration
INTERNAL_IPS = ('127.0.0.1','10.0.2.2')
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.version.VersionDebugPanel',
'debug_toolbar.panels.timer.TimerDebugPanel',
'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel',
'debug_toolbar.panels.headers.HeaderDebugPanel',
'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',
'debug_toolbar.panels.template.TemplateDebugPanel',
'debug_toolbar.panels.sql.SQLDebugPanel',
'debug_toolbar.panels.signals.SignalDebugPanel',
'debug_toolbar.panels.logger.LoggingPanel',
)
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False
}
MEDIA_ROOT = os.path.join(DIRNAME, 'media')
| bsd-3-clause | Python |
4008824b7b7bf8338b057bc0b594774cb055c794 | Decrease pattern timebase to 0.01 sec now that slow-mo bug is fixed | jonspeicher/blinkyfun | blinkylib/patterns/blinkypattern.py | blinkylib/patterns/blinkypattern.py | class BlinkyPattern(object):
def __init__(self, blinkytape):
self._blinkytape = blinkytape
self._animated = False
self._timebase_sec = 0.01
@property
def animated(self):
return self._animated
@property
def timebase_sec(self):
return self._timebase_sec
def setup(self):
pass
def animate(self):
pass
def teardown(self):
pass
| class BlinkyPattern(object):
def __init__(self, blinkytape):
self._blinkytape = blinkytape
self._animated = False
self._timebase_sec = 0.05
@property
def animated(self):
return self._animated
@property
def timebase_sec(self):
return self._timebase_sec
def setup(self):
pass
def animate(self):
pass
def teardown(self):
pass
| mit | Python |
38845ecae177635b98a2e074355227f0c9f9834d | Add Widget and WidgetList to namespace | CartoDB/cartoframes,CartoDB/cartoframes | cartoframes/viz/widgets/__init__.py | cartoframes/viz/widgets/__init__.py | """
Widget functions to generate widgets faster.
"""
from __future__ import absolute_import
from .animation_widget import animation_widget
from .category_widget import category_widget
from .default_widget import default_widget
from .formula_widget import formula_widget
from .histogram_widget import histogram_widget
from .time_series_widget import time_series_widget
from ..widget import Widget
from ..widget_list import WidgetList
def _inspect(widget):
import inspect
lines = inspect.getsource(widget)
print(lines)
__all__ = [
'Widget',
'WidgetList',
'animation_widget',
'category_widget',
'default_widget',
'formula_widget',
'histogram_widget',
'time_series_widget',
]
| """
Widget functions to generate widgets faster.
"""
from __future__ import absolute_import
from .animation_widget import animation_widget
from .category_widget import category_widget
from .default_widget import default_widget
from .formula_widget import formula_widget
from .histogram_widget import histogram_widget
from .time_series_widget import time_series_widget
def _inspect(widget):
import inspect
lines = inspect.getsource(widget)
print(lines)
__all__ = [
'animation_widget',
'category_widget',
'default_widget',
'formula_widget',
'histogram_widget',
'time_series_widget',
]
| bsd-3-clause | Python |
3640a5b1976ea6c5b21617cda11324d73071fb9f | Fix for whitespace.py so that Windows will save Unix EOLs. | GoogleCloudPlatform/datastore-ndb-python,GoogleCloudPlatform/datastore-ndb-python | trimwhitespace.py | trimwhitespace.py | """Remove trailing whitespace from files in current path and sub directories."""
import os, glob
def scanpath(path):
for filepath in glob.glob(os.path.join(path, '*')):
if os.path.isdir(filepath):
scanpath(filepath)
else:
trimwhitespace(filepath)
def trimwhitespace(filepath):
handle = open(filepath, 'rb')
stripped = ''
flag = False
for line in handle.readlines():
stripped_line = line.rstrip() + '\n'
if line != stripped_line:
flag = True
stripped += stripped_line
handle.close()
if flag:
print('FAIL: %s' % filepath)
overwritefile(filepath, stripped)
else:
print('OK: %s' % filepath)
def overwritefile(filepath, contents):
handle = open(filepath, 'wb')
handle.write(contents)
handle.close()
if __name__ == '__main__':
scanpath('.')
| """Remove trailing whitespace from files in current path and sub directories."""
import os, glob
def scanpath(path):
for filepath in glob.glob(os.path.join(path, '*')):
if os.path.isdir(filepath):
scanpath(filepath)
else:
trimwhitespace(filepath)
def trimwhitespace(filepath):
handle = open(filepath, 'r')
stripped = ''
flag = False
for line in handle.readlines():
stripped_line = line.rstrip() + '\n'
if line != stripped_line:
flag = True
stripped += stripped_line
handle.close()
if flag:
overwritefile(filepath, stripped)
def overwritefile(filepath, contents):
handle = open(filepath, 'w')
handle.write(contents)
handle.close()
if __name__ == '__main__':
scanpath('.')
| apache-2.0 | Python |
23584ddb3c598365f299f76b68ea7f5e9985be75 | fix current_roles contains a dict (#248) | vimalloc/flask-jwt-extended | examples/tokens_from_complex_objects.py | examples/tokens_from_complex_objects.py | from flask import Flask, jsonify, request
from flask_jwt_extended import (
JWTManager, jwt_required, create_access_token,
get_jwt_identity, get_jwt_claims
)
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'super-secret' # Change this!
jwt = JWTManager(app)
# This is an example of a complex object that we could build
# a JWT from. In practice, this will likely be something
# like a SQLAlchemy instance.
class UserObject:
def __init__(self, username, roles):
self.username = username
self.roles = roles
# Create a function that will be called whenever create_access_token
# is used. It will take whatever object is passed into the
# create_access_token method, and lets us define what custom claims
# should be added to the access token.
@jwt.user_claims_loader
def add_claims_to_access_token(user):
return {'roles': user.roles}
# Create a function that will be called whenever create_access_token
# is used. It will take whatever object is passed into the
# create_access_token method, and lets us define what the identity
# of the access token should be.
@jwt.user_identity_loader
def user_identity_lookup(user):
return user.username
@app.route('/login', methods=['POST'])
def login():
username = request.json.get('username', None)
password = request.json.get('password', None)
if username != 'test' or password != 'test':
return jsonify({"msg": "Bad username or password"}), 401
# Create an example UserObject
user = UserObject(username='test', roles=['foo', 'bar'])
# We can now pass this complex object directly to the
# create_access_token method. This will allow us to access
# the properties of this object in the user_claims_loader
# function, and get the identity of this object from the
# user_identity_loader function.
access_token = create_access_token(identity=user)
ret = {'access_token': access_token}
return jsonify(ret), 200
@app.route('/protected', methods=['GET'])
@jwt_required
def protected():
ret = {
'current_identity': get_jwt_identity(), # test
'current_roles': get_jwt_claims()['roles'] # ['foo', 'bar']
}
return jsonify(ret), 200
if __name__ == '__main__':
app.run()
| from flask import Flask, jsonify, request
from flask_jwt_extended import (
JWTManager, jwt_required, create_access_token,
get_jwt_identity, get_jwt_claims
)
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'super-secret' # Change this!
jwt = JWTManager(app)
# This is an example of a complex object that we could build
# a JWT from. In practice, this will likely be something
# like a SQLAlchemy instance.
class UserObject:
def __init__(self, username, roles):
self.username = username
self.roles = roles
# Create a function that will be called whenever create_access_token
# is used. It will take whatever object is passed into the
# create_access_token method, and lets us define what custom claims
# should be added to the access token.
@jwt.user_claims_loader
def add_claims_to_access_token(user):
return {'roles': user.roles}
# Create a function that will be called whenever create_access_token
# is used. It will take whatever object is passed into the
# create_access_token method, and lets us define what the identity
# of the access token should be.
@jwt.user_identity_loader
def user_identity_lookup(user):
return user.username
@app.route('/login', methods=['POST'])
def login():
username = request.json.get('username', None)
password = request.json.get('password', None)
if username != 'test' or password != 'test':
return jsonify({"msg": "Bad username or password"}), 401
# Create an example UserObject
user = UserObject(username='test', roles=['foo', 'bar'])
# We can now pass this complex object directly to the
# create_access_token method. This will allow us to access
# the properties of this object in the user_claims_loader
# function, and get the identity of this object from the
# user_identity_loader function.
access_token = create_access_token(identity=user)
ret = {'access_token': access_token}
return jsonify(ret), 200
@app.route('/protected', methods=['GET'])
@jwt_required
def protected():
ret = {
'current_identity': get_jwt_identity(), # test
'current_roles': get_jwt_claims() # ['foo', 'bar']
}
return jsonify(ret), 200
if __name__ == '__main__':
app.run()
| mit | Python |
d98d6a83c666d18c959286f0e8d052d262ed3f5b | Allow editing preferred articles in Django admin | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend | cla_backend/apps/knowledgebase/admin.py | cla_backend/apps/knowledgebase/admin.py | from django.contrib import admin
from .models import Article, ArticleCategoryMatrix
class ArticleCategoryMatrixInline(admin.TabularInline):
model = ArticleCategoryMatrix
class ArticleAdmin(admin.ModelAdmin):
actions = None
inlines = [ArticleCategoryMatrixInline]
ordering = ['service_name']
fields = (
'resource_type', 'service_name', 'organisation', 'website',
'description', 'how_to_use', 'when_to_use', 'address', 'helpline',
'opening_hours', 'keywords', 'geographic_coverage',
'type_of_service', 'accessibility'
)
list_display = (
'service_name', 'resource_type'
)
search_fields = [
'service_name', 'organisation', 'description', 'how_to_use',
'when_to_use', 'keywords', 'type_of_service'
]
class ArticleCategoryMatrixAdmin(admin.ModelAdmin):
list_display = (
'preferred_signpost',
'category_name',
'service_name',)
list_editable = ('preferred_signpost',)
list_display_links = ('service_name',)
ordering = (
'article_category__name',
'-preferred_signpost',
'article__service_name')
def service_name(self, obj):
return obj.article.service_name
def category_name(self, obj):
return obj.article_category.name
admin.site.register(Article, ArticleAdmin)
admin.site.register(ArticleCategoryMatrix, ArticleCategoryMatrixAdmin)
| from django.contrib import admin
from .models import Article, ArticleCategoryMatrix
class ArticleCategoryMatrixInline(admin.TabularInline):
model = ArticleCategoryMatrix
class ArticleAdmin(admin.ModelAdmin):
actions = None
inlines = [ArticleCategoryMatrixInline]
ordering = ['service_name']
fields = (
'resource_type', 'service_name', 'organisation', 'website',
'description', 'how_to_use', 'when_to_use', 'address', 'helpline',
'opening_hours', 'keywords', 'geographic_coverage',
'type_of_service', 'accessibility'
)
list_display = (
'service_name', 'resource_type'
)
search_fields = [
'service_name', 'organisation', 'description', 'how_to_use',
'when_to_use', 'keywords', 'type_of_service'
]
admin.site.register(Article, ArticleAdmin)
| mit | Python |
51d5c78471b2605225106166b6fc480be61cbbd9 | remove extra return | andrewlehmann/autoweather | auto_weather/main.py | auto_weather/main.py | import schedule
import time
import sendmessage
import location
import getweather
import mongo
def job():
lat, lon = location.get_location()
weather = getweather.get_weather(lat, lon) # retrieve weather info
mongo.insert(weather) # put info in database
msg = sendmessage.create_message(weather)
sendmessage.send_message(msg) # send text message
def main():
schedule.every().day.at("08:00").do(job)
while True:
schedule.run_pending()
time.sleep(60)
if __name__ == "__main__":
main()
| import schedule
import time
import sendmessage
import location
import getweather
import mongo
def job():
lat, lon = location.get_location()
weather = getweather.get_weather(lat, lon) # retrieve weather info
mongo.insert(weather) # put info in database
msg = sendmessage.create_message(weather)
sendmessage.send_message(msg) # send text message
return
def main():
schedule.every().day.at("08:00").do(job)
while True:
schedule.run_pending()
time.sleep(60)
if __name__ == "__main__":
main()
| mit | Python |
5eebad6ffa7ed125d3d42710ca6d93b9457f8587 | Fix checkpointer and save model json file as well | theislab/dca,theislab/dca,theislab/dca | autoencoder/train.py | autoencoder/train.py | # Copyright 2016 Goekcen Eraslan
#
# 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.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os, json
from .network import autoencoder
from . import io
import numpy as np
from keras.optimizers import SGD
from keras.callbacks import TensorBoard, ModelCheckpoint
def train(X, hidden_size=32, learning_rate=0.01,
log_dir='logs', epochs=10, batch_size=32, **kwargs):
assert isinstance(X, np.ndarray), 'Input mush be a numpy array'
model, _, _ = autoencoder(X.shape[1], hidden_size=hidden_size)
optimizer = SGD(lr=learning_rate, momentum=0.9, nesterov=True)
model.compile(loss='mse', optimizer=optimizer)
checkpointer = ModelCheckpoint(filepath="%s/weights.hdf5" % log_dir,
verbose=1)
if not os.path.exists(log_dir):
os.makedirs(log_dir)
with open('%s/arch.json' % log_dir, 'w') as f:
json.dump(model.to_json(), f)
print(model.summary())
model.fit(X, X,
nb_epoch=epochs,
batch_size=batch_size,
shuffle=True,
callbacks=[TensorBoard(log_dir=log_dir, histogram_freq=1),
checkpointer],
**kwargs)
def train_with_args(args):
X = io.read_records(args.trainingset)
assert isinstance(X, np.ndarray), 'Only numpy for now'
train(X=X, hidden_size=args.hiddensize,
learning_rate=args.learningrate,
log_dir=args.logdir,
epochs=args.epochs,
batch_size=args.batchsize)
| # Copyright 2016 Goekcen Eraslan
#
# 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.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os, json
from .network import autoencoder
from . import io
import numpy as np
from keras.optimizers import SGD
from keras.callbacks import TensorBoard, ModelCheckpoint
def train(X, hidden_size=32, learning_rate=0.01,
log_dir='logs', epochs=10, batch_size=32, **kwargs):
assert isinstance(X, np.ndarray), 'Input mush be a numpy array'
model, _, _ = autoencoder(X.shape[1], hidden_size=hidden_size)
optimizer = SGD(lr=learning_rate, momentum=0.9, nesterov=True)
model.compile(loss='mse', optimizer=optimizer)
checkpointer = ModelCheckpoint(filepath="%s/weights.{epoch:02d}.hdf5" % log_dir,
verbose=1, save_best_only=True)
#with open('%s/arch.json' % log_dir, 'w'):
#json.dump(model.to_json())
print(model.summary())
model.fit(X, X,
nb_epoch=epochs,
batch_size=batch_size,
shuffle=True,
callbacks=[TensorBoard(log_dir=log_dir, histogram_freq=1),
checkpointer]
)
def train_with_args(args):
X = io.read_records(args.trainingset)
assert isinstance(X, np.ndarray), 'Only numpy for now'
train(X=X, hidden_size=args.hiddensize,
learning_rate=args.learningrate,
log_dir=args.logdir,
epochs=args.epochs,
batch_size=args.batchsize)
| apache-2.0 | Python |
144b716eb321fb05458613a4a448dc3786445083 | Handle new users in suggestion module | DirkHoffmann/indico,pferreir/indico,OmeGak/indico,DirkHoffmann/indico,ThiefMaster/indico,mvidalgarcia/indico,pferreir/indico,pferreir/indico,indico/indico,mic4ael/indico,ThiefMaster/indico,mvidalgarcia/indico,mic4ael/indico,DirkHoffmann/indico,mvidalgarcia/indico,indico/indico,OmeGak/indico,mic4ael/indico,mvidalgarcia/indico,OmeGak/indico,mic4ael/indico,indico/indico,pferreir/indico,DirkHoffmann/indico,ThiefMaster/indico,ThiefMaster/indico,indico/indico,OmeGak/indico | indico/util/redis/suggestions.py | indico/util/redis/suggestions.py | # This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico 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.
#
# Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>.
from collections import OrderedDict
from indico.util.redis import scripts
from indico.util.redis import client as redis_client
from indico.util.redis import write_client as redis_write_client
def schedule_check(avatar, client=None):
if client is None:
client = redis_write_client
client.sadd('suggestions/scheduled_checks', avatar.id)
def unschedule_check(avatar_id, client=None):
if client is None:
client = redis_write_client
client.srem('suggestions/scheduled_checks', avatar_id)
def next_scheduled_check(client=None):
"""Returns an avatar id that is scheduled to be checked"""
if client is None:
client = redis_client
return client.srandmember('suggestions/scheduled_checks')
def suggest(avatar, what, id, score, client=None):
if client is None:
client = redis_write_client
scripts.suggestions_suggest(avatar.id, what, id, score, client=client)
def unsuggest(avatar, what, id, ignore=False, client=None):
if client is None:
client = redis_write_client
client.zrem('suggestions/suggested:%s:%s' % (avatar.id, what), id)
if ignore:
client.sadd('suggestions/ignored:%s:%s' % (avatar.id, what), id)
def unignore(avatar, what, id, client=None):
if client is None:
client = redis_write_client
client.srem('suggestions/ignored:%s:%s' % (avatar.id, what), id)
def get_suggestions(avatar, what, client=None):
if client is None:
client = redis_client
key = 'suggestions/suggested:%s:%s' % (avatar.id, what)
return OrderedDict(client.zrevrangebyscore(key, '+inf', '-inf', withscores=True))
def merge_avatars(destination, source, client=None):
if client is None:
client = redis_write_client
scripts.suggestions_merge_avatars(destination.id, source.id, client=client)
def delete_avatar(avatar, client=None):
if client is None:
client = redis_write_client
client.srem('suggestions/scheduled_checks', avatar.id)
client.delete('suggestions/suggested:%s:category' % avatar.id)
client.delete('suggestions/ignored:%s:category' % avatar.id)
| # This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico 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.
#
# Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>.
from collections import OrderedDict
from indico.util.redis import scripts
from indico.util.redis import client as redis_client
from indico.util.redis import write_client as redis_write_client
def schedule_check(avatar, client=None):
if client is None:
client = redis_write_client
client.sadd('suggestions/scheduled_checks', avatar.getId())
def unschedule_check(avatar_id, client=None):
if client is None:
client = redis_write_client
client.srem('suggestions/scheduled_checks', avatar_id)
def next_scheduled_check(client=None):
"""Returns an avatar id that is scheduled to be checked"""
if client is None:
client = redis_client
return client.srandmember('suggestions/scheduled_checks')
def suggest(avatar, what, id, score, client=None):
if client is None:
client = redis_write_client
scripts.suggestions_suggest(avatar.getId(), what, id, score, client=client)
def unsuggest(avatar, what, id, ignore=False, client=None):
if client is None:
client = redis_write_client
client.zrem('suggestions/suggested:%s:%s' % (avatar.getId(), what), id)
if ignore:
client.sadd('suggestions/ignored:%s:%s' % (avatar.getId(), what), id)
def unignore(avatar, what, id, client=None):
if client is None:
client = redis_write_client
client.srem('suggestions/ignored:%s:%s' % (avatar.getId(), what), id)
def get_suggestions(avatar, what, client=None):
if client is None:
client = redis_client
key = 'suggestions/suggested:%s:%s' % (avatar.getId(), what)
return OrderedDict(client.zrevrangebyscore(key, '+inf', '-inf', withscores=True))
def merge_avatars(destination, source, client=None):
if client is None:
client = redis_write_client
scripts.suggestions_merge_avatars(destination.getId(), source.getId(), client=client)
def delete_avatar(avatar, client=None):
if client is None:
client = redis_write_client
client.srem('suggestions/scheduled_checks', avatar.getId())
client.delete('suggestions/suggested:%s:category' % avatar.getId())
client.delete('suggestions/ignored:%s:category' % avatar.getId())
| mit | Python |
f08c465c7d3f096cdd468d681dad899355ef52b5 | Remove debug messages | karel-brinda/prophyle,karel-brinda/prophyle,karel-brinda/prophyle,karel-brinda/prophyle | bin/read_assignment.py | bin/read_assignment.py | #! /usr/bin/env python3
import os
import shutil
import datetime
import sys
import argparse
import operator
from ete3 import Tree
import logging
DEFAULT_FORMAT = 1
class TreeIndex:
def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT):
self.tree_newick_fn=tree_newick_fn
self.tree=Tree(tree_newick_fn,format=1)
self.name_dict={}
for node in self.tree.traverse("postorder"):
self.name_dict[node.name]=node
#print (self.name_dict)
def assdict_to_weightdic(self,ass_dict):
all_nodes_hit=set()
w=ass_dict.copy()
for node_name in ass_dict:
node=self.name_dict[node_name]
while node.up:
node=node.up
if node.name in ass_dict:
w[node_name]+=ass_dict[node.name]
return w
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Implementation of assignment algorithm')
parser.add_argument('-i', '--input',
type=argparse.FileType('r'),
required=True,
dest='input_file',
help = 'input file'
)
parser.add_argument('-n', '--newick-tree',
type=str,
metavar='str',
required=True,
dest='newick_fn',
help = 'newick tree',
)
args = parser.parse_args()
newick_fn=args.newick_fn
inp_fo=args.input_file
ti=TreeIndex(
tree_newick_fn=newick_fn,
)
#print("lets go")
#ti.process_node(ti.tree.get_tree_root())
for x in inp_fo:
x=x.strip()
stat,rname,ass_node,rlen,ass_kmers=x.split("\t")
ass_dict={}
ass_blocks=ass_kmers.split(" ")
for b in ass_blocks:
(ids,count)=b.split(":")
ids=ids.split(",")
for iid in ids:
if iid !="0":
try:
ass_dict[iid]+=int(count)
except KeyError:
ass_dict[iid]=int(count)
if ass_dict!={}:
weight_dict=ti.assdict_to_weightdic(ass_dict)
stat="C"
#arg max
#FIX: when 2 arg max exist
ass_node=max(weight_dict.items(), key=operator.itemgetter(1))[0]
#print(ass_dict)
#print(weight_dict)
print("\t".join([stat,rname,ass_node,rlen,ass_kmers]))
| #! /usr/bin/env python3
import os
import shutil
import datetime
import sys
import argparse
import operator
from ete3 import Tree
import logging
DEFAULT_FORMAT = 1
class TreeIndex:
def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT):
self.tree_newick_fn=tree_newick_fn
self.tree=Tree(tree_newick_fn,format=1)
self.name_dict={}
for node in self.tree.traverse("postorder"):
self.name_dict[node.name]=node
print (self.name_dict)
def assdict_to_weightdic(self,ass_dict):
all_nodes_hit=set()
w=ass_dict.copy()
for node_name in ass_dict:
node=self.name_dict[node_name]
while node.up:
node=node.up
if node.name in ass_dict:
w[node_name]+=ass_dict[node.name]
return w
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Implementation of assignment algorithm')
parser.add_argument('-i', '--input',
type=argparse.FileType('r'),
required=True,
dest='input_file',
help = 'input file'
)
parser.add_argument('-n', '--newick-tree',
type=str,
metavar='str',
required=True,
dest='newick_fn',
help = 'newick tree',
)
args = parser.parse_args()
newick_fn=args.newick_fn
inp_fo=args.input_file
ti=TreeIndex(
tree_newick_fn=newick_fn,
)
print("lets go")
#ti.process_node(ti.tree.get_tree_root())
for x in inp_fo:
stat,rname,ass_node,rlen,ass_kmers=x.split("\t")
ass_dict={}
ass_blocks=ass_kmers.split(" ")
for b in ass_blocks:
(ids,count)=b.split(":")
ids=ids.split(",")
for iid in ids:
if iid !="0":
try:
ass_dict[iid]+=int(count)
except KeyError:
ass_dict[iid]=int(count)
if ass_dict!={}:
weight_dict=ti.assdict_to_weightdic(ass_dict)
stat="C"
#arg max
#FIX: when 2 arg max exist
ass_node=max(weight_dict.items(), key=operator.itemgetter(1))[0]
print(ass_dict, weight_dict)
print("\t".join([stat,rname,ass_node,rlen,ass_kmers]))
| mit | Python |
a4ceb78b6189ecb352099840ff32fc1b213e7b6b | Add toggling check products | stormaaja/csvconverter,stormaaja/csvconverter,stormaaja/csvconverter | stock_updater.py | stock_updater.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from multiple_products_found_error import MultipleProductsFoundError
from product_not_found_error import ProductNotFoundError
class StockUpdater:
def __init__(self, db_connection):
self.db_connection = db_connection
self.perform_check_product = True
def set_perform_check_product(self, value):
self.perform_check_product = value
def set_items(self, items):
self.items = items
def set_table(self, table):
self.table = table
def set_destination_colums(self, product_code, quantity):
self.product_code_column = product_code
self.quantity_column = quantity
def update(self):
# cursor.execute_many?
for item in self.items:
self.update_quantity(item['product_code'], item['quantity'])
def check_product(self, product_code):
cursor = self.db_connection.cursor()
check_query = "SELECT COUNT(*) FROM {} WHERE {} LIKE ?".format(
self.table, self.product_code_column)
product_count = cursor.execute(check_query, (product_code,)).fetchone()[0]
cursor.close()
if product_count == 0:
raise ProductNotFoundError(
"No product found with product code {}"
.format(product_code))
elif product_count > 1:
raise MultipleProductsFoundError(
"Multiple products found with product code {}"
.format(product_code))
def update_quantity(self, product_code, quantity):
if self.perform_check_product:
self.check_product(product_code)
cursor = self.db_connection.cursor()
query = "UPDATE {} SET {} = ? WHERE {} LIKE ?".format(
self.table, self.quantity_column, self.product_code_column)
try:
cursor.execute(query, (quantity, product_code))
self.db_connection.commit()
except Exception as err:
raise err
finally:
cursor.close()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from multiple_products_found_error import MultipleProductsFoundError
from product_not_found_error import ProductNotFoundError
class StockUpdater:
def __init__(self, db_connection):
self.db_connection = db_connection
def set_items(self, items):
self.items = items
def set_table(self, table):
self.table = table
def set_destination_colums(self, product_code, quantity):
self.product_code_column = product_code
self.quantity_column = quantity
def update(self):
# cursor.execute_many?
for item in self.items:
self.update_quantity(item['product_code'], item['quantity'])
def check_product(self, product_code):
cursor = self.db_connection.cursor()
check_query = "SELECT COUNT(*) FROM {} WHERE {} LIKE ?".format(
self.table, self.product_code_column)
product_count = cursor.execute(check_query, (product_code,)).fetchone()[0]
cursor.close()
if product_count == 0:
raise ProductNotFoundError(
"No product found with product code {}"
.format(product_code))
elif product_count > 1:
raise MultipleProductsFoundError(
"Multiple products found with product code {}"
.format(product_code))
def update_quantity(self, product_code, quantity):
self.check_product(product_code)
cursor = self.db_connection.cursor()
query = "UPDATE {} SET {} = ? WHERE {} LIKE ?".format(
self.table, self.quantity_column, self.product_code_column)
try:
cursor.execute(query, (quantity, product_code))
self.db_connection.commit()
except Exception as err:
raise err
finally:
cursor.close()
| mit | Python |
294eca830f1252057461dec6840303fca7760da3 | add published to Article | armstrong/armstrong.apps.articles,armstrong/armstrong.apps.articles | armstrong/apps/articles/models.py | armstrong/apps/articles/models.py | from armstrong.apps.content.models import Content
from armstrong.core.arm_content.mixins.publication import PublishedManager
from django.db import models
class Article(Content):
body = models.TextField()
published = PublishedManager()
| from armstrong.apps.content.models import Content
from django.db import models
class Article(Content):
body = models.TextField()
| apache-2.0 | Python |
13675da66f389759d405922f4771ad200f263a50 | fix filter check | legacysurvey/rapala,legacysurvey/rapala,imcgreer/rapala | bokrmpipe/bokrmpipe.py | bokrmpipe/bokrmpipe.py | #!/usr/bin/env python
import os
import re
import glob
from copy import copy
import multiprocessing
import numpy as np
from numpy.core.defchararray import add as char_add
import fitsio
from astropy.table import Table
from bokpipe import bokpl
from bokpipe import __version__ as pipeVersion
def load_darksky_frames(filt):
darkSkyFrames = np.loadtxt(os.path.join('config',
'bokrm_darksky_%s.txt'%filt),
dtype=[('utDate','S8'),('fileName','S35'),
('skyVal','f4')])
# a quick pruning of the repeat images
return darkSkyFrames[::2]
def set_rm_defaults(args):
if args.rawdir is None:
args.rawdir = os.environ['BOK90PRIMERAWDIR']
if args.output is None:
args.output = os.path.join(os.environ['BOK90PRIMEOUTDIR'],
pipeVersion)
if args.obsdb is None:
args.obsdb = os.path.join('config','sdssrm-bok2014.fits')
return args
if __name__=='__main__':
import argparse
parser = argparse.ArgumentParser()
parser = bokpl.init_file_args(parser)
parser = bokpl.init_pipeline_args(parser)
parser.add_argument('--darkskyframes',action='store_true',
help='load only the dark sky frames')
args = parser.parse_args()
args = set_rm_defaults(args)
dataMap = bokpl.init_data_map(args)
dataMap = bokpl.set_master_cals(dataMap)
if args.darkskyframes:
# must select a band
if args.band is None or args.band not in ['g','i']:
raise ValueError("Must select a band for dark sky frames (-b)")
frames = load_darksky_frames(args.band)
dataMap.setFrameList(frames['utDate'],frames['fileName'])
bokpl.run_pipe(dataMap,args)
| #!/usr/bin/env python
import os
import re
import glob
from copy import copy
import multiprocessing
import numpy as np
from numpy.core.defchararray import add as char_add
import fitsio
from astropy.table import Table
from bokpipe import bokpl
from bokpipe import __version__ as pipeVersion
def load_darksky_frames(filt):
darkSkyFrames = np.loadtxt(os.path.join('config',
'bokrm_darksky_%s.txt'%filt),
dtype=[('utDate','S8'),('fileName','S35'),
('skyVal','f4')])
# a quick pruning of the repeat images
return darkSkyFrames[::2]
def set_rm_defaults(args):
if args.rawdir is None:
args.rawdir = os.environ['BOK90PRIMERAWDIR']
if args.output is None:
args.output = os.path.join(os.environ['BOK90PRIMEOUTDIR'],
pipeVersion)
if args.obsdb is None:
args.obsdb = os.path.join('config','sdssrm-bok2014.fits')
return args
if __name__=='__main__':
import argparse
parser = argparse.ArgumentParser()
parser = bokpl.init_file_args(parser)
parser = bokpl.init_pipeline_args(parser)
parser.add_argument('--darkskyframes',action='store_true',
help='load only the dark sky frames')
args = parser.parse_args()
args = set_rm_defaults(args)
dataMap = bokpl.init_data_map(args)
dataMap = bokpl.set_master_cals(dataMap)
if args.darkskyframes:
# must select a band
if bands is None or bands not in ['g','i']:
raise ValueError("Must select a band for dark sky frames (-b)")
frames = load_darksky_frames(bands)
dataMap.setFrameList(frames['utDate'],frames['fileName'])
bokpl.run_pipe(dataMap,args)
| bsd-3-clause | Python |
ec62d4f439299f20b7321e83a49e585aca644aab | refactor __main__.cli and __main__.main | Thor77/TeamspeakStats,Thor77/TeamspeakStats | tsstats/__main__.py | tsstats/__main__.py | import argparse
import json
import logging
from os.path import abspath, exists
from tsstats.config import parse_config
from tsstats.exceptions import InvalidConfig
from tsstats.log import parse_logs
from tsstats.template import render_template
logger = logging.getLogger('tsstats')
def cli():
parser = argparse.ArgumentParser(
description='A simple Teamspeak stats-generator - based on server-logs'
)
parser.add_argument(
'-c', '--config',
type=str, help='path to config'
)
parser.add_argument(
'--idmap', type=str, help='path to id_map'
)
parser.add_argument(
'-l', '--log',
type=str, help='path to your logfile(s)'
)
parser.add_argument(
'-o', '--output',
type=str, help='path to the output-file', default='stats.html'
)
parser.add_argument(
'-d', '--debug',
help='debug mode', action='store_true'
)
args = parser.parse_args()
main(**vars(args))
def main(config=None, idmap=None, log=None, output=None, debug=False):
if config:
config = abspath(config)
if not exists(config):
logger.fatal('config not found (%s)', config)
idmap, log, output, debug = parse_config(config)
if debug:
logger.setLevel(logging.DEBUG)
if idmap:
idmap = abspath(idmap)
if not exists(idmap):
logger.fatal('identmap not found (%s)', idmap)
# read id_map
identmap = json.load(open(idmap))
else:
identmap = None
if not log or not output:
raise InvalidConfig('log or output missing')
clients = parse_logs(log, ident_map=identmap)
render_template(clients, output=abspath(output))
if __name__ == '__main__':
cli()
| import argparse
import json
import logging
from os.path import abspath, exists
from tsstats.config import parse_config
from tsstats.exceptions import ConfigNotFound
from tsstats.log import parse_logs
from tsstats.template import render_template
logger = logging.getLogger('tsstats')
def cli():
parser = argparse.ArgumentParser(
description='A simple Teamspeak stats-generator - based on server-logs'
)
parser.add_argument(
'-c', '--config',
type=str, help='path to config'
)
parser.add_argument(
'--idmap', type=str, help='path to id_map'
)
parser.add_argument(
'-l', '--log',
type=str, help='path to your logfile(s)'
)
parser.add_argument(
'-o', '--output',
type=str, help='path to the output-file', default='stats.html'
)
parser.add_argument(
'-d', '--debug',
help='debug mode', action='store_true'
)
args = parser.parse_args()
if args.debug:
logger.setLevel(logging.DEBUG)
main(args.config, args.idmap)
def main(config_path='config.ini', id_map_path='id_map.json'):
# check cmdline-args
config_path = abspath(config_path)
id_map_path = abspath(id_map_path)
if not exists(config_path):
raise ConfigNotFound(config_path)
if exists(id_map_path):
# read id_map
id_map = json.load(open(id_map_path))
else:
id_map = {}
log, output = parse_config(config_path)
clients = parse_logs(log, ident_map=id_map)
render_template(clients, output=output)
if __name__ == '__main__':
cli()
| mit | Python |
d510ae8c08e5fd34d9bd73e23af1d6762e05e0fd | Bump version | basepair/basepair-python,basepair/basepair-python | basepair/__init__.py | basepair/__init__.py | '''set up basepair package'''
from __future__ import print_function
import sys
import requests
from .utils import colors
# from .api import basepair
__title__ = 'basepair'
__version__ = '1.6.6'
__copyright__ = 'Copyright [2017] - [2020] Basepair INC'
JSON_URL = 'https://pypi.python.org/pypi/{}/json'.format(__title__)
try:
resp = requests.get(JSON_URL, timeout=1)
if resp.status_code == 200:
latest_version = resp.json()['info']['version']
if latest_version != __version__:
print(colors.color.warning(
'WARNING: The latest version of basepair package is {}. '
'Please upgrade to avail the latest features and bug-fixes'
''.format(latest_version)), file=sys.stderr)
except (requests.exceptions.ConnectionError, requests.exceptions.ReadTimeout):
print('warning: no internet', file=sys.stderr)
def connect(*args, **kwargs):
'''return basepair package'''
from basepair.api import BpApi
return BpApi(*args, **kwargs)
| '''set up basepair package'''
from __future__ import print_function
import sys
import requests
from .utils import colors
# from .api import basepair
__title__ = 'basepair'
__version__ = '1.6.5'
__copyright__ = 'Copyright [2017] - [2020] Basepair INC'
JSON_URL = 'https://pypi.python.org/pypi/{}/json'.format(__title__)
try:
resp = requests.get(JSON_URL, timeout=1)
if resp.status_code == 200:
latest_version = resp.json()['info']['version']
if latest_version != __version__:
print(colors.color.warning(
'WARNING: The latest version of basepair package is {}. '
'Please upgrade to avail the latest features and bug-fixes'
''.format(latest_version)), file=sys.stderr)
except (requests.exceptions.ConnectionError, requests.exceptions.ReadTimeout):
print('warning: no internet', file=sys.stderr)
def connect(*args, **kwargs):
'''return basepair package'''
from basepair.api import BpApi
return BpApi(*args, **kwargs)
| mit | Python |
a7799346a5f2ce5c9fdb276e2957d3ed1f8efc7f | Fix for RHESSI sample image header parsing | dpshelio/sunpy,mjm159/sunpy,dpshelio/sunpy,Alex-Ian-Hamilton/sunpy,Alex-Ian-Hamilton/sunpy,mjm159/sunpy,Alex-Ian-Hamilton/sunpy,dpshelio/sunpy | sunpy/io/fits.py | sunpy/io/fits.py | """
FITS File Reader
Notes
-----
PyFITS
[1] Due to the way PyFITS works with images the header dictionary may
differ depending on whether is accessed before or after the fits[0].data
is requested. If the header is read before the data then the original
header will be returned. If the header is read after the data has been
accessed then the data will have been scaled and a modified header
reflecting these changes will be returned: BITPIX may differ and
BSCALE and B_ZERO may be dropped in the modified version.
[2] The verify('fix') call attempts to handle violations of the FITS
standard. For example, nan values will be converted to "nan" strings.
Attempting to cast a pyfits header to a dictionary while it contains
invalid header tags will result in an error so verifying it early on
makes the header easier to work with later.
References
----------
| http://stackoverflow.com/questions/456672/class-factory-in-python
| http://stsdas.stsci.edu/download/wikidocs/The_PyFITS_Handbook.pdf
"""
from __future__ import absolute_import
from sunpy.map.header import MapHeader
import pyfits
__author__ = "Keith Hughitt"
__email__ = "keith.hughitt@nasa.gov"
def read(filepath):
"""Reads in the file at the specified location"""
hdulist = pyfits.open(filepath)
hdulist.verify('silentfix')
fits_comment = hdulist[0].header.get_comment()
# PyFITS 2.x
if len(fits_comment) > 0 and isinstance(fits_comment[0], basestring):
comments = [val for val in fits_comment]
else:
# PyFITS 3.x
comments = [card.value for card in fits_comment]
comment = "".join(comments).strip()
header = MapHeader(hdulist[0].header)
header['comment'] = comment
return hdulist[0].data, header
def get_header(filepath):
"""Returns the header for a given file"""
hdulist = pyfits.open(filepath)
hdulist.verify('silentfix')
comment = "".join(hdulist[0].header.get_comment()).strip()
header = MapHeader(hdulist[0].header)
header['comment'] = comment
return header
| """
FITS File Reader
Notes
-----
PyFITS
[1] Due to the way PyFITS works with images the header dictionary may
differ depending on whether is accessed before or after the fits[0].data
is requested. If the header is read before the data then the original
header will be returned. If the header is read after the data has been
accessed then the data will have been scaled and a modified header
reflecting these changes will be returned: BITPIX may differ and
BSCALE and B_ZERO may be dropped in the modified version.
[2] The verify('fix') call attempts to handle violations of the FITS
standard. For example, nan values will be converted to "nan" strings.
Attempting to cast a pyfits header to a dictionary while it contains
invalid header tags will result in an error so verifying it early on
makes the header easier to work with later.
References
----------
| http://stackoverflow.com/questions/456672/class-factory-in-python
| http://stsdas.stsci.edu/download/wikidocs/The_PyFITS_Handbook.pdf
"""
from __future__ import absolute_import
from sunpy.map.header import MapHeader
import pyfits
__author__ = "Keith Hughitt"
__email__ = "keith.hughitt@nasa.gov"
def read(filepath):
"""Reads in the file at the specified location"""
hdulist = pyfits.open(filepath)
hdulist.verify('silentfix')
fits_comment = hdulist[0].header.get_comment()
# PyFITS 2.x
if isinstance(fits_comment[0], basestring):
comments = [val for val in fits_comment]
else:
# PyFITS 3.x
comments = [card.value for card in fits_comment]
comment = "".join(comments).strip()
header = MapHeader(hdulist[0].header)
header['comment'] = comment
return hdulist[0].data, header
def get_header(filepath):
"""Returns the header for a given file"""
hdulist = pyfits.open(filepath)
hdulist.verify('silentfix')
comment = "".join(hdulist[0].header.get_comment()).strip()
header = MapHeader(hdulist[0].header)
header['comment'] = comment
return header
| bsd-2-clause | Python |
ff3ea3b00bc7819abd6adac92ddb574b547f9ba3 | remove PyJWT deprecation warning by adding algorithms (#8267) | conan-io/conan,conan-io/conan,conan-io/conan | conans/server/crypto/jwt/jwt_manager.py | conans/server/crypto/jwt/jwt_manager.py | from datetime import datetime
import jwt
class JWTManager(object):
"""
Handles the JWT token generation and encryption.
"""
def __init__(self, secret, expire_time):
"""expire_time is a timedelta
secret is a string with the secret encoding key"""
self.secret = secret
self.expire_time = expire_time
def get_token_for(self, profile_fields=None):
"""Generates a token with the provided fields.
if exp is True, expiration time will be used"""
profile_fields = profile_fields or {}
if self.expire_time:
profile_fields["exp"] = datetime.utcnow() + self.expire_time
return jwt.encode(profile_fields, self.secret, algorithm="HS256")
def get_profile(self, token):
"""Gets the user from credentials object. None if no credentials.
Can raise jwt.ExpiredSignature and jwt.DecodeError"""
profile = jwt.decode(token, self.secret, algorithms=["HS256"])
return profile
| from datetime import datetime
import jwt
class JWTManager(object):
"""
Handles the JWT token generation and encryption.
"""
def __init__(self, secret, expire_time):
"""expire_time is a timedelta
secret is a string with the secret encoding key"""
self.secret = secret
self.expire_time = expire_time
def get_token_for(self, profile_fields=None):
"""Generates a token with the provided fields.
if exp is True, expiration time will be used"""
profile_fields = profile_fields or {}
if self.expire_time:
profile_fields["exp"] = datetime.utcnow() + self.expire_time
return jwt.encode(profile_fields, self.secret)
def get_profile(self, token):
"""Gets the user from credentials object. None if no credentials.
Can raise jwt.ExpiredSignature and jwt.DecodeError"""
profile = jwt.decode(token, self.secret)
return profile
| mit | Python |
326a0a1af140e3a57ccf31c3c9c5e17a5775c13d | Bump to v0.5.2 | onecodex/onecodex,refgenomics/onecodex,refgenomics/onecodex,onecodex/onecodex | onecodex/version.py | onecodex/version.py | __version__ = "0.5.2"
| __version__ = "0.5.1"
| mit | Python |
4c3d5c357f39699b82ed609fbcc0f62d59a00093 | bump version in __init__.py | WillianPaiva/1flow,WillianPaiva/1flow,1flow/1flow,WillianPaiva/1flow,1flow/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,1flow/1flow,1flow/1flow | oneflow/__init__.py | oneflow/__init__.py |
VERSION = '0.20.5.1'
|
VERSION = '0.20.5'
| agpl-3.0 | Python |
5ae32d659b7eacc52b91b53e8f8809814e9478aa | allow users to configure check layout | ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo | addons/account_check_printing/models/res_config_settings.py | addons/account_check_printing/models/res_config_settings.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
country_code = fields.Char(string="Company Country code", related='company_id.country_id.code', readonly=True)
account_check_printing_layout = fields.Selection(related='company_id.account_check_printing_layout', string="Check Layout", readonly=False,
help="Select the format corresponding to the check paper you will be printing your checks on.\n"
"In order to disable the printing feature, select 'None'.")
account_check_printing_date_label = fields.Boolean(related='company_id.account_check_printing_date_label', string="Print Date Label", readonly=False,
help="This option allows you to print the date label on the check as per CPA. Disable this if your pre-printed check includes the date label.")
account_check_printing_multi_stub = fields.Boolean(related='company_id.account_check_printing_multi_stub', string='Multi-Pages Check Stub', readonly=False,
help="This option allows you to print check details (stub) on multiple pages if they don't fit on a single page.")
account_check_printing_margin_top = fields.Float(related='company_id.account_check_printing_margin_top', string='Check Top Margin', readonly=False,
help="Adjust the margins of generated checks to make it fit your printer's settings.")
account_check_printing_margin_left = fields.Float(related='company_id.account_check_printing_margin_left', string='Check Left Margin', readonly=False,
help="Adjust the margins of generated checks to make it fit your printer's settings.")
account_check_printing_margin_right = fields.Float(related='company_id.account_check_printing_margin_right', string='Check Right Margin', readonly=False,
help="Adjust the margins of generated checks to make it fit your printer's settings.")
| # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
country_code = fields.Char(string="Company Country code", related='company_id.country_id.code', readonly=True)
account_check_printing_layout = fields.Selection(related='company_id.account_check_printing_layout', string="Check Layout",
help="Select the format corresponding to the check paper you will be printing your checks on.\n"
"In order to disable the printing feature, select 'None'.")
account_check_printing_date_label = fields.Boolean(related='company_id.account_check_printing_date_label', string="Print Date Label", readonly=False,
help="This option allows you to print the date label on the check as per CPA. Disable this if your pre-printed check includes the date label.")
account_check_printing_multi_stub = fields.Boolean(related='company_id.account_check_printing_multi_stub', string='Multi-Pages Check Stub', readonly=False,
help="This option allows you to print check details (stub) on multiple pages if they don't fit on a single page.")
account_check_printing_margin_top = fields.Float(related='company_id.account_check_printing_margin_top', string='Check Top Margin', readonly=False,
help="Adjust the margins of generated checks to make it fit your printer's settings.")
account_check_printing_margin_left = fields.Float(related='company_id.account_check_printing_margin_left', string='Check Left Margin', readonly=False,
help="Adjust the margins of generated checks to make it fit your printer's settings.")
account_check_printing_margin_right = fields.Float(related='company_id.account_check_printing_margin_right', string='Check Right Margin', readonly=False,
help="Adjust the margins of generated checks to make it fit your printer's settings.")
| agpl-3.0 | Python |
d31d2a73127a79566651e644d105cbe2063a6e2a | Fix for the new cloudly APi. | hdemers/webapp-template,hdemers/webapp-template,hdemers/webapp-template | webapp/publish.py | webapp/publish.py | from cloudly.pubsub import Pusher
from cloudly.tweets import Tweets, StreamManager, keep
from webapp import config
pubsub = Pusher.open(config.pubsub_channel)
def processor(tweets):
pubsub.publish(keep(['coordinates'], tweets), "tweets")
return len(tweets)
def start():
streamer = StreamManager('locate', processor, is_queuing=False)
tweets = Tweets()
streamer.run(tweets.with_coordinates())
if __name__ == "__main__":
start()
| from cloudly.pubsub import Pusher
from cloudly.tweets import Tweets
from cloudly.twitterstream import Streamer
from webapp import config
class Publisher(Pusher):
def publish(self, tweets, event):
"""Keep only relevant fields from the given tweets."""
stripped = []
for tweet in tweets:
stripped.append({
'coordinates': tweet['coordinates'],
})
super(Publisher, self).publish(stripped, event)
def processor(tweet):
return True
def start():
# This trick of importing the current module is for RQ workers to
# correctly unpickle the `processor` function.
from webapp import publish
pubsub = publish.Publisher.open(config.pubsub_channel)
streamer = Streamer(publish.processor, pubsub=pubsub, is_queuing=True,
cache_length=100)
tweets = Tweets()
streamer.run(tweets.with_coordinates())
if __name__ == "__main__":
start()
| mit | Python |
0370e765f635edf670508ee09be9bd9139967543 | Upgrade to v0.2.28 | biolink/ontobio,biolink/ontobio | ontobio/__init__.py | ontobio/__init__.py | from __future__ import absolute_import
__version__ = '0.2.28'
from .ontol_factory import OntologyFactory
from .ontol import Ontology, Synonym, TextDefinition
from .assoc_factory import AssociationSetFactory
from .io.ontol_renderers import GraphRenderer
| from __future__ import absolute_import
__version__ = '0.2.27'
from .ontol_factory import OntologyFactory
from .ontol import Ontology, Synonym, TextDefinition
from .assoc_factory import AssociationSetFactory
from .io.ontol_renderers import GraphRenderer
| bsd-3-clause | Python |
4ed1e969082046d7e92c5f311820c518930976c5 | add some doc strings | openaps/openaps,openaps/openaps | openaps/uses/use.py | openaps/uses/use.py |
"""
use - module for openaps devices to re-use
"""
from openaps.cli.subcommand import Subcommand
class Use (Subcommand):
"""A no-op base use.
A Use is a mini well-behaved linux application.
openaps framework will initialize your Use with a `method` and
`parent` objects, which are contextual objects within openaps.
"""
def __init__ (self, method=None, parent=None):
self.method = method
self.name = self.__class__.__name__.split('.').pop( )
self.parent = parent
self.device = parent.device
def main (self, args, app):
"""
Put main app logic here.
print "HAHA", args, app
"""
def get_params (self, args):
"""
Return dictionary of all parameters collected from args.
"""
return dict( )
def before_main (self, args, app):
pass
def after_main (self, args, app):
pass
def __call__ (self, args, app):
"""
openaps will use this to interface with your app.
"""
self.before_main(args, app)
output = self.main(args, app)
self.after_main(args, app)
return output
|
from openaps.cli.subcommand import Subcommand
class Use (Subcommand):
"""A no-op base use."""
pass
def __init__ (self, method=None, parent=None):
self.method = method
self.name = self.__class__.__name__.split('.').pop( )
self.parent = parent
self.device = parent.device
def main (self, args, app):
"""
Put main app logic here.
print "HAHA", args, app
"""
def get_params (self, args):
return dict( )
def before_main (self, args, app):
pass
def after_main (self, args, app):
pass
def __call__ (self, args, app):
self.before_main(args, app)
output = self.main(args, app)
self.after_main(args, app)
return output
| mit | Python |
74e24981c31445a16734d921ef4781dab8070d3a | Add static paths | westerncapelabs/uopbmoh-hub,westerncapelabs/uopboh-hub,westerncapelabs/uopbmoh-hub,westerncapelabs/uopbmoh-hub | uopbmoh_hub/urls.py | uopbmoh_hub/urls.py | import os
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
admin.site.site_header = os.environ.get('UOPBMOH_HUB_TITLE', 'UoPBMoH Admin')
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('hub.urls')),
)
urlpatterns += staticfiles_urlpatterns()
| import os
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.site.site_header = os.environ.get('UOPBMOH_HUB_TITLE', 'UoPBMoH Admin')
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('hub.urls')),
)
| bsd-3-clause | Python |
9de6956c6732d403916bf33702c16d75b5be1cff | add iterator to the log output on port-creation | CiscoSystems/os-sqe,CiscoSystems/os-sqe,CiscoSystems/os-sqe | lab/scenarios/net_subnet_port.py | lab/scenarios/net_subnet_port.py | def once(command, log):
net_id = command('neutron net-create')
command('neutron subnet-create {net_id} 10.0.100.0/24'.format(net_id=net_id))
command('neutron port-create {net_id}'.format(net_id=net_id))
def start(lab, log, args):
import time
import re
how_many = args['how_many']
unique_pattern_in_name = args.get('unique_pattern_in_name', 'sqe-test')
server = lab.controllers()[0]
def command(cmd):
name_part = '{0}-{1}'.format(unique_pattern_in_name, i)
if 'subnet-create' in cmd: # subnet-create needs to be before net-create since net-create is a substring of subnet-create
name_part = '--name ' + name_part + '-subnet'
elif 'net-create' in cmd:
name_part += '-net'
elif 'port-create' in cmd:
name_part = '--name ' + name_part + '-port'
res = server.run(command='{cmd} {name_part} {lab_creds}'.format(cmd=cmd, name_part=name_part, lab_creds=lab.cloud))
if res:
return re.search('id\s+\|\s+([-\w]+)', ''.join(res.stdout)).group(1)
start_time = time.time()
for i in xrange(0, how_many):
once(command=command, log=log)
log.info('{0} net-subnet-port created'.format(i+1))
log.info('{0} net-subnet-ports created in {1} secs'.format(how_many, time.time()-start_time))
| def once(command, log):
net_id = command('neutron net-create')
command('neutron subnet-create {net_id} 10.0.100.0/24'.format(net_id=net_id))
command('neutron port-create {net_id}'.format(net_id=net_id))
log.info('net-subnet-port created')
def start(lab, log, args):
import time
import re
how_many = args['how_many']
unique_pattern_in_name = args.get('unique_pattern_in_name', 'sqe-test')
server = lab.controllers()[0]
def command(cmd):
name_part = '{0}-{1}'.format(unique_pattern_in_name, i)
if 'subnet-create' in cmd: # subnet-create needs to be before net-create since net-create is a substring of subnet-create
name_part = '--name ' + name_part + '-subnet'
elif 'net-create' in cmd:
name_part += '-net'
elif 'port-create' in cmd:
name_part = '--name ' + name_part + '-port'
res = server.run(command='{cmd} {name_part} {lab_creds}'.format(cmd=cmd, name_part=name_part, lab_creds=lab.cloud))
if res:
return re.search('id\s+\|\s+([-\w]+)', ''.join(res.stdout)).group(1)
start_time = time.time()
for i in xrange(0, how_many):
once(command=command, log=log)
log.info('{0} net-subnet-ports created in {1} secs'.format(how_many, time.time()-start_time))
| apache-2.0 | Python |
4a7b548511fa0651aa0bc526302d13947941dacc | Return status code 200 when Device instance already exists | willandskill/django-parse-push | parse_push/views.py | parse_push/views.py | from django.db import IntegrityError
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import DeviceSerializer
class DeviceTokenSetter(APIView):
"""
Set a push token related to device for logged in User
"""
permission_classes = (IsAuthenticated, )
def post(self, request, format=None):
serializer = DeviceSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
try:
serializer.save(user=request.user)
return Response(status=status.HTTP_201_CREATED)
except IntegrityError:
return Response('Device instance already exists.', status=status.HTTP_200_OK)
| from django.db import IntegrityError
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import DeviceSerializer
class DeviceTokenSetter(APIView):
"""
Set a push token related to device for logged in User
"""
permission_classes = (IsAuthenticated, )
def post(self, request, format=None):
serializer = DeviceSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
try:
serializer.save(user=request.user)
return Response(status=status.HTTP_201_CREATED)
except IntegrityError:
return Response('Device instance already exists.', status=status.HTTP_409_CONFLICT)
| bsd-3-clause | Python |
8d28f866109223abedf6cac88c44234061bcd7f5 | Fix missing PLC pips | gatecat/prjoxide,gatecat/prjoxide,gatecat/prjoxide | fuzzers/LIFCL/001-plc-routing/fuzzer.py | fuzzers/LIFCL/001-plc-routing/fuzzer.py | from fuzzconfig import FuzzConfig
from interconnect import fuzz_interconnect
import re
cfg = FuzzConfig(job="PLCROUTE", device="LIFCL-40", sv="../shared/route_40.v", tiles=["R16C22:PLC"])
def main():
cfg.setup()
r = 16
c = 22
nodes = ["R{}C{}_J*".format(r, c)]
extra_sources = []
extra_sources += ["R{}C{}_H02E{:02}01".format(r, c+1, i) for i in range(8)]
extra_sources += ["R{}C{}_H06E{:02}03".format(r, c+3, i) for i in range(4)]
extra_sources += ["R{}C{}_V02N{:02}01".format(r-1, c, i) for i in range(8)]
extra_sources += ["R{}C{}_V06N{:02}03".format(r-3, c, i) for i in range(4)]
extra_sources += ["R{}C{}_V02S{:02}01".format(r+1, c, i) for i in range(8)]
extra_sources += ["R{}C{}_V06S{:02}03".format(r+3, c, i) for i in range(4)]
extra_sources += ["R{}C{}_H02W{:02}01".format(r, c-1, i) for i in range(8)]
extra_sources += ["R{}C{}_H06W{:02}03".format(r, c-3, i) for i in range(4)]
fuzz_interconnect(config=cfg, nodenames=nodes, regex=True, bidir=True, ignore_tiles=set(["TAP_PLC_R16C14:TAP_PLC"]))
fuzz_interconnect(config=cfg, nodenames=extra_sources, regex=False, bidir=False, ignore_tiles=set(["TAP_PLC_R16C14:TAP_PLC"]))
if __name__ == "__main__":
main()
| from fuzzconfig import FuzzConfig
from interconnect import fuzz_interconnect
import re
cfg = FuzzConfig(job="PLCROUTE", device="LIFCL-40", sv="../shared/route_40.v", tiles=["R16C22:PLC"])
def main():
cfg.setup()
r = 16
c = 22
nodes = ["R{}C{}_J*".format(r, c)]
fuzz_interconnect(config=cfg, nodenames=nodes, regex=True, bidir=True)
if __name__ == "__main__":
main()
| isc | Python |
5415fff9e51e02512d2d5e42ce22824670c83024 | Change writelines approach | ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools | cronjobs/fetch_interlibraryloan_ppns.py | cronjobs/fetch_interlibraryloan_ppns.py | #!/bin/python2
# -*- coding: utf-8 -*-
import datetime
import json
import os
import re
import sys
import time
import traceback
import urllib
import util
GVI_URL = 'http://gvi.bsz-bw.de/solr/GVI/select?rows=50000&wt=json&indent=true&fl=id&q=material_media_type:Book+AND+(ill_flag:Loan+OR+ill_flag:Copy+OR+ill_flag:Ecopy)+AND+publish_date:[2000+TO+*]&sort=id+asc&fq=id:\(DE-627\)*'
DROP_SIGIL_REGEX = '[(][A-Z]{2}-\d\d\d[)]'
PPN_LIST_FILE = "gvi_ppn_list-" + datetime.datetime.today().strftime('%y%m%d') + ".txt"
def GetDataFromGVI(cursor_mark):
response = urllib.urlopen(GVI_URL + '&cursorMark=' + cursor_mark)
try:
jdata = json.load(response)
except ValueError:
util.Error("GVI did not return valid JSON!")
return jdata
def ExtractPPNs(jdata, ppns):
drop_pattern = re.compile(DROP_SIGIL_REGEX)
for doc in jdata['response']['docs']:
if doc.get('id') is not None:
sigil_and_ppn = doc.get('id')
ppn = drop_pattern.sub("", sigil_and_ppn)
ppns.append(ppn)
return ppns
def WriteListFile(ppn_list):
with open(PPN_LIST_FILE, 'w') as file:
file.writelines(str(ppn) + '\n' for ppn in ppn_list)
def ExtractNextCursorMark(jdata):
return urllib.quote(jdata['nextCursorMark'])
def Main():
if len(sys.argv) != 2:
util.SendEmail(os.path.basename(sys.argv[0]),
"This script needs to be called with an email address as the only argument!\n", priority=1)
ppns = []
currentCursorMark = '*'
while True:
jdata = GetDataFromGVI(currentCursorMark)
ppns = ExtractPPNs(jdata, ppns)
newCursorMark = ExtractNextCursorMark(jdata)
if currentCursorMark == newCursorMark:
break
currentCursorMark = newCursorMark
WriteListFile(ppns)
try:
Main()
except Exception as e:
error_msg = "An unexpected error occured: " + str(e) + "\n\n" + traceback.format_exc(20)
util.Error(error_msg)
| #!/bin/python2
# -*- coding: utf-8 -*-
import datetime
import json
import os
import re
import sys
import time
import traceback
import urllib
import util
GVI_URL = 'http://gvi.bsz-bw.de/solr/GVI/select?rows=50000&wt=json&indent=true&fl=id&q=material_media_type:Book+AND+(ill_flag:Loan+OR+ill_flag:Copy+OR+ill_flag:Ecopy)+AND+publish_date:[2000+TO+*]&sort=id+asc&fq=id:\(DE-627\)*'
DROP_SIGIL_REGEX = '[(][A-Z]{2}-\d\d\d[)]'
PPN_LIST_FILE = "gvi_ppn_list-" + datetime.datetime.today().strftime('%y%m%d') + ".txt"
def GetDataFromGVI(cursor_mark):
response = urllib.urlopen(GVI_URL + '&cursorMark=' + cursor_mark)
try:
jdata = json.load(response)
except ValueError:
util.Error("GVI did not return valid JSON!")
return jdata
def ExtractPPNs(jdata, ppns):
drop_pattern = re.compile(DROP_SIGIL_REGEX)
for doc in jdata['response']['docs']:
if doc.get('id') is not None:
sigil_and_ppn = doc.get('id')
ppn = drop_pattern.sub("", sigil_and_ppn)
ppns.append(ppn)
return ppns
def WriteListFile(ppn_list):
with open(PPN_LIST_FILE, 'w') as file:
file.writelines("%s\n" % ppn for ppn in ppn_list)
def ExtractNextCursorMark(jdata):
return urllib.quote(jdata['nextCursorMark'])
def Main():
if len(sys.argv) != 2:
util.SendEmail(os.path.basename(sys.argv[0]),
"This script needs to be called with an email address as the only argument!\n", priority=1)
ppns = []
currentCursorMark = '*'
while True:
jdata = GetDataFromGVI(currentCursorMark)
ppns = ExtractPPNs(jdata, ppns)
newCursorMark = ExtractNextCursorMark(jdata)
if currentCursorMark == newCursorMark:
break
currentCursorMark = newCursorMark
WriteListFile(ppns)
try:
Main()
except Exception as e:
error_msg = "An unexpected error occured: " + str(e) + "\n\n" + traceback.format_exc(20)
util.Error(error_msg)
| agpl-3.0 | Python |
c42acd3e6d8e9371be84b9f94aa6c151b80ff123 | update to the app launcher locator for summer '19 | SalesforceFoundation/CumulusCI,SalesforceFoundation/CumulusCI | cumulusci/robotframework/locators_46.py | cumulusci/robotframework/locators_46.py | from cumulusci.robotframework import locators_45
lex_locators = locators_45.lex_locators.copy()
# oof. This is gnarly.
# Apparently, in 45 all modal buttons are in a class named 'modal-footer'
# but in 46 some are in a class named 'actionsContainer' instead.
lex_locators["modal"]["button"] = "{}{}{}".format(
"//div[contains(@class,'uiModal')]",
"//div[contains(@class,'modal-footer') or contains(@class, 'actionsContainer')]",
"//button[.//span[text()='{}']]",
)
# the app launcher links have changed a bit too...
lex_locators["app_launcher"][
"app_link"
] = "//div[@class='slds-card salesforceIdentityAppLauncherDesktopInternal']//section[@id='cards']//a[@class='appTileTitle' and text()='{}']"
| from cumulusci.robotframework import locators_45
lex_locators = locators_45.lex_locators.copy()
# oof. This is gnarly.
# Apparently, in 45 all modal buttons are in a class named 'modal-footer'
# but in 46 some are in a class named 'actionsContainer' instead.
lex_locators["modal"]["button"] = "{}{}{}".format(
"//div[contains(@class,'uiModal')]",
"//div[contains(@class,'modal-footer') or contains(@class, 'actionsContainer')]",
"//button[.//span[text()='{}']]",
)
| bsd-3-clause | Python |
f18dd0a73738db0e20a2f3c0e81151d4383ea860 | Bump to 0.8.4 | alexmojaki/birdseye,alexmojaki/birdseye,alexmojaki/birdseye,alexmojaki/birdseye | birdseye/__init__.py | birdseye/__init__.py | import sys
from importlib import import_module
__version__ = '0.8.4'
# birdseye has so many dependencies that simply importing them can be quite slow
# Sometimes you just want to leave an import sitting around without actually using it
# These proxies ensure that if you do, program startup won't be slowed down
# In a nutshell:
# from birdseye import eye
# is a lazy version of
# from birdseye.bird import eye
class _SimpleProxy(object):
def __init__(self, val):
object.__setattr__(self, '_SimpleProxy__val', val)
def __call__(self, *args, **kwargs):
return self.__val()(*args, **kwargs)
def __getattr__(self, item):
return getattr(self.__val(), item)
def __setattr__(self, key, value):
setattr(self.__val(), key, value)
eye = _SimpleProxy(lambda: import_module('birdseye.bird').eye)
BirdsEye = _SimpleProxy(lambda: import_module('birdseye.bird').BirdsEye)
def load_ipython_extension(ipython_shell):
from birdseye.ipython import BirdsEyeMagics
ipython_shell.register_magics(BirdsEyeMagics)
if sys.version_info.major == 3:
from birdseye.import_hook import BirdsEyeFinder
sys.meta_path.insert(0, BirdsEyeFinder())
| import sys
from importlib import import_module
__version__ = '0.8.3'
# birdseye has so many dependencies that simply importing them can be quite slow
# Sometimes you just want to leave an import sitting around without actually using it
# These proxies ensure that if you do, program startup won't be slowed down
# In a nutshell:
# from birdseye import eye
# is a lazy version of
# from birdseye.bird import eye
class _SimpleProxy(object):
def __init__(self, val):
object.__setattr__(self, '_SimpleProxy__val', val)
def __call__(self, *args, **kwargs):
return self.__val()(*args, **kwargs)
def __getattr__(self, item):
return getattr(self.__val(), item)
def __setattr__(self, key, value):
setattr(self.__val(), key, value)
eye = _SimpleProxy(lambda: import_module('birdseye.bird').eye)
BirdsEye = _SimpleProxy(lambda: import_module('birdseye.bird').BirdsEye)
def load_ipython_extension(ipython_shell):
from birdseye.ipython import BirdsEyeMagics
ipython_shell.register_magics(BirdsEyeMagics)
if sys.version_info.major == 3:
from birdseye.import_hook import BirdsEyeFinder
sys.meta_path.insert(0, BirdsEyeFinder())
| mit | Python |
53883178d786173d227d5e6062ab5b03fa087068 | Change version to 1.9.3.2 | Elec/django-bitfield | bitfield/__init__.py | bitfield/__init__.py | """
django-bitfield
~~~~~~~~~~~~~~~
"""
from __future__ import absolute_import
from bitfield.models import Bit, BitHandler, CompositeBitField, BitField # NOQA
default_app_config = 'bitfield.apps.BitFieldAppConfig'
VERSION = '1.9.3.2'
| """
django-bitfield
~~~~~~~~~~~~~~~
"""
from __future__ import absolute_import
from bitfield.models import Bit, BitHandler, CompositeBitField, BitField # NOQA
default_app_config = 'bitfield.apps.BitFieldAppConfig'
VERSION = '1.9.3'
| apache-2.0 | Python |
bfd516db001ef5a208be2d1c60764587d2609d1a | Add status column to order payment administration | armicron/plata,armicron/plata,armicron/plata,stefanklug/plata,allink/plata | plata/shop/admin.py | plata/shop/admin.py | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from . import models
class OrderItemInline(admin.TabularInline):
model = models.OrderItem
raw_id_fields = ('variation',)
class AppliedDiscountInline(admin.TabularInline):
model = models.AppliedDiscount
class OrderStatusInline(admin.TabularInline):
model = models.OrderStatus
extra = 1
admin.site.register(models.Order,
date_hierarchy='created',
fieldsets=(
(None, {'fields': ('created', 'confirmed', 'contact', 'status')}),
(_('Billing address'), {'fields': ('billing_company', 'billing_first_name',
'billing_last_name', 'billing_address', 'billing_zip_code',
'billing_city', 'billing_country')}),
(_('Shipping address'), {'fields': ('shipping_company', 'shipping_first_name',
'shipping_last_name', 'shipping_address', 'shipping_zip_code',
'shipping_city', 'shipping_country')}),
(_('Order items'), {'fields': ('items_subtotal', 'items_discount', 'items_tax')}),
(_('Shipping'), {'fields': ('shipping_cost', 'shipping_discount', 'shipping_tax')}),
(_('Total'), {'fields': ('currency', 'total', 'paid')}),
(_('Additional fields'), {'fields': ('notes',)}),
),
inlines=[OrderItemInline, AppliedDiscountInline, OrderStatusInline],
list_display=('__unicode__', 'created', 'contact', 'status', 'total', 'balance_remaining', 'is_paid'),
list_filter=('status',),
raw_id_fields=('contact',),
search_fields=tuple('billing_%s' % s for s in models.Order.ADDRESS_FIELDS)\
+tuple('shipping_%s' % s for s in models.Order.ADDRESS_FIELDS)\
+('total', 'notes'),
)
class OrderPaymentAdmin(admin.ModelAdmin):
date_hierarchy = 'timestamp'
list_display = ('order', 'timestamp', 'currency', 'amount', 'status', 'authorized',
'payment_module', 'payment_method', 'notes_short')
list_display_links = ('timestamp',)
list_filter = ('status',)
raw_id_fields = ('order',)
search_fields = ('amount', 'payment_module', 'payment_method', 'transaction_id',
'notes', 'data')
notes_short = lambda self, obj: (len(obj.notes) > 50) and obj.notes[:40]+'...' or obj.notes
notes_short.short_description = _('notes')
admin.site.register(models.OrderPayment, OrderPaymentAdmin)
| from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from . import models
class OrderItemInline(admin.TabularInline):
model = models.OrderItem
raw_id_fields = ('variation',)
class AppliedDiscountInline(admin.TabularInline):
model = models.AppliedDiscount
class OrderStatusInline(admin.TabularInline):
model = models.OrderStatus
extra = 1
admin.site.register(models.Order,
date_hierarchy='created',
fieldsets=(
(None, {'fields': ('created', 'confirmed', 'contact', 'status')}),
(_('Billing address'), {'fields': ('billing_company', 'billing_first_name',
'billing_last_name', 'billing_address', 'billing_zip_code',
'billing_city', 'billing_country')}),
(_('Shipping address'), {'fields': ('shipping_company', 'shipping_first_name',
'shipping_last_name', 'shipping_address', 'shipping_zip_code',
'shipping_city', 'shipping_country')}),
(_('Order items'), {'fields': ('items_subtotal', 'items_discount', 'items_tax')}),
(_('Shipping'), {'fields': ('shipping_cost', 'shipping_discount', 'shipping_tax')}),
(_('Total'), {'fields': ('currency', 'total', 'paid')}),
(_('Additional fields'), {'fields': ('notes',)}),
),
inlines=[OrderItemInline, AppliedDiscountInline, OrderStatusInline],
list_display=('__unicode__', 'created', 'contact', 'status', 'total', 'balance_remaining', 'is_paid'),
list_filter=('status',),
raw_id_fields=('contact',),
search_fields=tuple('billing_%s' % s for s in models.Order.ADDRESS_FIELDS)\
+tuple('shipping_%s' % s for s in models.Order.ADDRESS_FIELDS)\
+('total', 'notes'),
)
class OrderPaymentAdmin(admin.ModelAdmin):
date_hierarchy = 'timestamp'
list_display = ('order', 'timestamp', 'currency', 'amount', 'authorized',
'payment_module', 'payment_method', 'notes_short')
list_display_links = ('timestamp',)
list_filter = ('authorized',)
raw_id_fields = ('order',)
search_fields = ('amount', 'payment_module', 'payment_method', 'transaction_id',
'notes', 'data')
notes_short = lambda self, obj: (len(obj.notes) > 50) and obj.notes[:40]+'...' or obj.notes
notes_short.short_description = _('notes')
admin.site.register(models.OrderPayment, OrderPaymentAdmin)
| bsd-3-clause | Python |
f683291c406d9ad9e1a331f4e01ade335d78193e | Set the DJANGO_HOSTNAME in the wsgi file based on the servername options | mark0978/deployment | deployment/templates/deployment/wsgi.py | deployment/templates/deployment/wsgi.py | import os, sys
sys.path = [
{% for part in sys.path %} "{{ part }}",
{% endfor %}
]
from django.core.handlers.wsgi import WSGIHandler
#import pinax.env
#setup the environment for Django and Pinax
#pinax.env.setup_environ(__file__, settings_path=os.path.abspath(os.path.join()
{% if options.servername %}
os.environ["DJANGO_HOSTNAME"] = {{ options.servername }}.split('.')[0]
{% endif %}
os.environ["DJANGO_SETTINGS_MODULE"] = '{{ settings.SETTINGS_MODULE }}'
# set application for WSGI processing
application = WSGIHandler()
| import os, sys
sys.path = [
{% for part in sys.path %} "{{ part }}",
{% endfor %}
]
from django.core.handlers.wsgi import WSGIHandler
#import pinax.env
#setup the environment for Django and Pinax
#pinax.env.setup_environ(__file__, settings_path=os.path.abspath(os.path.join()
os.environ["DJANGO_SETTINGS_MODULE"] = '{{ settings.SETTINGS_MODULE }}'
# set application for WSGI processing
application = WSGIHandler()
| mit | Python |
77d4651231e6980ccc0b96109fc8033d277f5752 | Update Place Model | folse/MTS,folse/MTS,folse/MTS | Management/models.py | Management/models.py | from django.db import models
class Place(models.Model):
name = models.CharField(max_length=64)
photo = models.CharField(max_length=512)
latitude = models.FloatField(max_length=32)
longitude = models.FloatField(max_length=32)
phone = models.CharField(max_length=32)
open_hour = models.CharField(max_length=128)
category = models.CharField(max_length=512)
news = models.TextField(max_length=512)
description = models.TextField(max_length=512)
| from django.db import models
class Place(models.Model):
name = models.CharField(max_length=64)
photo = models.CharField(max_length=512)
latitude = models.FloatField(max_length=32)
longitude = models.FloatField(max_length=32)
phone = models.CharField(max_length=32)
news = models.CharField(max_length=512)
open_hours = models.CharField(max_length=128)
| mit | Python |
c1f5b9e3bfa96762fdbe9f4ca54b3851b38294da | Add versioned path for dynamic library lookup | badboy/hiredis-py-win,charsyam/hiredis-py,badboy/hiredis-py-win,redis/hiredis-py,charsyam/hiredis-py,badboy/hiredis-py-win,redis/hiredis-py | test/__init__.py | test/__init__.py | import glob, os.path, sys
version = sys.version.split(" ")[0]
majorminor = version[0:3]
# Add path to hiredis.so load path
path = glob.glob("build/lib*-%s/hiredis/*.so" % majorminor)[0]
sys.path.insert(0, os.path.dirname(path))
from unittest import *
from . import reader
def tests():
suite = TestSuite()
suite.addTest(makeSuite(reader.ReaderTest))
return suite
| import glob, os.path, sys
# Add path to hiredis.so load path
path = glob.glob("build/lib*/hiredis/*.so")[0]
sys.path.insert(0, os.path.dirname(path))
from unittest import *
from . import reader
def tests():
suite = TestSuite()
suite.addTest(makeSuite(reader.ReaderTest))
return suite
| bsd-3-clause | Python |
9e80b368b01cb11a7ac0d97143ea69aa6dd2eef0 | fix skipping tests on OSX | gardner/urllib3,silveringsea/urllib3,Disassem/urllib3,luca3m/urllib3,Geoion/urllib3,asmeurer/urllib3,mikelambert/urllib3,tutumcloud/urllib3,sigmavirus24/urllib3,matejcik/urllib3,boyxuper/urllib3,tutumcloud/urllib3,denim2x/urllib3,asmeurer/urllib3,matejcik/urllib3,Disassem/urllib3,sornars/urllib3,gardner/urllib3,sileht/urllib3,msabramo/urllib3,luca3m/urllib3,haikuginger/urllib3,Geoion/urllib3,urllib3/urllib3,silveringsea/urllib3,denim2x/urllib3,sornars/urllib3,sileht/urllib3,urllib3/urllib3,sigmavirus24/urllib3,boyxuper/urllib3,Lukasa/urllib3,msabramo/urllib3,mikelambert/urllib3,haikuginger/urllib3,Lukasa/urllib3 | test/__init__.py | test/__init__.py | import errno
import functools
import socket
from nose.plugins.skip import SkipTest
from urllib3.exceptions import MaxRetryError
from urllib3.packages import six
def onlyPY3(test):
"""Skips this test unless you are on Python3.x"""
@functools.wraps(test)
def wrapper(*args, **kwargs):
msg = "{name} requires Python3.x to run".format(name=test.__name__)
if not six.PY3:
raise SkipTest(msg)
return test(*args, **kwargs)
def requires_network(test):
"""Helps you skip tests that require the network"""
def _is_unreachable_err(err):
return getattr(err, 'errno', None) in (errno.ENETUNREACH,
errno.EHOSTUNREACH) # For OSX
@functools.wraps(test)
def wrapper(*args, **kwargs):
msg = "Can't run {name} because the network is unreachable".format(
name=test.__name__)
try:
return test(*args, **kwargs)
except socket.error as e:
# This test needs an initial network connection to attempt the
# connection to the TARPIT_HOST. This fails if you are in a place
# without an Internet connection, so we skip the test in that case.
if _is_unreachable_err(e):
raise SkipTest(msg)
raise
except MaxRetryError as e:
if (isinstance(e.reason, socket.error) and
_is_unreachable_err(e.reason)):
raise SkipTest(msg)
raise
return wrapper
| import errno
import functools
import socket
from nose.plugins.skip import SkipTest
from urllib3.exceptions import MaxRetryError
from urllib3.packages import six
def onlyPY3(test):
"""Skips this test unless you are on Python3.x"""
@functools.wraps(test)
def wrapper(*args, **kwargs):
msg = "{name} requires Python3.x to run".format(name=test.__name__)
if not six.PY3:
raise SkipTest(msg)
return test(*args, **kwargs)
def requires_network(test):
"""Helps you skip tests that require the network"""
def _is_unreachable_err(err):
return hasattr(err, 'errno') and err.errno == errno.ENETUNREACH
@functools.wraps(test)
def wrapper(*args, **kwargs):
msg = "Can't run {name} because the network is unreachable".format(
name=test.__name__)
try:
return test(*args, **kwargs)
except socket.error as e:
# This test needs an initial network connection to attempt the
# connection to the TARPIT_HOST. This fails if you are in a place
# without an Internet connection, so we skip the test in that case.
if _is_unreachable_err(e):
raise SkipTest(msg)
raise
except MaxRetryError as e:
if (isinstance(e.reason, socket.error) and
_is_unreachable_err(e.reason)):
raise SkipTest(msg)
raise
return wrapper
| mit | Python |
4a854b68588cbc943fdf0145daa3552587894202 | fix import for CentOS | cdr-stats/cdr-stats,Star2Billing/cdr-stats,areski/cdr-stats,cdr-stats/cdr-stats,Star2Billing/cdr-stats,areski/cdr-stats,Star2Billing/cdr-stats,cdr-stats/cdr-stats,areski/cdr-stats,cdr-stats/cdr-stats,Star2Billing/cdr-stats,areski/cdr-stats | cdr_stats/cdr/admin.py | cdr_stats/cdr/admin.py | from cdr.models import *
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django.db.models import Q
from cdr.models import Customer, Staff
class UserProfileInline(admin.StackedInline):
model = UserProfile
class StaffAdmin(UserAdmin):
inlines = [UserProfileInline]
list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'is_active', 'is_superuser', 'last_login')
def queryset(self, request):
qs = super(UserAdmin, self).queryset(request)
qs = qs.filter(Q(is_staff=True) | Q(is_superuser=True))
return qs
class CustomerAdmin(StaffAdmin):
inlines = [UserProfileInline]
list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'is_active', 'is_superuser', 'last_login')
def queryset(self, request):
qs = super(UserAdmin, self).queryset(request)
qs = qs.exclude(Q(is_staff=True) | Q(is_superuser=True))
return qs
admin.site.unregister(User)
admin.site.register(Staff, StaffAdmin)
admin.site.register(Customer, CustomerAdmin)
# Setting
class CompanyAdmin(admin.ModelAdmin):
list_display = ('name', 'address', 'phone', 'fax')
search_fields = ('name', 'phone')
admin.site.register(Company, CompanyAdmin)
# Setting
class CDRAdmin(admin.ModelAdmin):
list_display = ('id', 'src', 'dst', 'calldate', 'clid', 'channel', 'duration', 'disposition', 'accountcode')
list_filter = ['calldate', 'accountcode']
search_fields = ('accountcode', 'dst', 'src')
ordering = ('-id',)
admin.site.register(CDR, CDRAdmin)
| from cdr.models import *
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django.db.models import Q
from .models import Customer, Staff
class UserProfileInline(admin.StackedInline):
model = UserProfile
class StaffAdmin(UserAdmin):
inlines = [UserProfileInline]
list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'is_active', 'is_superuser', 'last_login')
def queryset(self, request):
qs = super(UserAdmin, self).queryset(request)
qs = qs.filter(Q(is_staff=True) | Q(is_superuser=True))
return qs
class CustomerAdmin(StaffAdmin):
inlines = [UserProfileInline]
list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'is_active', 'is_superuser', 'last_login')
def queryset(self, request):
qs = super(UserAdmin, self).queryset(request)
qs = qs.exclude(Q(is_staff=True) | Q(is_superuser=True))
return qs
admin.site.unregister(User)
admin.site.register(Staff, StaffAdmin)
admin.site.register(Customer, CustomerAdmin)
# Setting
class CompanyAdmin(admin.ModelAdmin):
list_display = ('name', 'address', 'phone', 'fax')
search_fields = ('name', 'phone')
admin.site.register(Company, CompanyAdmin)
# Setting
class CDRAdmin(admin.ModelAdmin):
list_display = ('id', 'src', 'dst', 'calldate', 'clid', 'channel', 'duration', 'disposition', 'accountcode')
list_filter = ['calldate', 'accountcode']
search_fields = ('accountcode', 'dst', 'src')
ordering = ('-id',)
admin.site.register(CDR, CDRAdmin)
| mpl-2.0 | Python |
e8e14e04903b8e81782b0818a80fecb14bbd202c | update a test for HTCondorJobSubmitter | alphatwirl/alphatwirl,alphatwirl/alphatwirl,alphatwirl/alphatwirl,alphatwirl/alphatwirl | tests/unit/concurrently/test_HTCondorJobSubmitter.py | tests/unit/concurrently/test_HTCondorJobSubmitter.py | # Tai Sakuma <tai.sakuma@gmail.com>
import os
import sys
import logging
import textwrap
import pytest
try:
import unittest.mock as mock
except ImportError:
import mock
from alphatwirl.concurrently import HTCondorJobSubmitter
##__________________________________________________________________||
job_desc_template_with_extra = """
Executable = run.py
output = results/$(resultdir)/stdout.txt
error = results/$(resultdir)/stderr.txt
log = results/$(resultdir)/log.txt
Arguments = $(resultdir).p.gz
should_transfer_files = YES
when_to_transfer_output = ON_EXIT
transfer_input_files = {input_files}
transfer_output_files = results
Universe = vanilla
notification = Error
getenv = True
request_memory = 900
queue resultdir in {resultdirs}
"""
job_desc_template_with_extra = textwrap.dedent(job_desc_template_with_extra).strip()
##__________________________________________________________________||
@pytest.fixture()
def subprocess():
proc_submit = mock.MagicMock(name='proc_condor_submit')
proc_submit.communicate.return_value = (b'1 job(s) submitted to cluster 1012.', b'')
proc_prio = mock.MagicMock(name='proc_condor_prio')
proc_prio.communicate.return_value = ('', '')
proc_prio.returncode = 0
ret = mock.MagicMock(name='subprocess')
ret.Popen.side_effect = [proc_submit, proc_prio]
return ret
@pytest.fixture()
def obj(monkeypatch, subprocess):
module = sys.modules['alphatwirl.concurrently.HTCondorJobSubmitter']
monkeypatch.setattr(module, 'subprocess', subprocess)
module = sys.modules['alphatwirl.concurrently.exec_util']
monkeypatch.setattr(module, 'subprocess', subprocess)
return HTCondorJobSubmitter()
def test_repr(obj):
repr(obj)
def test_init_job_desc_extra(obj):
job_desc_extra = ['request_memory = 900']
obj = HTCondorJobSubmitter(job_desc_extra=job_desc_extra)
assert job_desc_template_with_extra == obj.job_desc_template
def test_run(obj, tmpdir_factory, caplog):
workingarea = mock.MagicMock()
workingarea.path = str(tmpdir_factory.mktemp(''))
workingarea.package_path.return_value = 'aaa'
with caplog.at_level(logging.WARNING):
assert '1012.0' == obj.run(workingArea=workingarea, package_index=0)
##__________________________________________________________________||
| # Tai Sakuma <tai.sakuma@gmail.com>
import os
import sys
import logging
import textwrap
import pytest
try:
import unittest.mock as mock
except ImportError:
import mock
from alphatwirl.concurrently import HTCondorJobSubmitter
##__________________________________________________________________||
job_desc_template_with_extra = """
Executable = run.py
output = results/$(resultdir)/stdout.txt
error = results/$(resultdir)/stderr.txt
log = results/$(resultdir)/log.txt
Arguments = $(resultdir).p.gz
should_transfer_files = YES
when_to_transfer_output = ON_EXIT
transfer_input_files = {input_files}
transfer_output_files = results
Universe = vanilla
notification = Error
getenv = True
request_memory = 900
queue resultdir in {resultdirs}
"""
job_desc_template_with_extra = textwrap.dedent(job_desc_template_with_extra).strip()
##__________________________________________________________________||
@pytest.fixture()
def subprocess():
proc_submit = mock.MagicMock(name='proc_condor_submit')
proc_submit.communicate.return_value = (b'1 job(s) submitted to cluster 1012.', b'')
proc_prio = mock.MagicMock(name='proc_condor_prio')
proc_prio.communicate.return_value = ('', '')
proc_prio.returncode = 0
ret = mock.MagicMock(name='subprocess')
ret.Popen.side_effect = [proc_submit, proc_prio]
return ret
@pytest.fixture()
def obj(monkeypatch, subprocess):
module = sys.modules['alphatwirl.concurrently.HTCondorJobSubmitter']
monkeypatch.setattr(module, 'subprocess', subprocess)
module = sys.modules['alphatwirl.concurrently.exec_util']
monkeypatch.setattr(module, 'subprocess', subprocess)
return HTCondorJobSubmitter()
def test_repr(obj):
repr(obj)
def test_init_job_desc_extra(obj):
job_desc_extra = ['request_memory = 900']
obj = HTCondorJobSubmitter(job_desc_extra=job_desc_extra)
assert job_desc_template_with_extra == obj.job_desc_template
def test_run(obj, tmpdir_factory, caplog):
workingarea = mock.MagicMock()
workingarea.path = str(tmpdir_factory.mktemp(''))
workingarea.package_path.return_value = 'aaa'
with caplog.at_level(logging.WARNING, logger = 'alphatwirl'):
assert '1012.0' == obj.run(workingArea=workingarea, package_index=0)
##__________________________________________________________________||
| bsd-3-clause | Python |
7ff95411cf999d074b7ae8496ea33f083ac78de6 | Add test for push --ship command | cloudControl/cctrl,cloudControl/cctrl | test/app_test.py | test/app_test.py | import unittest
from mock import patch, call, Mock
from cctrl.error import InputErrorException
from cctrl.app import AppController
from cctrl.settings import Settings
class AppControllerTestCase(unittest.TestCase):
def test_get_size_from_memory_1gb(self):
self.assertEqual(8, AppController(None, Settings())._get_size_from_memory('1GB'))
@patch('cctrl.app.sys')
def test_get_size_from_memory_mb_rounded(self, _sys):
self.assertEqual(6, AppController(None, Settings())._get_size_from_memory('666MB'))
self.assertEqual([
call.stderr.write('Memory size has to be a multiple of 128MB and has been rounded up to 768MB.'),
call.stderr.write('\n')], _sys.mock_calls)
def test_get_size_from_memory_nop_match(self):
with self.assertRaises(InputErrorException) as ctx:
AppController(None, Settings())._get_size_from_memory('0.7')
self.assertEqual('[ERROR] Memory size should be an integer between 128 and 1024 MB', str(ctx.exception))
def test_get_size_from_memory_unrecognized_unit(self):
with self.assertRaises(InputErrorException) as ctx:
AppController(None, Settings())._get_size_from_memory('4kb')
self.assertEqual('[ERROR] Memory size should be an integer between 128 and 1024 MB', str(ctx.exception))
@patch('cctrl.app.check_call')
def test_push_with_ship(self, check_call):
app = AppController(None, Settings())
app.redeploy = Mock()
app.log_from_now = Mock()
app._get_or_create_deployment = Mock(return_value=({'branch': 'default', 'name': 'dep'}, 'name'))
args = Mock()
args.name = 'app/dep'
args.deploy = False
app.push(args)
self.assertTrue(check_call.called)
self.assertTrue(app.redeploy.called)
self.assertTrue(app.log_from_now.called)
@patch('cctrl.app.check_call')
def test_push_with_deploy(self, check_call):
app = AppController(None, Settings())
app.redeploy = Mock()
app._get_or_create_deployment = Mock(return_value=({'branch': 'default'}, 'name'))
args = Mock()
args.name = 'app/dep'
args.ship = False
app.push(args)
self.assertTrue(check_call.called)
self.assertTrue(app.redeploy.called)
| import unittest
from mock import patch, call, Mock
from cctrl.error import InputErrorException
from cctrl.app import AppController
from cctrl.settings import Settings
class AppControllerTestCase(unittest.TestCase):
def test_get_size_from_memory_1gb(self):
self.assertEqual(8, AppController(None, Settings())._get_size_from_memory('1GB'))
@patch('cctrl.app.sys')
def test_get_size_from_memory_mb_rounded(self, _sys):
self.assertEqual(6, AppController(None, Settings())._get_size_from_memory('666MB'))
self.assertEqual([
call.stderr.write('Memory size has to be a multiple of 128MB and has been rounded up to 768MB.'),
call.stderr.write('\n')], _sys.mock_calls)
def test_get_size_from_memory_nop_match(self):
with self.assertRaises(InputErrorException) as ctx:
AppController(None, Settings())._get_size_from_memory('0.7')
self.assertEqual('[ERROR] Memory size should be an integer between 128 and 1024 MB', str(ctx.exception))
def test_get_size_from_memory_unrecognized_unit(self):
with self.assertRaises(InputErrorException) as ctx:
AppController(None, Settings())._get_size_from_memory('4kb')
self.assertEqual('[ERROR] Memory size should be an integer between 128 and 1024 MB', str(ctx.exception))
@patch('cctrl.app.check_call')
def test_push_with_deploy(self, check_call):
app = AppController(None, Settings())
app.redeploy = Mock()
app._get_or_create_deployment = Mock(return_value=({'branch': 'default'}, 'name'))
args = Mock()
args.name = 'app/dep'
args.ship = False
app.push(args)
self.assertTrue(check_call.called)
self.assertTrue(app.redeploy.called)
| apache-2.0 | Python |
ec94b6b15cabc3a190ec59ab822330d9410af56f | Update tag search | ping/instagram_private_api | instagram_private_api/endpoints/tags.py | instagram_private_api/endpoints/tags.py | import json
class TagsEndpointsMixin(object):
"""For endpoints in ``/tags/``."""
def tag_info(self, tag):
"""
Get tag info
:param tag:
:return:
"""
endpoint = 'tags/{tag!s}/info/'.format(**{'tag': tag})
res = self._call_api(endpoint)
return res
def tag_related(self, tag, **kwargs):
"""
Get related tags
:param tag:
:return:
"""
endpoint = 'tags/{tag!s}/related/'.format(**{'tag': tag})
query = {
'visited': json.dumps([{'id': tag, 'type': 'hashtag'}], separators=(',', ':')),
'related_types': json.dumps(['hashtag', 'location'], separators=(',', ':'))}
res = self._call_api(endpoint, query=query)
return res
def tag_search(self, text, **kwargs):
"""
Search tag
:param text:
:param kwargs:
:return:
"""
query = {
'q': text,
'timezone_offset': self.timezone_offset,
'count': 30,
}
query.update(kwargs)
res = self._call_api('tags/search/', query=query)
return res
| import json
class TagsEndpointsMixin(object):
"""For endpoints in ``/tags/``."""
def tag_info(self, tag):
"""
Get tag info
:param tag:
:return:
"""
endpoint = 'tags/{tag!s}/info/'.format(**{'tag': tag})
res = self._call_api(endpoint)
return res
def tag_related(self, tag, **kwargs):
"""
Get related tags
:param tag:
:return:
"""
endpoint = 'tags/{tag!s}/related/'.format(**{'tag': tag})
query = {
'visited': json.dumps([{'id': tag, 'type': 'hashtag'}], separators=(',', ':')),
'related_types': json.dumps(['hashtag', 'location'], separators=(',', ':'))}
res = self._call_api(endpoint, query=query)
return res
def tag_search(self, text, **kwargs):
"""
Search tag
:param text:
:param kwargs:
:return:
"""
query = {
'is_typeahead': True,
'q': text,
'rank_token': self.rank_token,
}
query.update(kwargs)
res = self._call_api('tags/search/', query=query)
return res
| mit | Python |
ae9ba3c6bfdb5f9e47a16e8d8f8585d73fd2edce | format code | phodal/growth-code,phodal/growth-code,phodal/growth-code | chapter5/blog/tests.py | chapter5/blog/tests.py | from datetime import datetime
from django.core.urlresolvers import resolve
from django.test import TestCase
from blog.models import Blog
from blog.views import blog_detail
class BlogpostTest(TestCase):
def test_blogpost_url_resolves_to_blog_post_view(self):
found = resolve('/blog/this_is_a_test.html')
self.assertEqual(found.func, blog_detail)
def test_blogpost_create_with_view(self):
Blog.objects.create(title='hello', author='admin', slug='this_is_a_test', body='This is a blog',
posted=datetime.now)
response = self.client.get('/blog/this_is_a_test.html')
self.assertIn(b'This is a blog', response.content)
| from datetime import datetime
from django.core.urlresolvers import resolve
from django.test import TestCase
from blog.models import Blog
from blog.views import blog_detail
class BlogpostTest(TestCase):
def test_blogpost_url_resolves_to_blog_post_view(self):
found = resolve('/blog/this_is_a_test.html')
self.assertEqual(found.func, blog_detail)
def test_blogpost_create_with_view(self):
Blog.objects.create(title='hello', author='admin', slug='this_is_a_test', body='This is a blog',
posted=datetime.now)
response = self.client.get('/blog/this_is_a_test.html')
self.assertIn(b'This is a blog', response.content)
| mit | Python |
b03e993c8d9ecf344b3f05432b0c07ecaba6fe89 | Fix pip example for latest CentOS 8 Docker image. | Fizzadar/pyinfra,Fizzadar/pyinfra | examples/pip.py | examples/pip.py | from pyinfra import host
from pyinfra.operations import apk, apt, files, pip, python, yum
SUDO = True
if host.fact.linux_name in ['Alpine']:
apk.packages(
name='Install packages for python virtual environments',
packages=[
'gcc',
'libffi-dev',
'make',
'musl-dev',
'openssl-dev',
'py3-pynacl',
'py3-virtualenv',
'python3-dev',
],
)
if host.fact.linux_name in ['CentOS']:
yum.packages(
name='Install pip3 so you can install virtualenv',
packages=['python3-pip', 'python3-devel', 'gcc-c++', 'make'],
)
if host.fact.linux_name in ['Ubuntu']:
apt.packages(
name='Install pip3 so you can install virtualenv',
packages='python3-pip',
update=True,
)
if not host.fact.file('/usr/bin/pip'):
files.link(
name='Create link /usr/bin/pip that points to /usr/bin/pip3',
path='/usr/bin/pip',
target='/usr/bin/pip3',
)
pip.packages(
name='Install virtualenv using pip',
packages='virtualenv',
)
pip.virtualenv(
name='Create a virtualenv',
path='/usr/local/bin/venv',
)
# use that virtualenv to install pyinfra
pip.packages(
name='Install pyinfra into a virtualenv',
packages='pyinfra',
virtualenv='/usr/local/bin/venv',
)
# Show that we can actually run the pyinfra command from that virtualenv
def run_pyinfra_version(state, host):
status, stdout, stderr = host.run_shell_command(
'/usr/local/bin/venv/bin/pyinfra --version',
env={'LC_ALL': 'C.UTF-8', 'LANG': 'C.UTF-8,'},
)
assert status, 'pyinfra command failed: {0}'.format((stdout, stderr))
assert 'pyinfra: ' in stdout[0]
python.call(run_pyinfra_version) # noqa: E305
| from pyinfra import host
from pyinfra.operations import apk, apt, files, pip, python, yum
SUDO = True
if host.fact.linux_name in ['Alpine']:
apk.packages(
name='Install packages for python virtual environments',
packages=[
'gcc',
'libffi-dev',
'make',
'musl-dev',
'openssl-dev',
'py3-pynacl',
'py3-virtualenv',
'python3-dev',
],
)
if host.fact.linux_name in ['CentOS']:
yum.packages(
name='Install pip3 so you can install virtualenv',
packages='python3-pip',
)
if host.fact.linux_name in ['Ubuntu']:
apt.packages(
name='Install pip3 so you can install virtualenv',
packages='python3-pip',
update=True,
)
if not host.fact.file('/usr/bin/pip'):
files.link(
name='Create link /usr/bin/pip that points to /usr/bin/pip3',
path='/usr/bin/pip',
target='/usr/bin/pip3',
)
pip.packages(
name='Install virtualenv using pip',
packages='virtualenv',
)
pip.virtualenv(
name='Create a virtualenv',
path='/usr/local/bin/venv',
)
# use that virtualenv to install pyinfra
pip.packages(
name='Install pyinfra into a virtualenv',
packages='pyinfra',
virtualenv='/usr/local/bin/venv',
)
# Show that we can actually run the pyinfra command from that virtualenv
def run_pyinfra_version(state, host):
status, stdout, stderr = host.run_shell_command(
'/usr/local/bin/venv/bin/pyinfra --version',
env={'LC_ALL': 'C.UTF-8', 'LANG': 'C.UTF-8,'},
)
assert status, 'pyinfra command failed: {0}'.format((stdout, stderr))
assert 'pyinfra: ' in stdout[0]
python.call(run_pyinfra_version) # noqa: E305
| mit | Python |
6a22a5c7429b66010eb023643d838c7f0beb31b8 | use argparse for robust parsing | andrewSC/checkthat | checkthat/checkthat.py | checkthat/checkthat.py | import datetime
import os
import sys
import smtplib
import argparse
from .models import BuildFailure
from .builders import PackageBuilder
from .views import EmailView
def gather_pkgbuild_paths(root_pkgs_dir):
pkgbuild_paths = []
for root, dirs, files in os.walk(root_pkgs_dir):
if 'PKGBUILD' in files:
pkgbuild_paths.append(root)
return pkgbuild_paths
def email_results(message):
server = smtplib.SMTP('localhost')
now = datetime.datetime.now()
subject = f"Arrakis AUR build results on {now.strftime('%Y-%m-%d %H:%M:%S')}"
message = f"From: duncan@planet.arrakis\r\nTo: andrew@crerar.io\r\nSubject: {subject} \r\n\r\n{message}"
email = {
'from': 'duncan@planet.arrakis',
'to': ['andrew@crerar.io'],
'subject': subject,
'message': message
}
server.sendmail(email['from'], email['to'], email['message'])
server.quit()
def main():
parser = argparse.ArgumentParser(description='An automated AUR package builder and analyzer')
parser.add_argument('path', help='Path to where packages are located')
args = parser.parse_args()
abs_paths = gather_pkgbuild_paths(args.path) # ABS path to where all the folders for packages are located
builder = PackageBuilder()
view = EmailView()
builds = []
for path in abs_paths:
build = builder.build(path,
fetch_latest_pkgbuild=True)
build.namcap_pkgbuild_analysis = builder.analyze_pkgbuild(path)
if type(build) is not BuildFailure:
# NOTE: We should only try to analyze the package if the build
# was actually successful
build.namcap_pkg_analysis = builder.analyze_pkg(path)
builder.cleanup(build) # TODO: Make this better
builds.append(build)
# TODO: Make cli output or email results output configurable
email_results(view.generate_output(builds))
| import datetime
import os
import sys
import smtplib
from .models import BuildFailure
from .builders import PackageBuilder
from .views import EmailView
def gather_pkgbuild_paths(root_pkgs_dir):
pkgbuild_paths = []
for root, dirs, files in os.walk(root_pkgs_dir):
if 'PKGBUILD' in files:
pkgbuild_paths.append(root)
return pkgbuild_paths
def email_results(message):
server = smtplib.SMTP('localhost')
now = datetime.datetime.now()
subject = f"Arrakis AUR build results on {now.strftime('%Y-%m-%d %H:%M:%S')}"
message = f"From: duncan@planet.arrakis\r\nTo: andrew@crerar.io\r\nSubject: {subject} \r\n\r\n{message}"
email = {
'from': 'duncan@planet.arrakis',
'to': ['andrew@crerar.io'],
'subject': subject,
'message': message
}
server.sendmail(email['from'], email['to'], email['message'])
server.quit()
def main():
if len(sys.argv) < 2:
print('Error: Missing path to directory containing AUR packages.')
print('Usage: python checkthat.py <dir>')
quit()
abs_paths = gather_pkgbuild_paths(sys.argv[1]) # ABS path to where all the folders for packages are located
builder = PackageBuilder()
view = EmailView()
builds = []
for path in abs_paths:
build = builder.build(path,
fetch_latest_pkgbuild=True)
build.namcap_pkgbuild_analysis = builder.analyze_pkgbuild(path)
if type(build) is not BuildFailure:
# NOTE: We should only try to analyze the package if the build
# was actually successful
build.namcap_pkg_analysis = builder.analyze_pkg(path)
builder.cleanup(build) # TODO: Make this better
builds.append(build)
# TODO: Make cli output or email results output configurable
email_results(view.generate_output(builds))
| mit | Python |
2950cc7c2cccdf32a7494299158dee31316c3248 | Choose SPW | e-koch/canfar_scripts,e-koch/canfar_scripts | cal_pipe/plot_scans.py | cal_pipe/plot_scans.py |
import numpy as np
import re
import os
ms_active = raw_input("MS? : ")
field_str = raw_input("Field? : ")
spw_str = raw_input("SPW? : ")
tb.open(ms_active+"/FIELD")
names = tb.getcol('NAME')
matches = [string for string in names if re.match(field_str, string)]
posn_matches = \
[i for i, string in enumerate(names) if re.match(field_str, string)]
numFields = tb.nrows()
tb.close()
if len(matches) == 0:
raise TypeError("No matches found for the given field string")
tb.open(ms_active)
scanNums = sorted(np.unique(tb.getcol('SCAN_NUMBER')))
field_scans = []
for ii in range(numFields):
subtable = tb.query('FIELD_ID==%s'%ii)
field_scans.append(list(np.unique(subtable.getcol('SCAN_NUMBER'))))
tb.close()
field_scans = [scans for i, scans in enumerate(field_scans) if i in posn_matches]
try:
os.mkdir("scan_plots")
except OSError:
pass
for ii in range(len(field_scans)):
print("On field "+matches[ii])
for jj in field_scans[ii]:
print("On scan "+str(jj))
default('plotms')
vis = ms_active
xaxis = 'time'
yaxis = 'amp'
ydatacolumn = 'corrected'
selectdata = True
field = matches[ii]
scan = str(jj)
spw = spw_str
correlation = "RR,LL"
averagedata = True
avgbaseline = True
transform = False
extendflag = False
plotrange = []
title = 'Amp vs Time: Field '+matches[ii]+' Scan'+str(jj)
xlabel = ''
ylabel = ''
showmajorgrid = False
showminorgrid = False
plotfile = 'scan_plots/field_'+matches[ii]+'_scan_'+str(jj)+'.png'
overwrite = True
showgui = False
async = False
plotms()
|
import numpy as np
import re
import os
ms_active = raw_input("MS? : ")
field_str = raw_input("Field? : ")
tb.open(ms_active+"/FIELD")
names = tb.getcol('NAME')
matches = [string for string in names if re.match(field_str, string)]
posn_matches = \
[i for i, string in enumerate(names) if re.match(field_str, string)]
numFields = tb.nrows()
tb.close()
if len(matches) == 0:
raise TypeError("No matches found for the given field string")
tb.open(ms_active)
scanNums = sorted(np.unique(tb.getcol('SCAN_NUMBER')))
field_scans = []
for ii in range(numFields):
subtable = tb.query('FIELD_ID==%s'%ii)
field_scans.append(list(np.unique(subtable.getcol('SCAN_NUMBER'))))
tb.close()
field_scans = [scans for i, scans in enumerate(field_scans) if i in posn_matches]
try:
os.mkdir("scan_plots")
except OSError:
pass
for ii in range(len(field_scans)):
print("On field "+matches[ii])
for jj in field_scans[ii]:
print("On scan "+str(jj))
default('plotms')
vis = ms_active
xaxis = 'time'
yaxis = 'amp'
ydatacolumn = 'corrected'
selectdata = True
field = matches[ii]
scan = str(jj)
correlation = "RR,LL"
averagedata = True
avgbaseline = True
transform = False
extendflag = False
plotrange = []
title = 'Amp vs Time: Field'+matches[ii]+' Scan'+str(jj)
xlabel = ''
ylabel = ''
showmajorgrid = False
showminorgrid = False
plotfile = 'scan_plots/field_'+matches[ii]+'_scan_'+str(jj)+'.png'
overwrite = True
showgui = False
async = False
plotms()
| mit | Python |
fec2f62104a37f703341e4732e0a4f094f0d6750 | Bump version | brynpickering/calliope,calliope-project/calliope,brynpickering/calliope | calliope/_version.py | calliope/_version.py | __version__ = '0.4.0-dev'
| __version__ = '0.3.8-dev'
| apache-2.0 | Python |
34c71dc8914fe753010e94b0cb0779418846c99f | Use apt-get instead of aptitude | fabtools/fabtools,pombredanne/fabtools,ahnjungho/fabtools,bitmonk/fabtools,prologic/fabtools,AMOSoft/fabtools,pahaz/fabtools,sociateru/fabtools,n0n0x/fabtools-python,ronnix/fabtools,hagai26/fabtools,badele/fabtools,wagigi/fabtools-python,davidcaste/fabtools | fabtools/deb.py | fabtools/deb.py | """
Fabric tools for managing Debian/Ubuntu packages
"""
from fabric.api import *
MANAGER = 'apt-get'
def update_index():
"""
Quietly update package index
"""
sudo("%s -q -q update" % MANAGER)
def upgrade(safe=True):
"""
Upgrade all packages
"""
manager = MANAGER
cmds = {'apt-get': {False: 'dist-upgrade', True: 'upgrade'},
'aptitude': {False: 'full-upgrade', True: 'safe-upgrade'}}
cmd = cmds[manager][safe]
sudo("%(manager)s --assume-yes %(cmd)s" % locals())
def is_installed(pkg_name):
"""
Check if .deb package is installed
"""
with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):
res = run("dpkg -s %(pkg_name)s" % locals())
for line in res.splitlines():
if line.startswith("Status: "):
status = line[8:]
if "installed" in status.split(' '):
return True
return False
def install(packages, update=False, options=None):
"""
Install .deb package(s)
"""
manager = MANAGER
if update:
update_index()
if options is None:
options = []
if not isinstance(packages, basestring):
packages = " ".join(packages)
options.append("--assume-yes")
options = " ".join(options)
sudo('%(manager)s install %(options)s %(packages)s' % locals())
def preseed_package(pkg_name, preseed):
"""
Enable unattended package installation by preseeding debconf parameters
"""
for q_name, _ in preseed.items():
q_type, q_answer = _
sudo('echo "%(pkg_name)s %(q_name)s %(q_type)s %(q_answer)s" | debconf-set-selections' % locals())
def distrib_codename():
"""
Get the codename of the distrib
"""
with settings(hide('running', 'stdout')):
return run('grep DISTRIB_CODENAME /etc/lsb-release').split('=')[1]
| """
Fabric tools for managing Debian/Ubuntu packages
"""
from fabric.api import *
def update_index():
"""
Quietly update package index
"""
sudo("aptitude -q -q update")
def upgrade():
"""
Upgrade all packages
"""
sudo("aptitude --assume-yes safe-upgrade")
def is_installed(pkg_name):
"""
Check if .deb package is installed
"""
with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):
res = run("dpkg -s %(pkg_name)s" % locals())
for line in res.splitlines():
if line.startswith("Status: "):
status = line[8:]
if "installed" in status.split(' '):
return True
return False
def install(packages, update=False, options=None):
"""
Install .deb package(s)
"""
if update:
update_index()
if options is None:
options = []
if not isinstance(packages, basestring):
packages = " ".join(packages)
options.append("--assume-yes")
options = " ".join(options)
sudo('aptitude install %(options)s %(packages)s' % locals())
def preseed_package(pkg_name, preseed):
"""
Enable unattended package installation by preseeding debconf parameters
"""
for q_name, _ in preseed.items():
q_type, q_answer = _
sudo('echo "%(pkg_name)s %(q_name)s %(q_type)s %(q_answer)s" | debconf-set-selections' % locals())
def distrib_codename():
"""
Get the codename of the distrib
"""
with settings(hide('running', 'stdout')):
return run('grep DISTRIB_CODENAME /etc/lsb-release').split('=')[1]
| bsd-2-clause | Python |
b2e471813a27150b28071dc3caa4e4f3e41401c3 | Remove dory reference | openstack/poppy,obulpathi/cdn1,amitgandhinz/cdn,openstack/poppy,obulpathi/poppy,stackforge/poppy,openstack/poppy,obulpathi/cdn1,amitgandhinz/cdn,obulpathi/poppy,stackforge/poppy,obulpathi/poppy,stackforge/poppy | cdn/transport/app.py | cdn/transport/app.py | # Copyright (c) 2014 Rackspace, Inc.
#
# 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.
"""WSGI callable for WSGI containers
This app should be used by external WSGI
containers. For example:
$ gunicorn cdn.transport.app:app
NOTE: As for external containers, it is necessary
to put config files in the standard paths. There's
no common way to specify / pass configuration files
to the WSGI app when it is called from other apps.
"""
from oslo.config import cfg
from cdn import bootstrap
conf = cfg.CONF
conf(project='cdn', prog='cdn', args=[])
app = bootstrap.Bootstrap(conf).transport.app
| # Copyright (c) 2014 Rackspace, Inc.
#
# 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.
"""WSGI callable for WSGI containers
This app should be used by external WSGI
containers. For example:
$ gunicorn dory.transport.app:app
NOTE: As for external containers, it is necessary
to put config files in the standard paths. There's
no common way to specify / pass configuration files
to the WSGI app when it is called from other apps.
"""
from oslo.config import cfg
from cdn import bootstrap
conf = cfg.CONF
conf(project='cdn', prog='cdn', args=[])
app = bootstrap.Bootstrap(conf).transport.app
| apache-2.0 | Python |
3e30737c98a4a9e890d362ba4cbbb2315163bc29 | Remove unused Python 2 support | kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh | cfgov/v1/__init__.py | cfgov/v1/__init__.py | from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse
from django.template.defaultfilters import slugify
from wagtail.wagtailcore.templatetags import wagtailcore_tags
from wagtail.wagtailadmin.templatetags import wagtailuserbar
from jinja2 import Environment
from compressor.contrib.jinja2ext import CompressorExtension
def environment(**options):
options.setdefault('extensions', []).append(CompressorExtension)
env = Environment(**options)
env.globals.update({
'static': staticfiles_storage.url,
'reverse': reverse,
'wagtailuserbar': wagtailuserbar.wagtailuserbar
})
env.filters.update({
'slugify': slugify,
'richtext': wagtailcore_tags.richtext
})
return env
| from __future__ import absolute_import # Python 2 only
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse
from django.template.defaultfilters import slugify
from wagtail.wagtailcore.templatetags import wagtailcore_tags
from wagtail.wagtailadmin.templatetags import wagtailuserbar
from jinja2 import Environment
from compressor.contrib.jinja2ext import CompressorExtension
def environment(**options):
options.setdefault('extensions', []).append(CompressorExtension)
env = Environment(**options)
env.globals.update({
'static': staticfiles_storage.url,
'reverse': reverse,
'wagtailuserbar': wagtailuserbar.wagtailuserbar
})
env.filters.update({
'slugify': slugify,
'richtext': wagtailcore_tags.richtext
})
return env
| cc0-1.0 | Python |
28e7f68022f17657f91ba30feffae49ddefe5227 | Update version to 0.8.6 | vkosuri/ChatterBot,gunthercox/ChatterBot | chatterbot/__init__.py | chatterbot/__init__.py | """
ChatterBot is a machine learning, conversational dialog engine.
"""
from .chatterbot import ChatBot
__version__ = '0.8.6'
__author__ = 'Gunther Cox'
__email__ = 'gunthercx@gmail.com'
__url__ = 'https://github.com/gunthercox/ChatterBot'
__all__ = (
'ChatBot',
)
| """
ChatterBot is a machine learning, conversational dialog engine.
"""
from .chatterbot import ChatBot
__version__ = '0.8.5'
__author__ = 'Gunther Cox'
__email__ = 'gunthercx@gmail.com'
__url__ = 'https://github.com/gunthercox/ChatterBot'
__all__ = (
'ChatBot',
)
| bsd-3-clause | Python |
a2d3e7113dcda7c5f4ebaff96bdb9ac39ed434f9 | fix import error | arokem/nipy,nipy/nipy-labs,alexis-roche/nipy,alexis-roche/register,nipy/nireg,arokem/nipy,alexis-roche/nipy,bthirion/nipy,bthirion/nipy,alexis-roche/register,bthirion/nipy,alexis-roche/register,alexis-roche/nireg,alexis-roche/niseg,arokem/nipy,nipy/nipy-labs,nipy/nireg,alexis-roche/nipy,alexis-roche/nipy,alexis-roche/nireg,alexis-roche/niseg,arokem/nipy,bthirion/nipy | nipy/algorithms/registration/__init__.py | nipy/algorithms/registration/__init__.py | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
from .resample import resample
from .histogram_registration import (HistogramRegistration, clamp,
ideal_spacing, interp_methods)
from .affine import (threshold, rotation_mat2vec, rotation_vec2mat, to_matrix44,
preconditioner, inverse_affine, subgrid_affine, Affine,
Affine2D, Rigid, Rigid2D, Similarity, Similarity2D,
affine_transforms)
from .groupwise_registration import (interp_slice_times, scanner_coords,
make_grid, Image4d, Realign4dAlgorithm,
resample4d, adjust_subsampling,
single_run_realign4d, realign4d,
SpaceTimeRealign,
Realign4d, FmriRealign4d)
from nipy.testing import Tester
test = Tester().test
bench = Tester().bench
| # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
from .resample import resample
from .histogram_registration import (HistogramRegistration, clamp,
ideal_spacing, interp_methods)
from .affine import (threshold, rotation_mat2vec, rotation_vec2mat, to_matrix44,
preconditioner, inverse_affine, subgrid_affine, Affine,
Affine2D, Rigid, Rigid2D, Similarity, Similarity2D,
affine_transforms)
from .groupwise_registration import (interp_slice_times, scanner_coords,
make_grid, Image4d, Realign4dAlgorithm,
resample4d, adjust_subsampling,
single_run_realign4d, realign4d,
Realign4d, FmriRealign4d)
from nipy.testing import Tester
test = Tester().test
bench = Tester().bench
| bsd-3-clause | Python |
39e30520ce6c1cf01fc35f18f8b01f8668af55ed | add v2.4.1 (#22172) | LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack | var/spack/repos/builtin/packages/bpp-core/package.py | var/spack/repos/builtin/packages/bpp-core/package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class BppCore(CMakePackage):
"""Bio++ core library."""
homepage = "http://biopp.univ-montp2.fr/wiki/index.php/Installation"
url = "http://biopp.univ-montp2.fr/repos/sources/bpp-core-2.2.0.tar.gz"
version('2.4.1', sha256='1150b8ced22cff23dd4770d7c23fad11239070b44007740e77407f0d746c0af6')
version('2.2.0', sha256='aacd4afddd1584ab6bfa1ff6931259408f1d39958a0bdc5f78bf1f9ee4e98b79')
depends_on('cmake@2.6:', type='build')
# Clarify isnan's namespace, because Fujitsu compiler can't
# resolve ambiguous of 'isnan' function.
patch('clarify_isnan.patch', when='%fj')
def cmake_args(self):
return ['-DBUILD_TESTING=FALSE']
| # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class BppCore(CMakePackage):
"""Bio++ core library."""
homepage = "http://biopp.univ-montp2.fr/wiki/index.php/Installation"
url = "http://biopp.univ-montp2.fr/repos/sources/bpp-core-2.2.0.tar.gz"
version('2.2.0', sha256='aacd4afddd1584ab6bfa1ff6931259408f1d39958a0bdc5f78bf1f9ee4e98b79')
depends_on('cmake@2.6:', type='build')
# Clarify isnan's namespace, because Fujitsu compiler can't
# resolve ambiguous of 'isnan' function.
patch('clarify_isnan.patch', when='%fj')
def cmake_args(self):
return ['-DBUILD_TESTING=FALSE']
| lgpl-2.1 | Python |
8d052a48b2fc8dfe2110c006aec886b163ba9a55 | fix python3 comp., metric ordering | loadimpact/loadimpact-cli | loadimpactcli/metric_commands.py | loadimpactcli/metric_commands.py | # coding=utf-8
"""
Copyright 2016 Load Impact
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.
"""
from operator import attrgetter
import click
from loadimpact3.exceptions import ConnectionError
from .client import client
# TestRunResults type codes.
TEXT_TO_TYPE_CODE_MAP = {
'common': 1,
'url': 2,
'live_feedback': 3,
'log': 4,
'custom_metric': 5,
'page': 6,
'dtp': 7,
'system': 8,
'server_metric': 9,
'integration': 10
}
@click.group()
@click.pass_context
def metric(ctx):
pass
@metric.command('list', short_help='List metrics for a test run.')
@click.argument('test_run_id')
@click.option('--type', '-t', 'metric_types', multiple=True, type=click.Choice(TEXT_TO_TYPE_CODE_MAP.keys()),
help='Metric type to include on the list.')
def list_metrics(test_run_id, metric_types):
try:
types = ','.join(str(TEXT_TO_TYPE_CODE_MAP[k]) for k in metric_types)
result_ids = client.list_test_run_result_ids(test_run_id, data={'types': types})
click.echo('NAME:\tTYPE:')
for result_id in sorted(result_ids, key=attrgetter('type')):
for key, _ in sorted(result_id.ids.items()):
click.echo('{0}\t{1}'.format(key, result_id.results_type_code_to_text(result_id.type)))
except ConnectionError:
click.echo("Cannot connect to Load impact API")
| # coding=utf-8
"""
Copyright 2016 Load Impact
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 click
from loadimpact3.exceptions import ConnectionError
from .client import client
# TestRunResults type codes.
TEXT_TO_TYPE_CODE_MAP = {
'common': 1,
'url': 2,
'live_feedback': 3,
'log': 4,
'custom_metric': 5,
'page': 6,
'dtp': 7,
'system': 8,
'server_metric': 9,
'integration': 10
}
@click.group()
@click.pass_context
def metric(ctx):
pass
@metric.command('list', short_help='List metrics for a test run.')
@click.argument('test_run_id')
@click.option('--type', '-t', 'metric_types', multiple=True, type=click.Choice(TEXT_TO_TYPE_CODE_MAP.keys()),
help='Metric type to include on the list.')
def list_metrics(test_run_id, metric_types):
try:
types = ','.join(str(TEXT_TO_TYPE_CODE_MAP[k]) for k in metric_types)
result_ids = client.list_test_run_result_ids(test_run_id, data={'types': types})
click.echo('NAME:\tTYPE:')
for result_id in result_ids:
for key, _ in result_id.ids.iteritems():
click.echo('{0}\t{1}'.format(key, result_id.results_type_code_to_text(result_id.type)))
except ConnectionError:
click.echo("Cannot connect to Load impact API")
| apache-2.0 | Python |
ed050be8138c14428184cb99d19a3422ff2956fc | set version to 1.0.0 | simonsdave/clair-database,simonsdave/clair-cicd,simonsdave/clair-database,simonsdave/clair-cicd,simonsdave/clair-cicd | clair_cicd/__init__.py | clair_cicd/__init__.py | #
# this is the package version number
#
__version__ = '1.0.0'
#
# a few different components in this project need to make
# sure they use the same version of Clair and hence the
# motivation for having __clair_version__
#
# see https://quay.io/repository/coreos/clair?tab=tags
#
__clair_version__ = 'v2.1.2'
| #
# this is the package version number
#
__version__ = '0.6.0'
#
# a few different components in this project need to make
# sure they use the same version of Clair and hence the
# motivation for having __clair_version__
#
# see https://quay.io/repository/coreos/clair?tab=tags
#
__clair_version__ = 'v2.1.2'
| mit | Python |
f2d1d08ac3c0437c1649af90d699dd5e283b0948 | Add SK_IGNORE_UNDERLINE_POSITION_FIX to stage underline position fix. | primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs | public/blink_skia_config.gyp | public/blink_skia_config.gyp | #
# Copyright (C) 2012 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.
#
# This target is a dependency of Chromium's skia/skia_library.gyp.
# It only contains code suppressions which keep Webkit tests from failing.
{
'targets': [
{
'target_name': 'blink_skia_config',
'type': 'none',
'direct_dependent_settings': {
'defines': [
# Place defines here that require significant Blink rebaselining, or that
# are otherwise best removed in Blink and then rolled into Chromium.
# Defines should be in single quotes and a comma must appear after every one.
# DO NOT remove the define until you are ready to rebaseline, and
# AFTER the flag has been removed from skia.gyp in Chromium.
'SK_DEFERRED_CANVAS_USES_FACTORIES=1',
'SK_IGNORE_UNDERLINE_POSITION_FIX',
],
},
},
],
}
| #
# Copyright (C) 2012 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.
#
# This target is a dependency of Chromium's skia/skia_library.gyp.
# It only contains code suppressions which keep Webkit tests from failing.
{
'targets': [
{
'target_name': 'blink_skia_config',
'type': 'none',
'direct_dependent_settings': {
'defines': [
# Place defines here that require significant Blink rebaselining, or that
# are otherwise best removed in Blink and then rolled into Chromium.
# Defines should be in single quotes and a comma must appear after every one.
# DO NOT remove the define until you are ready to rebaseline, and
# AFTER the flag has been removed from skia.gyp in Chromium.
'SK_DEFERRED_CANVAS_USES_FACTORIES=1',
],
},
},
],
}
| bsd-3-clause | Python |
f7cd2a6a70ac0eda24f57d328273b9ff146b4f4a | make this a bit more useable and interesting | rdkit/rdkit-orig,rdkit/rdkit-orig,rdkit/rdkit-orig,rdkit/rdkit-orig,rdkit/rdkit-orig,rdkit/rdkit-orig,rdkit/rdkit-orig,rdkit/rdkit-orig | Code/Demos/RDKit/MPI/rdkpympi.py | Code/Demos/RDKit/MPI/rdkpympi.py | # $Id$
#
# Copyright (C) 2009 Greg Landrum
# All rights reserved
#
# Demo for using boost.mpi with the RDKit
#
# run this with : mpirun -n 4 python rdkpympi.py
#
from boost import mpi
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.RDLogger import logger
logger = logger()
def dividetask(data,task,silent=True):
data=mpi.broadcast(mpi.world,data,0)
nProcs = mpi.world.size
chunkSize=len(data)//nProcs
extraBits =len(data)%nProcs
res=[]
allRes=[]
# the root node handles the extra pieces:
if mpi.world.rank == 0:
for i in range(extraBits):
elem=data[i]
res.append(task(elem))
if not silent:
logger.info('task(%d) done %d'%(mpi.world.rank,i+1))
pos=extraBits+mpi.world.rank*chunkSize;
for i in range(chunkSize):
elem=data[pos]
pos += 1
res.append(task(elem))
if not silent:
logger.info('task(%d) done %d'%(mpi.world.rank,i+1))
if mpi.world.rank==0:
tmp=mpi.gather(mpi.world,res,0)
for res in tmp: allRes.extend(res)
else:
mpi.gather(mpi.world,res,0)
return allRes
if __name__=='__main__':
from rdkit import RDConfig
import os
fName = os.path.join(RDConfig.RDBaseDir,'Projects','DbCLI','testData','bzr.sdf')
if mpi.world.rank==0:
data = [x for x in Chem.SDMolSupplier(fName)][:50]
else:
data=None
def generateconformations(m):
m = Chem.AddHs(m)
ids=AllChem.EmbedMultipleConfs(m,numConfs=10)
for id in ids:
AllChem.UFFOptimizeMolecule(m,confId=id)
return m
cms=dividetask(data,generateconformations,silent=False)
# report:
if mpi.world.rank==0:
for i,mol in enumerate(cms):
print i,mol.GetNumConformers()
| # $Id$
#
# Copyright (C) 2009 Greg Landrum
# All rights reserved
#
# Demo for using boost.mpi with the RDKit
#
# run this with : mpirun -n 4 python rdkpympi.py
#
from boost import mpi
from rdkit import Chem
import sys
if mpi.world.rank==0:
data = [Chem.MolFromSmiles('C'*x) for x in range(1,100)]
else:
data=None
data=mpi.broadcast(mpi.world,data,0)
res=[]
allRes=[]
nProcs = mpi.world.size
chunkSize=len(data)//nProcs
extraBits =len(data)%nProcs
# handle extra bits on the root node:
if mpi.world.rank == 0:
for i in range(extraBits):
elem=data[i]
res.append(elem.GetNumAtoms(False))
pos=extraBits+mpi.world.rank*chunkSize;
for i in range(chunkSize):
elem=data[pos]
pos += 1
res.append(elem.GetNumAtoms(False))
if mpi.world.rank==0:
allRes=mpi.gather(mpi.world,res,0)
else:
mpi.gather(mpi.world,res,0)
# report:
if mpi.world.rank==0:
for i in range(mpi.world.size):
print "results from process:",i,": ",allRes[i]
| bsd-3-clause | Python |
94a4d09c1a484602070b06760581ad02ee01639e | update link | Pinaute/OctoPrint_FreeMobile-Notifier,Pinaute/OctoPrint_FreeMobile-Notifier | octoprint_freemobilenotifier/__init__.py | octoprint_freemobilenotifier/__init__.py | # coding=utf-8
from __future__ import absolute_import
import os
import octoprint.plugin
import urllib2
class FreemobilenotifierPlugin(octoprint.plugin.EventHandlerPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin):
#~~ SettingsPlugin
def get_settings_defaults(self):
return dict(
enabled=False,
login="",
pass_key="",
message_format=dict(
body="Job complete: {filename} done printing after {elapsed_time}"
)
)
def get_settings_version(self):
return 1
#~~ TemplatePlugin
def get_template_configs(self):
return [dict(type="settings", name="FreeMobile Notifier", custom_bindings=False)]
#~~ EventPlugin
def on_event(self, event, payload):
if event != "PrintDone":
return
if not self._settings.get(['enabled']):
return
filename = os.path.basename(payload["file"])
import datetime
import octoprint.util
elapsed_time = octoprint.util.get_formatted_timedelta(datetime.timedelta(seconds=payload["time"]))
tags = {'filename': filename, 'elapsed_time': elapsed_time}
message = self._settings.get(["message_format", "body"]).format(**tags)
login = self._settings.get(["login"])
pass_key = self._settings.get(["pass_key"])
url = 'https://smsapi.free-mobile.fr/sendmsg?&user='+login+'&pass='+pass_key+'&msg='+message
request = urllib2.Request(url)
try:
urllib2.urlopen(request)
except Exception as e:
# report problem sending sms
self._logger.exception("SMS notification error: %s" % (str(e)))
else:
# report notification was sent
self._logger.info("Print notification sent to %s" % (self._settings.get(['login'])))
##~~ Softwareupdate hook
def get_update_information(self):
return dict(
freemobilenotifier=dict(
displayName="FreeMobile Notifier Plugin",
displayVersion=self._plugin_version,
# version check: github repository
type="github_release",
user="Pinaute",
repo="OctoPrint_FreeMobile-Notifier",
current=self._plugin_version,
# update method: pip
pip="https://github.com/Pinaute/OctoPrint_FreeMobile-Notifier/archive/{target_version}.zip"
)
)
__plugin_name__ = "FreeMobile Notifier Plugin"
def __plugin_load__():
global __plugin_implementation__
__plugin_implementation__ = FreemobilenotifierPlugin()
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.plugin.softwareupdate.check_config": __plugin_implementation__.get_update_information
} | # coding=utf-8
from __future__ import absolute_import
import os
import octoprint.plugin
import urllib2
class FreemobilenotifierPlugin(octoprint.plugin.EventHandlerPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin):
#~~ SettingsPlugin
def get_settings_defaults(self):
return dict(
enabled=False,
login="",
pass_key="",
message_format=dict(
body="Job complete: {filename} done printing after {elapsed_time}"
)
)
def get_settings_version(self):
return 1
#~~ TemplatePlugin
def get_template_configs(self):
return [dict(type="settings", name="FreeMobile Notifier", custom_bindings=False)]
#~~ EventPlugin
def on_event(self, event, payload):
if event != "PrintDone":
return
if not self._settings.get(['enabled']):
return
filename = os.path.basename(payload["file"])
import datetime
import octoprint.util
elapsed_time = octoprint.util.get_formatted_timedelta(datetime.timedelta(seconds=payload["time"]))
tags = {'filename': filename, 'elapsed_time': elapsed_time}
message = self._settings.get(["message_format", "body"]).format(**tags)
login = self._settings.get(["login"])
pass_key = self._settings.get(["pass_key"])
url = 'https://smsapi.free-mobile.fr/sendmsg?&user='+login+'&pass='+pass_key+'&msg='+message
request = urllib2.Request(url)
try:
urllib2.urlopen(request)
except Exception as e:
# report problem sending sms
self._logger.exception("SMS notification error: %s" % (str(e)))
else:
# report notification was sent
self._logger.info("Print notification sent to %s" % (self._settings.get(['login'])))
##~~ Softwareupdate hook
def get_update_information(self):
return dict(
freemobilenotifier=dict(
displayName="FreeMobile Notifier Plugin",
displayVersion=self._plugin_version,
# version check: github repository
type="github_release",
user="Pinaute",
repo="OctoPrint-FreeMobile-Notifier",
current=self._plugin_version,
# update method: pip
pip="https://github.com/Pinaute/OctoPrint-FreeMobile-Notifier/archive/{target_version}.zip"
)
)
__plugin_name__ = "FreeMobile Notifier Plugin"
def __plugin_load__():
global __plugin_implementation__
__plugin_implementation__ = FreemobilenotifierPlugin()
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.plugin.softwareupdate.check_config": __plugin_implementation__.get_update_information
} | agpl-3.0 | Python |
cb4b7ce7cbb9e7e951dacc5e4f38a31c045038cd | Fix ResourcePath ctor (to restore Python 2.7 compatibility) #473 | vgrem/Office365-REST-Python-Client | office365/runtime/paths/resource_path.py | office365/runtime/paths/resource_path.py | from office365.runtime.client_path import ClientPath
class ResourcePath(ClientPath):
"""OData resource path"""
def __init__(self, name, parent=None):
"""
:param str name: entity or property name
:type parent: office365.runtime.client_path.ClientPath or None
"""
super(ResourcePath, self).__init__(parent)
self._name = name
self._parent = parent
@property
def segments(self):
return [self.delimiter, self._name]
| from office365.runtime.client_path import ClientPath
class ResourcePath(ClientPath):
"""OData resource path"""
def __init__(self, name, parent=None):
"""
:param str name: entity or property name
:type parent: office365.runtime.client_path.ClientPath or None
"""
super().__init__(parent)
self._name = name
self._parent = parent
@property
def segments(self):
return [self.delimiter, self._name]
| mit | Python |
0cbbc0eac7ea87e6a7c2c92599ed9d37fd22a477 | move some globals | mattsmart/biomodels,mattsmart/biomodels,mattsmart/biomodels | oncogenesis_dynamics/python/constants.py | oncogenesis_dynamics/python/constants.py | """
Comments
- current implementation for bifurcation along VALID_BIFURCATION_PARAMS only
- no stability calculation implemented (see matlab code for that)
Conventions
- params is 7-vector of the form: params[0] -> alpha_plus
params[1] -> alpha_minus
params[2] -> mu
params[3] -> a (usually normalized to 1)
params[4] -> b (b = 1 - delta)
params[5] -> c (c = 1 + s)
params[6] -> N
- if an element of params is specified as None then a bifurcation range will be be found and used
"""
PARAMS_DICT = {0: "bifurc_alpha_minus",
1: "bifurc_alpha_plus",
2: "bifurc_mu",
3: "bifurc_a",
4: "bifurc_b",
5: "bifurc_c",
6: "bifurc_N"}
VALID_BIFURCATION_PARAMS = ["bifurc_b"] # list of implemented bifurcation parameters
| mit | Python | |
f20c0b650da2354f3008c7a0933eb32a1409fbf0 | Add domain or and ilike | KarenKawaii/openacademy-project | openacademy/model/openacademy_session.py | openacademy/model/openacademy_session.py | # -*- coding: utf-8 -*-
from openerp import fields, models
class Session(models.Model):
_name = 'openacademy.session'
name = fields.Char(required=True)
start_date = fields.Date()
duration = fields.Float(digits=(6, 2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
instructor_id = fields.Many2one('res.partner', string="Instructor",
domain=['|',
("instructor","=",True),
("category_id.name", "ilike", "Teacher")
])
course_id = fields.Many2one('openacademy.course',
ondelete='cascade', string="Course", required=True)
attendee_ids = fields.Many2many('res.partner', string="Attendees")
| # -*- coding: utf-8 -*-
from openerp import fields, models
class Session(models.Model):
_name = 'openacademy.session'
name = fields.Char(required=True)
start_date = fields.Date()
duration = fields.Float(digits=(6, 2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
instructor_id = fields.Many2one('res.partner', string="Instructor")
course_id = fields.Many2one('openacademy.course',
ondelete='cascade', string="Course", required=True)
attendee_ids = fields.Many2many('res.partner', string="Attendees")
| apache-2.0 | Python |
42ef885c1da9f181608bc5d1715d09837a06db62 | Tag new release: 2.7.1 | Floobits/floobits-sublime,Floobits/floobits-sublime | floo/version.py | floo/version.py | PLUGIN_VERSION = '2.7.1'
# The line above is auto-generated by tag_release.py. Do not change it manually.
try:
from .common import shared as G
assert G
except ImportError:
from common import shared as G
G.__VERSION__ = '0.11'
G.__PLUGIN_VERSION__ = PLUGIN_VERSION
| PLUGIN_VERSION = '2.7.0'
# The line above is auto-generated by tag_release.py. Do not change it manually.
try:
from .common import shared as G
assert G
except ImportError:
from common import shared as G
G.__VERSION__ = '0.11'
G.__PLUGIN_VERSION__ = PLUGIN_VERSION
| apache-2.0 | Python |
da4a497e8cd73df40830388faedc589deff756c5 | Refactor to use the validation API. | back-to/streamlink,fishscene/streamlink,bastimeyer/streamlink,wlerin/streamlink,intact/livestreamer,Feverqwe/livestreamer,hmit/livestreamer,blxd/livestreamer,lyhiving/livestreamer,okaywit/livestreamer,hmit/livestreamer,jtsymon/livestreamer,wlerin/streamlink,melmorabity/streamlink,okaywit/livestreamer,gtmanfred/livestreamer,gravyboat/streamlink,beardypig/streamlink,back-to/streamlink,gravyboat/streamlink,derrod/livestreamer,sbstp/streamlink,intact/livestreamer,flijloku/livestreamer,chhe/livestreamer,ethanhlc/streamlink,gtmanfred/livestreamer,chrippa/livestreamer,bastimeyer/streamlink,streamlink/streamlink,programming086/livestreamer,ethanhlc/streamlink,mmetak/streamlink,javiercantero/streamlink,caorong/livestreamer,Klaudit/livestreamer,beardypig/streamlink,Masaz-/livestreamer,derrod/livestreamer,chhe/streamlink,flijloku/livestreamer,charmander/livestreamer,caorong/livestreamer,lyhiving/livestreamer,Klaudit/livestreamer,blxd/livestreamer,fishscene/streamlink,wolftankk/livestreamer,Dobatymo/livestreamer,javiercantero/streamlink,chhe/streamlink,programming086/livestreamer,Masaz-/livestreamer,mmetak/streamlink,jtsymon/livestreamer,sbstp/streamlink,chrippa/livestreamer,Dobatymo/livestreamer,streamlink/streamlink,Feverqwe/livestreamer,chhe/livestreamer,Saturn/livestreamer,melmorabity/streamlink,charmander/livestreamer,wolftankk/livestreamer,Saturn/livestreamer | src/livestreamer/plugins/chaturbate.py | src/livestreamer/plugins/chaturbate.py | import re
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http, validate
from livestreamer.stream import HLSStream
_url_re = re.compile("http://chaturbate.com/[^/?&]+")
_playlist_url_re = re.compile("html \+= \"src='(?P<url>[^']+)'\";")
_schema = validate.Schema(
validate.transform(_playlist_url_re.search),
validate.any(
None,
validate.all(
validate.get("url"),
validate.url(
scheme="http",
path=validate.endswith(".m3u8")
)
)
)
)
class Chaturbate(Plugin):
@classmethod
def can_handle_url(self, url):
return _url_re.match(url)
def _get_streams(self):
playlist_url = http.get(self.url, schema=_schema)
if not playlist_url:
return
return HLSStream.parse_variant_playlist(self.session, playlist_url)
__plugin__ = Chaturbate
| from livestreamer.exceptions import NoStreamsError
from livestreamer.plugin import Plugin
from livestreamer.stream import HLSStream
from livestreamer.plugin.api import http
import re
class Chaturbate(Plugin):
_reSrc = re.compile(r'html \+= \"src=\'([^\']+)\'\";')
@classmethod
def can_handle_url(self, url):
return "chaturbate.com" in url
def _get_streams(self):
res = http.get(self.url)
match = self._reSrc.search(res.text)
if not match:
raise NoStreamsError(self.url)
return HLSStream.parse_variant_playlist(self.session, match.group(1))
__plugin__ = Chaturbate
| bsd-2-clause | Python |
6288dac2fd91d41b27006ea7d546ed90a88e3b39 | Fix inheritance error | pysv/djep,EuroPython/djep,pysv/djep,EuroPython/djep,pysv/djep,EuroPython/djep,EuroPython/djep,pysv/djep,pysv/djep | pyconde/sponsorship/views.py | pyconde/sponsorship/views.py | # -*- encoding: utf-8 -*-
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.template.response import TemplateResponse
from django.utils.translation import ugettext_lazy as _
from django.views import generic as generic_views
from .forms import JobOfferForm
from .models import JobOffer, Sponsor
from .tasks import send_job_offer
class SendJobOffer(generic_views.FormView):
template_name = 'sponsorship/send_job_offer.html'
form_class = JobOfferForm
def dispatch(self, request, *args, **kwargs):
if not request.user.has_perm('sponsorship.add_joboffer'):
messages.error(request, _('You do not have permission to send job offers.'))
return HttpResponseRedirect('/')
return super(SendJobOffer, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
send_job_offer.delay(form.cleaned_data)
messages.success(self.request, _('Job offer sent'))
return HttpResponseRedirect(self.request.path)
send_job_offer_view = SendJobOffer.as_view()
def list_sponsors(request):
"""
This view lists all sponsors ordered by their level and name.
"""
sponsors = Sponsor.objects.filter(active=True) \
.select_related('level') \
.order_by('level__order', 'name') \
.all()
return TemplateResponse(
request=request,
context={
'sponsors': sponsors,
},
template='sponsorship/sponsor_list.html'
)
class JobOffersListView(generic_views.ListView):
model = JobOffer
def get_queryset(self):
qs = super(JobOffersListView, self).get_queryset()
return qs.filter(active=True).select_related('sponsor')
job_offers_list_view = JobOffersListView.as_view()
| # -*- encoding: utf-8 -*-
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.template.response import TemplateResponse
from django.utils.translation import ugettext_lazy as _
from django.views import generic as generic_views
from .forms import JobOfferForm
from .models import JobOffer, Sponsor
from .tasks import send_job_offer
class SendJobOffer(generic_views.FormView):
template_name = 'sponsorship/send_job_offer.html'
form_class = JobOfferForm
def dispatch(self, request, *args, **kwargs):
if not request.user.has_perm('sponsorship.add_joboffer'):
messages.error(request, _('You do not have permission to send job offers.'))
return HttpResponseRedirect('/')
return super(JobOffer, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
send_job_offer.delay(form.cleaned_data)
messages.success(self.request, _('Job offer sent'))
return HttpResponseRedirect(self.request.path)
send_job_offer_view = SendJobOffer.as_view()
def list_sponsors(request):
"""
This view lists all sponsors ordered by their level and name.
"""
sponsors = Sponsor.objects.filter(active=True) \
.select_related('level') \
.order_by('level__order', 'name') \
.all()
return TemplateResponse(
request=request,
context={
'sponsors': sponsors,
},
template='sponsorship/sponsor_list.html'
)
class JobOffersListView(generic_views.ListView):
model = JobOffer
def get_queryset(self):
qs = super(JobOffersListView, self).get_queryset()
return qs.filter(active=True).select_related('sponsor')
job_offers_list_view = JobOffersListView.as_view()
| bsd-3-clause | Python |
410207e4c0a091e7b4eca9cedd08f381095f50a9 | Revert "change from string to int" | PeerAssets/pypeerassets | pypeerassets/card_parsers.py | pypeerassets/card_parsers.py | '''parse cards according to deck issue mode'''
from .pautils import exponent_to_amount
def none_parser(cards):
'''parser for NONE [0] issue mode'''
return None
def custom_parser(cards, parser=None):
'''parser for CUSTOM [1] issue mode,
please provide your custom parser as argument'''
if not parser:
return cards
else:
return parser(cards)
def once_parser(cards):
'''parser for ONCE [2] issue mode'''
return [next(i for i in cards if i.type == "CardIssue")]
def multi_parser(cards):
'''parser for MULTI [4] issue mode'''
return cards
def mono_parser(cards):
'''parser for MONO [8] issue mode'''
return [i for i in cards if i.type == "CardIssue"
and exponent_to_amount(i.amount[0], i.number_of_decimals) == 1]
def unflushable_parser(cards):
'''parser for UNFLUSHABLE [16] issue mode'''
return [i for i in cards if i.type == "CardIssue"]
parsers = {
'NONE': none_parser,
'CUSTOM': none_parser,
'ONCE': once_parser,
'MULTI': multi_parser,
'MONO': mono_parser,
'UNFLUSHABLE': unflushable_parser
}
| '''parse cards according to deck issue mode'''
from .pautils import exponent_to_amount
def none_parser(cards):
'''parser for NONE [0] issue mode'''
return None
def custom_parser(cards, parser=None):
'''parser for CUSTOM [1] issue mode,
please provide your custom parser as argument'''
if not parser:
return cards
else:
return parser(cards)
def once_parser(cards):
'''parser for ONCE [2] issue mode'''
return [next(i for i in cards if i.type == "CardIssue")]
def multi_parser(cards):
'''parser for MULTI [4] issue mode'''
return cards
def mono_parser(cards):
'''parser for MONO [8] issue mode'''
return [i for i in cards if i.type == "CardIssue"
and exponent_to_amount(i.amount[0], i.number_of_decimals) == 1]
def unflushable_parser(cards):
'''parser for UNFLUSHABLE [16] issue mode'''
return [i for i in cards if i.type == "CardIssue"]
parsers = {
0: none_parser,
1: custom_parser,
2: once_parser,
4: multi_parser,
8: mono_parser,
16: unflushable_parser
}
| bsd-3-clause | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.