commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
60ee6a5d2ad9e85fefd973c020ef65bd212e687c
astrobin/management/commands/notify_new_blog_entry.py
astrobin/management/commands/notify_new_blog_entry.py
from django.core.management.base import BaseCommand from django.contrib.auth.models import User from zinnia.models import Entry from astrobin.notifications import push_notification class Command(BaseCommand): help = "Notifies all users about most recent blog entry." def handle(self, *args, **options): entry = Entry.objects.all()[0] push_notification( User.objects.all(), 'new_blog_entry', { 'object': entry.title, 'object_url': entry.get_absolute_url() } )
from django.core.management.base import BaseCommand from django.contrib.auth.models import User import persistent_messages from zinnia.models import Entry class Command(BaseCommand): help = "Notifies all users about most recent blog entry." def handle(self, *args, **options): entry = Entry.objects.all()[0] for u in User.objects.all(): m = persistent_messages.models.Message( user = u, from_user = User.objects.get(username = 'astrobin'), message = '<a href="' + entry.get_absolute_url() + '">New blog entry: <strong>' + entry.title + '</strong></a>', level = persistent_messages.INFO, ) m.save()
Fix management command to send notification about new blog post.
Fix management command to send notification about new blog post.
Python
agpl-3.0
astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin
1af1a7acface58cd8a6df5671d83b0a1a3ad4f3e
tiddlywebplugins/tiddlyspace/config.py
tiddlywebplugins/tiddlyspace/config.py
""" Base configuration for TiddlySpace. This provides the basics which may be changed in tidlywebconfig.py. """ from tiddlywebplugins.instancer.util import get_tiddler_locations from tiddlywebplugins.tiddlyspace.instance import store_contents PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace' config = { 'instance_tiddlers': get_tiddler_locations(store_contents, PACKAGE_NAME), 'atom.default_filter': 'select=tag:!excludeLists;sort=-modified;limit=20', 'auth_systems': ['cookie_form', 'tiddlywebplugins.tiddlyspace.openid'], 'bag_create_policy': 'ANY', 'recipe_create_policy': 'ANY', 'css_uri': '/bags/common/tiddlers/tiddlyweb.css', 'socialusers.reserved_names': ['www', 'about', 'help', 'announcements', 'dev', 'info', 'api', 'status', 'login', 'frontpage'], 'cookie_age': '2592000', # 1 month 'server_store': ['tiddlywebplugins.mysql', { 'db_config': 'mysql:///tiddlyspace?charset=utf8&use_unicode=0'}], 'indexer': 'tiddlywebplugins.mysql', }
""" Base configuration for TiddlySpace. This provides the basics which may be changed in tidlywebconfig.py. """ from tiddlywebplugins.instancer.util import get_tiddler_locations from tiddlywebplugins.tiddlyspace.instance import store_contents PACKAGE_NAME = 'tiddlywebplugins.tiddlyspace' config = { 'instance_tiddlers': get_tiddler_locations(store_contents, PACKAGE_NAME), 'atom.default_filter': 'select=tag:!excludeLists;sort=-modified;limit=20', 'auth_systems': ['cookie_form', 'tiddlywebplugins.tiddlyspace.openid'], 'bag_create_policy': 'ANY', 'recipe_create_policy': 'ANY', 'css_uri': '/bags/common/tiddlers/tiddlyweb.css', 'socialusers.reserved_names': ['www', 'about', 'help', 'announcements', 'dev', 'info', 'api', 'status', 'login', 'frontpage'], 'cookie_age': '2592000', # 1 month 'server_store': ['tiddlywebplugins.mysql', { 'db_config': 'mysql:///tiddlyspace?charset=utf8&use_unicode=0'}], 'indexer': 'tiddlywebplugins.mysql', 'tiddlywebwiki.binary_limit': 1048576, # 1MB }
Set the tiddlywebwiki binary limit to 1MB.
Set the tiddlywebwiki binary limit to 1MB.
Python
bsd-3-clause
FND/tiddlyspace,FND/tiddlyspace,TiddlySpace/tiddlyspace,FND/tiddlyspace,TiddlySpace/tiddlyspace,TiddlySpace/tiddlyspace
18f29b2b1a99614b09591df4a60c1670c845aa9b
students/crobison/session04/dict_lab.py
students/crobison/session04/dict_lab.py
# Charles Robison # 2016.10.18 # Dictionary and Set Lab # Create a dictionary containing “name”, “city”, and “cake” # for “Chris” from “Seattle” who likes “Chocolate”. d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'}
# Charles Robison # 2016.10.18 # Dictionary and Set Lab # Create a dictionary containing “name”, “city”, and “cake” # for “Chris” from “Seattle” who likes “Chocolate”. d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'} #Display the dictionary. d # Delete the entry for “cake”. del d['cake'] # Display the dictionary. d # Add an entry for “fruit” with “Mango” and display the dictionary. d['fruit'] = 'Mango' d # Display the dictionary keys. d.keys() # Display the dictionary values. d.values() # Display whether or not “cake” is a key in the dictionary # (i.e. False) (now). 'cake' in d # Display whether or not “Mango” is a value in the dictionary # (i.e. True). 'Mango' in d.values() # Using the dictionary from item 1: Make a dictionary using # the same keys but with the number of ‘t’s in each value. # Create sets s2, s3 and s4 that contain numbers from zero through # twenty, divisible 2, 3 and 4. # Display the sets. # Display if s3 is a subset of s2 (False) # and if s4 is a subset of s2 (True). # Create a set with the letters in ‘Python’ and add ‘i’ to the set. # Create a frozenset with the letters in ‘marathon’ # display the union and intersection of the two sets.
Add first set of exercises.
Add first set of exercises.
Python
unlicense
Baumelbi/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,Baumelbi/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016
c9b6387702baee3da0a3bca8b302b619e69893f7
steel/chunks/iff.py
steel/chunks/iff.py
import collections import io from steel.fields.numbers import BigEndian from steel import fields from steel.chunks import base __all__ = ['Chunk', 'Form'] class Chunk(base.Chunk): id = fields.String(size=4, encoding='ascii') size = fields.Integer(size=4, endianness=BigEndian) payload = base.Payload(size=size) class Form(base.Chunk, encoding='ascii'): tag = fields.FixedString('FORM') size = fields.Integer(size=4, endianness=BigEndian) id = fields.String(size=4) payload = base.Payload(size=size)
import collections import io from steel.fields.numbers import BigEndian from steel import fields from steel.chunks import base __all__ = ['Chunk', 'ChunkList', 'Form'] class Chunk(base.Chunk): id = fields.String(size=4, encoding='ascii') size = fields.Integer(size=4, endianness=BigEndian) payload = base.Payload(size=size) class ChunkList(base.ChunkList): def __init__(self, *args, **kwargs): # Just a simple override to default to a list of IFF chunks return super(ChunkList, self).__init__(Chunk, *args, **kwargs) class Form(base.Chunk, encoding='ascii'): tag = fields.FixedString('FORM') size = fields.Integer(size=4, endianness=BigEndian) id = fields.String(size=4) payload = base.Payload(size=size)
Customize a ChunkList just for IFF chunks
Customize a ChunkList just for IFF chunks
Python
bsd-3-clause
gulopine/steel
f7d4a3df11a67e3ae679b4c8f25780538c4c3c32
core/management/commands/send_tweets.py
core/management/commands/send_tweets.py
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5): user_tokens = tweet.user.social_auth.all()[0].tokens api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=user_tokens['oauth_token'], access_token_secret=user_tokens['oauth_token_secret'],) try: if tweet.media_path: status = api.PostMedia(tweet.text, tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trails += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save()
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5): user_tokens = tweet.user.social_auth.all()[0].tokens api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=user_tokens['oauth_token'], access_token_secret=user_tokens['oauth_token_secret'],) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trails += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save()
Use the newer PostUpdate instead of PostMedia
Use the newer PostUpdate instead of PostMedia
Python
agpl-3.0
osamak/student-portal,enjaz/enjaz,osamak/student-portal,enjaz/enjaz,enjaz/enjaz,osamak/student-portal,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz
70a40f50e9988fadfbc42f236881c1e3e78f40f1
icekit/project/settings/_test.py
icekit/project/settings/_test.py
from ._develop import * # DJANGO ###################################################################### DATABASES['default'].update({ 'TEST': { 'NAME': DATABASES['default']['NAME'], # See: https://docs.djangoproject.com/en/1.7/ref/settings/#serialize 'SERIALIZE': False, }, }) INSTALLED_APPS += ( 'fluent_pages.pagetypes.fluentpage', 'icekit.tests', ) ROOT_URLCONF = 'icekit.tests.urls' TEMPLATES_DJANGO['DIRS'].insert( 0, os.path.join(BASE_DIR, 'icekit', 'tests', 'templates')), # ICEKIT ###################################################################### # RESPONSE_PAGE_PLUGINS = ['ImagePlugin', ] # HAYSTACK #################################################################### # HAYSTACK_CONNECTIONS = { # 'default': { # 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', # }, # } # TRAVIS ###################################################################### if 'TRAVIS' in os.environ: NOSE_ARGS.remove('--with-progressive')
from ._base import * # DJANGO ###################################################################### ALLOWED_HOSTS = ('*', ) CSRF_COOKIE_SECURE = False # Don't require HTTPS for CSRF cookie SESSION_COOKIE_SECURE = False # Don't require HTTPS for session cookie DATABASES['default'].update({ 'TEST': { 'NAME': DATABASES['default']['NAME'], # See: https://docs.djangoproject.com/en/1.7/ref/settings/#serialize 'SERIALIZE': False, }, }) INSTALLED_APPS += ( 'fluent_pages.pagetypes.fluentpage', 'icekit.tests', ) ROOT_URLCONF = 'icekit.tests.urls' TEMPLATES_DJANGO['DIRS'].insert( 0, os.path.join(BASE_DIR, 'icekit', 'tests', 'templates')), # ICEKIT ###################################################################### # RESPONSE_PAGE_PLUGINS = ['ImagePlugin', ] # HAYSTACK #################################################################### # HAYSTACK_CONNECTIONS = { # 'default': { # 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', # }, # } # TRAVIS ###################################################################### if 'TRAVIS' in os.environ: NOSE_ARGS.remove('--with-progressive')
Extend base settings for test settings. Don't use live cache backend for tests.
Extend base settings for test settings. Don't use live cache backend for tests.
Python
mit
ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit
6c74e5c2bc08fd48af9e646dc911cff5e22064cb
django_performance_recorder/__init__.py
django_performance_recorder/__init__.py
# -*- coding:utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from .api import record # noqa: F401 __version__ = '1.0.0'
# -*- coding:utf-8 -*- """ isort:skip_file """ from __future__ import absolute_import, division, print_function, unicode_literals import six try: import pytest except ImportError: pytest = None if pytest is not None: if six.PY2: pytest.register_assert_rewrite(b'django_performance_recorder.api') else: pytest.register_assert_rewrite('django_performance_recorder.api') from .api import record # noqa: F401 __version__ = '1.0.0'
Make assert statement rich in pytest
Make assert statement rich in pytest
Python
mit
moumoutte/django-perf-rec,YPlan/django-perf-rec
89984eb5e9e8cdb8420ff1da07c54ce0dd265629
tests/test_git_pre_commit_hook_utils.py
tests/test_git_pre_commit_hook_utils.py
import git_pre_commit_hook_utils as utils def test_is_python_code_by_path(): file_at_index = utils.FileAtIndex( contents='', size=0, mode='', sha1='', status='', path='some/path/main.py', ) assert file_at_index.is_python_code() def test_is_python_code_by_contents(): file_at_index = utils.FileAtIndex( contents='#!/usr/bin/env/python\nprint "hello"\n', size=0, mode='', sha1='', status='', path='some/path/python_script', ) assert file_at_index.is_python_code() def test_is_not_python_code(): file_at_index = utils.FileAtIndex( contents='some text with python\n', size=0, mode='', sha1='', status='', path='some/path/not_python_script.cpp', ) assert not file_at_index.is_python_code()
import git_pre_commit_hook_utils as utils import scripttest import os import copy def test_with_empty_repo(tmpdir): os_environ = copy.deepcopy(os.environ) os_environ['GIT_DIR'] = str(tmpdir) os_environ['GIT_WORK_TREE'] = str(tmpdir) env = scripttest.TestFileEnvironment( str(tmpdir), start_clear=False, template_path='data', environ=os_environ, ) env.writefile('empty_file', content='') env.run('git', 'init') env.run('git', 'add', 'empty_file') files_staged_for_commit = list(utils.files_staged_for_commit()) assert len(files_staged_for_commit) == 1 file_at_index = files_staged_for_commit[0] assert file_at_index.path == 'empty_file' assert file_at_index.contents == '' assert file_at_index.size == 0 assert file_at_index.status == 'A' def test_is_python_code_by_path(): file_at_index = utils.FileAtIndex( contents='', size=0, mode='', sha1='', status='', path='some/path/main.py', ) assert file_at_index.is_python_code() def test_is_python_code_by_contents(): file_at_index = utils.FileAtIndex( contents='#!/usr/bin/env/python\nprint "hello"\n', size=0, mode='', sha1='', status='', path='some/path/python_script', ) assert file_at_index.is_python_code() def test_is_not_python_code(): file_at_index = utils.FileAtIndex( contents='some text with python\n', size=0, mode='', sha1='', status='', path='some/path/not_python_script.cpp', ) assert not file_at_index.is_python_code()
Add test for commit to empty repo case
Add test for commit to empty repo case
Python
mit
evvers/git-pre-commit-hook-utils
30a173da5850a457393cfdf47b7c0db303cdd2e9
tests/test_utils.py
tests/test_utils.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}} assert utils.merge_dict(dict1, dict2) == expected def test_import_string(): utils.import_string('cihai') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai2')
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'welcome': 2}} assert utils.merge_dict(dict1, dict2) == expected def test_import_string(): utils.import_string('cihai') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai.core.nonexistingimport') with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)): utils.import_string('cihai2')
Test importing of module with unexisting target inside
Test importing of module with unexisting target inside There's a coverage case where a module exists, but what's inside it isn't covered.
Python
mit
cihai/cihai-python,cihai/cihai,cihai/cihai
fc259061ccf048af7e657888eb655da120a6606f
panoptes/test/mount/test_ioptron.py
panoptes/test/mount/test_ioptron.py
from nose.tools import raises import panoptes from panoptes.mount.ioptron import Mount class TestIOptron(): @raises(AssertionError) def test_no_config_no_commands(self): """ Mount needs a config """ mount = Mount() @raises(AssertionError) def test_config_bad_commands(self): """ Passes in a default config but blank commands, which should error """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }, commands={'foo': 'bar'}) def test_config_auto_commands(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) def test_default_settings(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) assert mount.is_connected is False assert mount.is_initialized is False assert mount.is_slewing is False
import nose.tools import panoptes from panoptes.mount.ioptron import Mount class TestIOptron(): @nose.tools.raises(AssertionError) def test_no_config_no_commands(self): """ Mount needs a config """ mount = Mount() @nose.tools.raises(AssertionError) def test_config_bad_commands(self): """ Passes in a default config but blank commands, which should error """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }, commands={'foo': 'bar'}) def test_config_auto_commands(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) def test_default_settings(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) assert mount.is_connected is False assert mount.is_initialized is False assert mount.is_slewing is False def test_port_set(self): """ Passes in config like above, but no commands, so they should read from defaults """ mount = Mount(config={'mount': { 'model': 'ioptron', 'port':'/dev/ttyUSB0' } }) nose.tools.ok_(mount.port == '/dev/ttyUSB0')
Use nose.tools explicitly; test for port
Use nose.tools explicitly; test for port
Python
mit
fmin2958/POCS,Guokr1991/POCS,joshwalawender/POCS,panoptes/POCS,joshwalawender/POCS,panoptes/POCS,panoptes/POCS,Guokr1991/POCS,fmin2958/POCS,AstroHuntsman/POCS,AstroHuntsman/POCS,joshwalawender/POCS,AstroHuntsman/POCS,Guokr1991/POCS,panoptes/POCS,fmin2958/POCS,Guokr1991/POCS,AstroHuntsman/POCS
d448367d68e37c2d719063b8ec2ce543fec5b5e7
sphinxcontrib/reviewbuilder/__init__.py
sphinxcontrib/reviewbuilder/__init__.py
# -*- coding: utf-8 -*- """ sphinxcontrib-reviewbuilder ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2013 by the WAKAYAMA Shirou :license: LGPLv2, see LICENSE for details. """ from __future__ import absolute_import from docutils.nodes import Text, paragraph from sphinxcontrib.reviewbuilder.reviewbuilder import ReVIEWBuilder # from japanesesupport.py def trunc_whitespace(app, doctree, docname): for node in doctree.traverse(Text): if isinstance(node.parent, paragraph): newtext = node.astext() for c in "\n\r\t": newtext = newtext.replace(c, "") newtext = newtext.strip() node.parent.replace(node, Text(newtext)) def setup(app): app.add_builder(ReVIEWBuilder) app.connect("doctree-resolved", trunc_whitespace)
# -*- coding: utf-8 -*- """ sphinxcontrib-reviewbuilder ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2013 by the WAKAYAMA Shirou :license: LGPLv2, see LICENSE for details. """ from __future__ import absolute_import from docutils import nodes from sphinxcontrib.reviewbuilder.reviewbuilder import ReVIEWBuilder # from japanesesupport.py def trunc_whitespace(app, doctree, docname): for node in doctree.traverse(nodes.Text): if isinstance(node.parent, nodes.paragraph): newtext = node.astext() for c in "\n\r\t": newtext = newtext.replace(c, "") newtext = newtext.strip() node.parent.replace(node, nodes.Text(newtext)) def setup(app): app.add_builder(ReVIEWBuilder) app.connect("doctree-resolved", trunc_whitespace)
Access docutils standard nodes through nodes.*
Access docutils standard nodes through nodes.*
Python
lgpl-2.1
shirou/sphinxcontrib-reviewbuilder
f2f77cd326c3b121eb7e6e53dfcab3964f473451
fileupload/models.py
fileupload/models.py
from django.db import models class Picture(models.Model): file = models.ImageField(upload_to="pictures") slug = models.SlugField(max_length=50, blank=True) def __unicode__(self): return self.file @models.permalink def get_absolute_url(self): return ('upload-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs)
from django.db import models class Picture(models.Model): # This is a small demo using FileField instead of ImageField, not # depending on PIL. You will probably want ImageField in your app. file = models.FileField(upload_to="pictures") slug = models.SlugField(max_length=50, blank=True) def __unicode__(self): return self.file @models.permalink def get_absolute_url(self): return ('upload-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs)
Use FileField instead of ImageField, we don't need PIL in this demo.
Use FileField instead of ImageField, we don't need PIL in this demo.
Python
mit
extremoburo/django-jquery-file-upload,indrajithi/mgc-django,Imaginashion/cloud-vision,madteckhead/django-jquery-file-upload,sigurdga/django-jquery-file-upload,vaniakov/django-jquery-file-upload,extremoburo/django-jquery-file-upload,sigurdga/django-jquery-file-upload,Imaginashion/cloud-vision,Imaginashion/cloud-vision,madteckhead/django-jquery-file-upload,Imaginashion/cloud-vision,Imaginashion/cloud-vision,indrajithi/mgc-django,extremoburo/django-jquery-file-upload,sigurdga/django-jquery-file-upload,Imaginashion/cloud-vision,minhlongdo/django-jquery-file-upload,vaniakov/django-jquery-file-upload,minhlongdo/django-jquery-file-upload,vaniakov/django-jquery-file-upload,minhlongdo/django-jquery-file-upload
72c9a00d691b2b91bf39e1f5bdd1ef2358d8d671
updateCollection.py
updateCollection.py
from DataObjects.Collection import Collection from ObjectFactories.ItemFactory import ItemFactory import json def main(): updateCollection( Collection('item','Items', 'agarner', []), ItemFactory.factory('item', [0, 'someItem', 'date', 'date']), 'collections/agarner_collections/agarner_Item_collection.dat' ) def getCollection(fileName): collectionFile = open(fileName, 'r') fileData = json.loads(collectionFile.read()) itemData = fileData['items'] itemArr = [] for value in itemData: item = ItemFactory.factory( fileData['collectionType'], value.values() ) itemArr.append(item) collection = Collection(fileData['collectionType'], fileData['collectionName'], fileData['username'], itemArr) for item in collection.items: print(item.id) def updateCollection(collection, item, fileName): collection.items.append(item) getCollection(fileName) if __name__ == '__main__': main()
from DataObjects.Collection import Collection from ObjectFactories.ItemFactory import ItemFactory from collections import OrderedDict import json def main(): updateCollection( Collection('item','Items', 'agarner', []), ItemFactory.factory('item', [0, 'someItem', 'date', 'date']), 'collections/TestUser_collections/TestUser_album_collection.dat' ) def getCollection(fileName): collectionFile = open(fileName, 'r') fileData = json.loads(collectionFile.read()) collectionType = fileData['collectionType'] collectionName = fileData['collectionName'] username = fileData['username'] itemData = fileData['items'] itemArr = [] for value in itemData: if fileData['collectionType'] == 'item': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit']]) itemArr.append(item) elif fileData['collectionType'] == 'album': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit'], value['artist']]) itemArr.append(item) elif fileData['collectionType'] == 'book': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit'], value['author']]) itemArr.append(item) elif fileData['collectionType'] == 'movie': item = ItemFactory.factory(collectionType,[value['id'], value['name'], value['addedOn'], value['lastEdit'], value['director']]) itemArr.append(item) collection = Collection(fileData['collectionType'], fileData['collectionName'], fileData['username'], itemArr) print collection.collectionType print collection.collectionName print collection.username print collection.items def updateCollection(collection, item, fileName): collection.items.append(item) getCollection(fileName) if __name__ == '__main__': main()
Implement base json extraction to collection functionality
Implement base json extraction to collection functionality
Python
apache-2.0
AmosGarner/PyInventory
e6fb5ba043c2db08cbacb119664297b3f3668517
fluent_comments/forms/_captcha.py
fluent_comments/forms/_captcha.py
from django.core.exceptions import ImproperlyConfigured try: from captcha.fields import ReCaptchaField as CaptchaField except ImportError: try: from captcha.fields import CaptchaField except ImportError: raise ImportError( "To use the captcha contact form, you need to have " "django-recaptcha or django-simple-captcha installed." ) class CaptchaFormMixin(object): def _reorder_fields(self, ordering): """ Test that the 'captcha' field is really present. This could be broken by a bad FLUENT_COMMENTS_FIELD_ORDER configuration. """ if 'captcha' not in ordering: raise ImproperlyConfigured( "When using 'FLUENT_COMMENTS_FIELD_ORDER', " "make sure the 'captcha' field included too to use '{}' form. ".format( self.__class__.__name__ ) ) super(CaptchaFormMixin, self)._reorder_fields(ordering) # Avoid making captcha required for previews. if self.is_preview: self.fields.pop('captcha')
from django.core.exceptions import ImproperlyConfigured class CaptchaFormMixin(object): def _reorder_fields(self, ordering): """ Test that the 'captcha' field is really present. This could be broken by a bad FLUENT_COMMENTS_FIELD_ORDER configuration. """ if 'captcha' not in ordering: raise ImproperlyConfigured( "When using 'FLUENT_COMMENTS_FIELD_ORDER', " "make sure the 'captcha' field included too to use '{}' form. ".format( self.__class__.__name__ ) ) super(CaptchaFormMixin, self)._reorder_fields(ordering) # Avoid making captcha required for previews. if self.is_preview: self.fields.pop('captcha')
Fix duplicate captcha import check
Fix duplicate captcha import check
Python
apache-2.0
django-fluent/django-fluent-comments,django-fluent/django-fluent-comments,edoburu/django-fluent-comments,django-fluent/django-fluent-comments,django-fluent/django-fluent-comments,edoburu/django-fluent-comments,edoburu/django-fluent-comments
7f1ddec9e170941e3a5159236ede817c2d569f38
graphical_tests/test_partition.py
graphical_tests/test_partition.py
""" Draw a solid circle off center in a blank image. Use the same array as both the image and the mask. The tiles should subdivide along the curved edge to trace out a smooth circle. """ from skimage import draw import matplotlib.pyplot as plt import numpy as np import photomosaic as pm img = np.zeros((1000, 1000)) rr, cc = draw.circle(300, 500, 150) img[rr, cc] = 1 tiles = pm.partition(img, (10, 10), mask=img.astype(bool), depth=3) plt.imshow(pm.draw_tiles(img, tiles, color=0.5)) plt.savefig('test-partition.png')
""" Draw a solid circle off center in a blank image. Use the same array as both the image and the mask. The tiles should subdivide along the curved edge to trace out a smooth circle. """ from skimage import draw import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import photomosaic as pm img = np.zeros((1000, 1000)) rr, cc = draw.circle(300, 500, 150) img[rr, cc] = 1 tiles = pm.partition(img, (10, 10), mask=img.astype(bool), depth=3) plt.imshow(pm.draw_tile_layout(img, tiles, color=0.5)) plt.savefig('test-partition.png')
Update test to match API.
TST: Update test to match API.
Python
bsd-3-clause
danielballan/photomosaic
8e1e6624fb9120b3f26ac373dc48e877240cccac
bootcamp/lesson5.py
bootcamp/lesson5.py
import datetime import csv # Question 1 # ---------- # Using the csv data file users.csv aggregate app users as well as registration date by month. The count of app # users should be one dictionary while the count of registration month should be another dictionary. There will be # no checking or test harness so simply print your results to the console. # Example: # d1 = { # 'RECEIPT_HOG': 3325, # 'SHOPAROO': 38, # 'RECEIPT_LOTTERY': 820, # 'RECEIPT_BIN': 3208 # } # d2 = { # 'Jan': 3852, # 'Feb': 38525, # etc... # } def bigdata(): # Write code here pass def main(): bigdata() if __name__ == '__main__': main()
import datetime import csv # Question 1 # ---------- # Using the csv data file users.csv aggregate app users as well as registration date by month. The count of app # users should be one dictionary while the count of registration month should be another dictionary. There will be # no checking or test harness so simply print your results to the console in the display_results function. # Example: # d1 = { # 'RECEIPT_HOG': 3325, # 'SHOPAROO': 38, # 'RECEIPT_LOTTERY': 820, # 'RECEIPT_BIN': 3208 # } # d2 = { # 'Jan': 3852, # 'Feb': 38525, # etc... # } def bigdata(): # Write code here pass def display_results(d1, d2): # Write code here pass def main(): bigdata() if __name__ == '__main__': main()
Add print function to demonstrate func calling
Add print function to demonstrate func calling
Python
mit
infoscout/python-bootcamp-pv
17ffc13ba4a5eab56b66b8fe144cc53e8d02d961
easyedit/TextArea.py
easyedit/TextArea.py
from PyQt5.Qsci import QsciScintilla, QsciLexerPython class TextArea(QsciScintilla): def __init__(self): super().__init__() self.filePath = "Untitled" self.pythonLexer = QsciLexerPython(self) self.setLexer(self.pythonLexer) self.setMargins(1) self.setMarginType(0, QsciScintilla.NumberMargin) self.setUtf8(True) self.setIndentationsUseTabs(False) self.setTabWidth(4) self.setIndentationGuides(False) self.setAutoIndent(True) def changeMarginWidth(self): numLines = self.lines() print(len(str(numLines))) self.setMarginWidth(0, "00" * len(str(numLines))) def updateFont(self, newFont): self.lexer().setFont(newFont)
from PyQt5.Qsci import QsciScintilla, QsciLexerPython class TextArea(QsciScintilla): def __init__(self): super().__init__() self.filePath = "Untitled" self.pythonLexer = QsciLexerPython(self) self.setLexer(self.pythonLexer) self.setMargins(1) self.setMarginType(0, QsciScintilla.NumberMargin) self.setUtf8(True) self.setIndentationsUseTabs(False) self.setTabWidth(4) self.setIndentationGuides(False) self.setAutoIndent(True) def changeMarginWidth(self): numLines = self.lines() self.setMarginWidth(0, "00" * len(str(numLines))) def updateFont(self, newFont): self.lexer().setFont(newFont)
Remove debugging print statement from changeMarginWidth
Remove debugging print statement from changeMarginWidth
Python
mit
msklosak/EasyEdit
3f5b1e830eff73cdff013a423b647c795e21bef2
captcha/fields.py
captcha/fields.py
from django.conf import settings from django import forms from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ from recaptcha.client import captcha from captcha.widgets import ReCaptcha class ReCaptchaField(forms.CharField): default_error_messages = { 'captcha_invalid': _(u'Invalid captcha') } def __init__(self, *args, **kwargs): self.widget = ReCaptcha self.required = True super(ReCaptchaField, self).__init__(*args, **kwargs) def __init__(self, *args, **kwargs): self.widget = ReCaptcha self.required = True super(ReCaptchaField, self).__init__(*args, **kwargs) def clean(self, values): super(ReCaptchaField, self).clean(values[1]) recaptcha_challenge_value = smart_unicode(values[0]) recaptcha_response_value = smart_unicode(values[1]) check_captcha = captcha.submit(recaptcha_challenge_value, recaptcha_response_value, settings.RECAPTCHA_PRIVATE_KEY, {}) if self.required and not check_captcha.is_valid: raise forms.util.ValidationError( self.error_messages['captcha_invalid']) return values[0]
from django.conf import settings from django import forms from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ from recaptcha.client import captcha from captcha.widgets import ReCaptcha class ReCaptchaField(forms.CharField): default_error_messages = { 'captcha_invalid': _(u'Invalid captcha') } def __init__(self, *args, **kwargs): self.widget = ReCaptcha self.required = True super(ReCaptchaField, self).__init__(*args, **kwargs) def __init__(self, *args, **kwargs): self.widget = ReCaptcha self.required = True super(ReCaptchaField, self).__init__(*args, **kwargs) def clean(self, values): super(ReCaptchaField, self).clean(values[1]) recaptcha_challenge_value = smart_unicode(values[0]) recaptcha_response_value = smart_unicode(values[1]) check_captcha = captcha.submit(recaptcha_challenge_value, recaptcha_response_value, settings.RECAPTCHA_PRIVATE_KEY, {}) if not check_captcha.is_valid: raise forms.util.ValidationError( self.error_messages['captcha_invalid']) return values[0]
Revert "Enforce valid captcha only if required, so tests can relax captcha requirement"
Revert "Enforce valid captcha only if required, so tests can relax captcha requirement" This reverts commit c3c450b1a7070a1dd1b808e55371e838dd297857. It wasn't such a great idea.
Python
bsd-3-clause
mozilla/django-recaptcha
b48984747d0f33f8ad9a8721bf7489d8ff97c157
matador/commands/deploy_ticket.py
matador/commands/deploy_ticket.py
#!/usr/bin/env python from .command import Command from matador import utils class DeployTicket(Command): def _add_arguments(self, parser): parser.prog = 'matador deploy-ticket' parser.add_argument( '-e', '--environment', type=str, required=True, help='Agresso environment name') def _execute(self): project = utils.project() utils.update_repository(project)
#!/usr/bin/env python from .command import Command from matador import utils class DeployTicket(Command): def _add_arguments(self, parser): parser.prog = 'matador deploy-ticket' parser.add_argument( '-e', '--environment', type=str, required=True, help='Agresso environment name') parser.add_argument( '-', '--package', type=bool, default=False, help='Agresso environment name') def _execute(self): project = utils.project() if not self.args.package: utils.update_repository(project)
Add package argument to deploy-ticket
Add package argument to deploy-ticket
Python
mit
Empiria/matador
f6ce19f558bd298a6f0651ead865b65da3a2c479
spiff/sensors/tests.py
spiff/sensors/tests.py
from django.test import TestCase from spiff.api.tests import APITestMixin, withPermission import models class SensorTest(APITestMixin): def setUp(self): self.setupAPI() self.sensor = models.Sensor.objects.create( name = 'sensor', description = 'Test sensor', type = 0, ttl = 255 ) @withPermission('sensors.read_sensor') @withPermission('sensors.update_value_on_sensor') def testSetSensorValue(self): self.patchAPI('/v1/sensor/%s/'%(self.sensor.id), { 'value': True, }) self.assertEqual(self.sensor.value(), 'True') self.patchAPI('/v1/sensor/%s/'%(self.sensor.id), { 'value': False, }) self.assertEqual(self.sensor.value(), 'False') def testSensorTTL(self): for i in range(0, self.sensor.ttl*2): models.SensorValue.objects.create( sensor=self.sensor, value=True ) self.assertEqual(len(self.sensor.values.all()), self.sensor.ttl)
from django.test import TestCase from spiff.api.tests import APITestMixin, withPermission import models class SensorTest(APITestMixin): def setUp(self): self.setupAPI() self.sensor = models.Sensor.objects.create( name = 'sensor', description = 'Test sensor', type = models.SENSOR_TYPE_BOOLEAN, ttl = 255 ) @withPermission('sensors.read_sensor') @withPermission('sensors.update_value_on_sensor') def testSetSensorValue(self): self.patchAPI('/v1/sensor/%s/'%(self.sensor.id), { 'value': True, }) sensor = self.getAPI('/v1/sensor/%s/'%(self.sensor.id)) self.assertEqual(sensor['value'], True) self.patchAPI('/v1/sensor/%s/'%(self.sensor.id), { 'value': False, }) sensor = self.getAPI('/v1/sensor/%s/'%(self.sensor.id)) self.assertEqual(sensor['value'], False) def testSensorTTL(self): for i in range(0, self.sensor.ttl*2): models.SensorValue.objects.create( sensor=self.sensor, value=True ) self.assertEqual(len(self.sensor.values.all()), self.sensor.ttl)
Use a bool sensor for testing, and query the API instead of models
Use a bool sensor for testing, and query the API instead of models
Python
agpl-3.0
SYNHAK/spiff,SYNHAK/spiff,SYNHAK/spiff
600fe835ddce18a6aec5702766350003f2f90745
gen-android-icons.py
gen-android-icons.py
__author__ = 'Maksim Dmitriev' import argparse if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--foo', help='foo help', required=True) args = parser.parse_args()
__author__ = 'Maksim Dmitriev' import argparse import os if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-s', '--source', help='the icon to be resized', required=True) parser.add_argument('-d', '--dest', help='the directory where resized icons are saved') parser.add_argument('-f', '--outfile', help='the output file names') args = parser.parse_args() source_image = args.source dest_dir = args.dest if dest_dir is None: os.makedirs(os.path.dirname(os.path.realpath(source_image)) + os.sep + 'out', exist_ok=True)
Create an output directory unless it exists
Create an output directory unless it exists
Python
bsd-3-clause
MaksimDmitriev/Python-Scripts
a52039c139e0d5b1c5fedb1dfb160e2c9b9387b3
teuthology/task/tests/test_locking.py
teuthology/task/tests/test_locking.py
import pytest class TestLocking(object): def test_correct_os_type(self, ctx, config): os_type = ctx.config.get("os_type") if os_type is None: pytest.skip('os_type was not defined') for remote in ctx.cluster.remotes.iterkeys(): assert remote.os.name == os_type def test_correct_os_version(self, ctx, config): os_version = ctx.config.get("os_version") if os_version is None: pytest.skip('os_version was not defined') for remote in ctx.cluster.remotes.iterkeys(): assert remote.os.version == os_version def test_correct_machine_type(self, ctx, config): machine_type = ctx.machine_type for remote in ctx.cluster.remotes.iterkeys(): assert remote.machine_type in machine_type
import pytest class TestLocking(object): def test_correct_os_type(self, ctx, config): os_type = ctx.config.get("os_type") if os_type is None: pytest.skip('os_type was not defined') for remote in ctx.cluster.remotes.iterkeys(): assert remote.os.name == os_type def test_correct_os_version(self, ctx, config): os_version = ctx.config.get("os_version") if os_version is None: pytest.skip('os_version was not defined') if ctx.config.get("os_type") == "debian": pytest.skip('known issue with debian versions; see: issue #10878') for remote in ctx.cluster.remotes.iterkeys(): assert remote.os.version == os_version def test_correct_machine_type(self, ctx, config): machine_type = ctx.machine_type for remote in ctx.cluster.remotes.iterkeys(): assert remote.machine_type in machine_type
Make an exception for debian in tests.test_correct_os_version
Make an exception for debian in tests.test_correct_os_version This is because of a known issue where downburst gives us 7.1 when we ask for 7.0. We're ok with this behavior for now. See: issue #10878 Signed-off-by: Andrew Schoen <1bb641dc23c3a93cce4eee683bcf4b2bea7903a3@redhat.com>
Python
mit
SUSE/teuthology,yghannam/teuthology,dmick/teuthology,caibo2014/teuthology,dreamhost/teuthology,caibo2014/teuthology,t-miyamae/teuthology,ivotron/teuthology,SUSE/teuthology,ceph/teuthology,ivotron/teuthology,ktdreyer/teuthology,SUSE/teuthology,dmick/teuthology,t-miyamae/teuthology,robbat2/teuthology,zhouyuan/teuthology,ceph/teuthology,dmick/teuthology,michaelsevilla/teuthology,dreamhost/teuthology,zhouyuan/teuthology,robbat2/teuthology,ktdreyer/teuthology,yghannam/teuthology,michaelsevilla/teuthology
65d2a5f08ee96e80752362f7545167888599819e
website/addons/figshare/exceptions.py
website/addons/figshare/exceptions.py
from website.util.sanitize import escape_html from website.addons.base.exceptions import AddonEnrichmentError class FigshareIsDraftError(AddonEnrichmentError): def __init__(self, file_guid): self.file_guid = file_guid @property def renderable_error(self): return ''' <div class="alert alert-info" role="alert"> The file "{name}" is still a draft on Figshare. <br> To view it on the OSF <a href="http://figshare.com/faqs">publish</a> it on Figshare. </div> '''.format(name=escape_html(self.file_guid.name))
from website.util.sanitize import escape_html from website.addons.base.exceptions import AddonEnrichmentError class FigshareIsDraftError(AddonEnrichmentError): def __init__(self, file_guid): self.file_guid = file_guid @property def can_delete(self): return True @property def renderable_error(self): return ''' <div class="alert alert-info" role="alert"> The file "{name}" is still a draft on Figshare. <br> To view it on the OSF <a href="http://figshare.com/faqs">publish</a> it on Figshare. </div> '''.format(name=escape_html(self.file_guid.name))
Allow deletion of figshare drafts
Allow deletion of figshare drafts
Python
apache-2.0
zachjanicki/osf.io,DanielSBrown/osf.io,njantrania/osf.io,kushG/osf.io,erinspace/osf.io,GaryKriebel/osf.io,wearpants/osf.io,chrisseto/osf.io,samchrisinger/osf.io,caneruguz/osf.io,petermalcolm/osf.io,doublebits/osf.io,arpitar/osf.io,cldershem/osf.io,Nesiehr/osf.io,amyshi188/osf.io,brandonPurvis/osf.io,mluo613/osf.io,pattisdr/osf.io,mluo613/osf.io,RomanZWang/osf.io,bdyetton/prettychart,KAsante95/osf.io,HalcyonChimera/osf.io,caneruguz/osf.io,Johnetordoff/osf.io,dplorimer/osf,Nesiehr/osf.io,jinluyuan/osf.io,ZobairAlijan/osf.io,samanehsan/osf.io,danielneis/osf.io,samanehsan/osf.io,brandonPurvis/osf.io,samanehsan/osf.io,adlius/osf.io,himanshuo/osf.io,alexschiller/osf.io,jinluyuan/osf.io,jnayak1/osf.io,CenterForOpenScience/osf.io,mluo613/osf.io,kch8qx/osf.io,erinspace/osf.io,zamattiac/osf.io,haoyuchen1992/osf.io,reinaH/osf.io,pattisdr/osf.io,alexschiller/osf.io,ckc6cz/osf.io,mluo613/osf.io,aaxelb/osf.io,njantrania/osf.io,TomBaxter/osf.io,mfraezz/osf.io,RomanZWang/osf.io,kwierman/osf.io,mluke93/osf.io,icereval/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,kushG/osf.io,KAsante95/osf.io,mfraezz/osf.io,chennan47/osf.io,acshi/osf.io,MerlinZhang/osf.io,ZobairAlijan/osf.io,Ghalko/osf.io,icereval/osf.io,Nesiehr/osf.io,cwisecarver/osf.io,DanielSBrown/osf.io,rdhyee/osf.io,ticklemepierce/osf.io,zamattiac/osf.io,CenterForOpenScience/osf.io,samchrisinger/osf.io,haoyuchen1992/osf.io,acshi/osf.io,asanfilippo7/osf.io,jnayak1/osf.io,zachjanicki/osf.io,DanielSBrown/osf.io,lyndsysimon/osf.io,cwisecarver/osf.io,fabianvf/osf.io,asanfilippo7/osf.io,baylee-d/osf.io,monikagrabowska/osf.io,kch8qx/osf.io,lamdnhan/osf.io,HarryRybacki/osf.io,reinaH/osf.io,lyndsysimon/osf.io,ZobairAlijan/osf.io,monikagrabowska/osf.io,saradbowman/osf.io,alexschiller/osf.io,cslzchen/osf.io,bdyetton/prettychart,hmoco/osf.io,caseyrollins/osf.io,billyhunt/osf.io,erinspace/osf.io,GaryKriebel/osf.io,MerlinZhang/osf.io,cldershem/osf.io,HarryRybacki/osf.io,binoculars/osf.io,revanthkolli/osf.io,brandonPurvis/osf.io,billyhunt/osf.io,brianjgeiger/osf.io,sbt9uc/osf.io,felliott/osf.io,doublebits/osf.io,rdhyee/osf.io,Ghalko/osf.io,billyhunt/osf.io,crcresearch/osf.io,sbt9uc/osf.io,caseyrollins/osf.io,KAsante95/osf.io,KAsante95/osf.io,wearpants/osf.io,TomBaxter/osf.io,HarryRybacki/osf.io,haoyuchen1992/osf.io,zamattiac/osf.io,felliott/osf.io,Johnetordoff/osf.io,jeffreyliu3230/osf.io,petermalcolm/osf.io,danielneis/osf.io,brianjgeiger/osf.io,SSJohns/osf.io,hmoco/osf.io,hmoco/osf.io,billyhunt/osf.io,alexschiller/osf.io,baylee-d/osf.io,aaxelb/osf.io,jeffreyliu3230/osf.io,zachjanicki/osf.io,DanielSBrown/osf.io,crcresearch/osf.io,TomHeatwole/osf.io,mluke93/osf.io,kch8qx/osf.io,njantrania/osf.io,binoculars/osf.io,ckc6cz/osf.io,billyhunt/osf.io,chennan47/osf.io,GaryKriebel/osf.io,leb2dg/osf.io,cosenal/osf.io,TomBaxter/osf.io,cosenal/osf.io,barbour-em/osf.io,Ghalko/osf.io,SSJohns/osf.io,zkraime/osf.io,icereval/osf.io,TomHeatwole/osf.io,HalcyonChimera/osf.io,samchrisinger/osf.io,cslzchen/osf.io,cwisecarver/osf.io,mattclark/osf.io,rdhyee/osf.io,haoyuchen1992/osf.io,caneruguz/osf.io,chrisseto/osf.io,chrisseto/osf.io,GageGaskins/osf.io,laurenrevere/osf.io,barbour-em/osf.io,himanshuo/osf.io,wearpants/osf.io,RomanZWang/osf.io,barbour-em/osf.io,monikagrabowska/osf.io,MerlinZhang/osf.io,TomHeatwole/osf.io,zkraime/osf.io,SSJohns/osf.io,crcresearch/osf.io,jinluyuan/osf.io,sloria/osf.io,revanthkolli/osf.io,laurenrevere/osf.io,HalcyonChimera/osf.io,CenterForOpenScience/osf.io,arpitar/osf.io,petermalcolm/osf.io,hmoco/osf.io,GaryKriebel/osf.io,caseyrygt/osf.io,felliott/osf.io,bdyetton/prettychart,ckc6cz/osf.io,danielneis/osf.io,binoculars/osf.io,ckc6cz/osf.io,samanehsan/osf.io,aaxelb/osf.io,jnayak1/osf.io,mluke93/osf.io,KAsante95/osf.io,arpitar/osf.io,saradbowman/osf.io,Johnetordoff/osf.io,asanfilippo7/osf.io,RomanZWang/osf.io,Ghalko/osf.io,doublebits/osf.io,fabianvf/osf.io,pattisdr/osf.io,jnayak1/osf.io,emetsger/osf.io,fabianvf/osf.io,sloria/osf.io,kch8qx/osf.io,laurenrevere/osf.io,jolene-esposito/osf.io,rdhyee/osf.io,revanthkolli/osf.io,jmcarp/osf.io,jolene-esposito/osf.io,lamdnhan/osf.io,jeffreyliu3230/osf.io,caseyrygt/osf.io,doublebits/osf.io,dplorimer/osf,abought/osf.io,danielneis/osf.io,emetsger/osf.io,sbt9uc/osf.io,adlius/osf.io,njantrania/osf.io,cslzchen/osf.io,cwisecarver/osf.io,mattclark/osf.io,HarryRybacki/osf.io,jolene-esposito/osf.io,barbour-em/osf.io,cosenal/osf.io,zachjanicki/osf.io,monikagrabowska/osf.io,jolene-esposito/osf.io,caseyrygt/osf.io,cosenal/osf.io,zkraime/osf.io,kwierman/osf.io,dplorimer/osf,himanshuo/osf.io,amyshi188/osf.io,lyndsysimon/osf.io,reinaH/osf.io,jmcarp/osf.io,TomHeatwole/osf.io,bdyetton/prettychart,jmcarp/osf.io,mattclark/osf.io,kushG/osf.io,abought/osf.io,acshi/osf.io,samchrisinger/osf.io,jmcarp/osf.io,ZobairAlijan/osf.io,lamdnhan/osf.io,jeffreyliu3230/osf.io,sbt9uc/osf.io,amyshi188/osf.io,lamdnhan/osf.io,cldershem/osf.io,reinaH/osf.io,ticklemepierce/osf.io,brandonPurvis/osf.io,GageGaskins/osf.io,alexschiller/osf.io,asanfilippo7/osf.io,revanthkolli/osf.io,emetsger/osf.io,mluke93/osf.io,baylee-d/osf.io,leb2dg/osf.io,doublebits/osf.io,kushG/osf.io,chrisseto/osf.io,CenterForOpenScience/osf.io,wearpants/osf.io,mfraezz/osf.io,HalcyonChimera/osf.io,SSJohns/osf.io,mfraezz/osf.io,lyndsysimon/osf.io,felliott/osf.io,Johnetordoff/osf.io,MerlinZhang/osf.io,brandonPurvis/osf.io,himanshuo/osf.io,adlius/osf.io,GageGaskins/osf.io,petermalcolm/osf.io,brianjgeiger/osf.io,abought/osf.io,mluo613/osf.io,cslzchen/osf.io,dplorimer/osf,ticklemepierce/osf.io,Nesiehr/osf.io,zkraime/osf.io,leb2dg/osf.io,adlius/osf.io,brianjgeiger/osf.io,ticklemepierce/osf.io,GageGaskins/osf.io,cldershem/osf.io,jinluyuan/osf.io,fabianvf/osf.io,abought/osf.io,caseyrygt/osf.io,arpitar/osf.io,chennan47/osf.io,zamattiac/osf.io,aaxelb/osf.io,emetsger/osf.io,acshi/osf.io,amyshi188/osf.io,GageGaskins/osf.io,caneruguz/osf.io,kwierman/osf.io,kch8qx/osf.io,sloria/osf.io,acshi/osf.io,kwierman/osf.io,RomanZWang/osf.io,caseyrollins/osf.io
96726f66fb4ac69328e84877ead5adb6c2037e5e
site/cgi/csv-upload.py
site/cgi/csv-upload.py
#!/usr/bin/python # Based on examples from # http://www.tutorialspoint.com/python/python_cgi_programming.htm import sys import cgi import os import cgitb cgitb.enable() CSV_DIR = '../csv/' # CSV upload directory form = cgi.FieldStorage() fileitem = form['filename'] # Get filename # Check if the file was uploaded if fileitem.filename: # strip leading path from file name to avoid # directory traversal attacks fn = os.path.basename(fileitem.filename) open(CSV_DIR + fn, 'wb').write(fileitem.file.read()) print 'Status: 204\r\n\r\n' # Success, don't reload page else: # Error, send a message print """\ Status: 500\r\n Content-Type: text/html;charset=UTF-8\n <html> <body> <p>Error: No se subi&oacute; el archivo.</p> </body> </html> """
#!/usr/bin/python # Based on examples from # http://www.tutorialspoint.com/python/python_cgi_programming.htm import cgi import os import cgitb cgitb.enable() CSV_DIR = '../csv/' # CSV upload directory form = cgi.FieldStorage() fileitem = form['filename'] # Get filename # Check if the file was uploaded if fileitem.filename: # strip leading path from file name to avoid # directory traversal attacks fn = os.path.basename(fileitem.filename) open(CSV_DIR + fn, 'wb').write(fileitem.file.read()) print 'Status: 204\r\n\r\n' # Success, don't reload page else: # Error, send a message print """\ Status: 500\r Content-Type: text/html;charset=UTF-8\r <html>\r <body>\r <p>Error: No se subi&oacute; el archivo.</p>\r </body>\r </html>\r """
Remove unused modules, fix HTML response
Remove unused modules, fix HTML response
Python
agpl-3.0
alejosanchez/CSVBenford,alejosanchez/CSVBenford
cb31dcc7be5e89c865686d9a2a07e8a64c9c0179
gamernews/apps/threadedcomments/views.py
gamernews/apps/threadedcomments/views.py
from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.utils.translation import ugettext as _ from django.views.generic.list import ListView from core.models import Account as User from django_comments.models import Comment from .models import ThreadedComment def single_comment(request, id): comment = get_object_or_404(ThreadedComment, id=id) variables = RequestContext(request, {'comment': comment}) return render_to_response('comments/single.html', variables) def comment_posted( request ): if request.GET['c']: comment_id, feeditem_id = request.GET['c'].split( ':' ) feeditem = FeedItem.objects.get( pk=feeditem_id ) if post: return HttpResponseRedirect( feeditem.get_absolute_url() ) return HttpResponseRedirect( "/" )
from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.utils.translation import ugettext as _ from django.views.generic.list import ListView from core.models import Account as User from django_comments.models import Comment from news.models import Blob, BlobInstance from .models import ThreadedComment def single_comment(request, id): comment = get_object_or_404(ThreadedComment, id=id) variables = RequestContext(request, {'comment': comment}) return render_to_response('comments/single.html', variables) def comment_posted( request ): if request.GET['c']: comment_id, blob_id = request.GET['c'].split( ':' ) blob = Blob.objects.get( pk=blob_id ) if post: return HttpResponseRedirect( blob.get_absolute_url() ) return HttpResponseRedirect( "/" )
Remove name, url and email from comment form
Remove name, url and email from comment form
Python
mit
underlost/GamerNews,underlost/GamerNews
08da4c91853b14a264ea07fa5314be437fbce9d4
src/gui/graphscheme.py
src/gui/graphscheme.py
# -*- coding: utf-8 -*- from PySide import QtGui class GraphScheme( QtGui.QGraphicsScene): """ Graph scheme drawing class This class inherits from QtGui.QGraphicsScene and add functions for manage GraphBlocks objects in scheme. """ def __init__(self ): super(GraphScheme, self).__init__() self.layout = QtGui.QGraphicsGridLayout() self.form = QtGui.QGraphicsWidget() self.form.setLayout(self.layout) self.addItem(self.form) self.form.setPos(0, 0) def add_block(self, block, row, column): """ Add GraphBlock to scheme into specified row and column """ self.layout.addItem(block, row, column)
# -*- coding: utf-8 -*- from PySide import QtGui, QtCore class GraphScheme( QtGui.QGraphicsScene): """ Graph scheme drawing class This class inherits from QtGui.QGraphicsScene and add functions for manage GraphBlocks objects in scheme. """ def __init__(self ): super(GraphScheme, self).__init__() self.layout = QtGui.QGraphicsGridLayout() self.form = QtGui.QGraphicsWidget() self.form.setLayout(self.layout) self.addItem(self.form) self.form.setPos(0, 0) gradient = QtGui.QLinearGradient(0, 0, 0, 4000) gradient.setColorAt( 0, QtGui.QColor(255, 255, 255)) gradient.setColorAt( 1, QtGui.QColor(0, 0, 255)) self.setBackgroundBrush(gradient) def add_block(self, block, row, column): """ Add GraphBlock to scheme into specified row and column """ self.layout.addItem(block, row, column)
Add gradient background to GraphScheme
Add gradient background to GraphScheme
Python
lgpl-2.1
anton-golubkov/Garland,anton-golubkov/Garland
c5742bb27aa8446cb5b4c491df6be9c733a1408f
unitary/examples/tictactoe/enums.py
unitary/examples/tictactoe/enums.py
# Copyright 2022 Google # # 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 # # https://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 enum class TicTacSquare(enum.Enum): EMPTY = 0 X = 1 O = 2 class TicTacResult(enum.Enum): UNFINISHED = 0 X_WINS = 1 O_WINS = 2 DRAW = 3 BOTH_WIN = 4
# Copyright 2022 Google # # 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 # # https://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 enum class TicTacSquare(enum.Enum): EMPTY = 0 X = 1 O = 2 class TicTacResult(enum.Enum): UNFINISHED = 0 X_WINS = 1 O_WINS = 2 DRAW = 3 BOTH_WIN = 4 class TicTacRules(enum.Enum): CLASSICAL = 0 MINIMAL_QUANTUM = 1 FULLY_QUANTUM = 2
Add enum for different rulesets
Add enum for different rulesets
Python
apache-2.0
quantumlib/unitary,quantumlib/unitary
ee37119a4f77eef5c8163936d982e178c42cbc00
src/adhocracy/lib/machine_name.py
src/adhocracy/lib/machine_name.py
import platform class IncludeMachineName(object): def __init__(self, app, config): self.app = app self.config = config def __call__(self, environ, start_response): def local_response(status, headers, exc_info=None): headers.append(('X-Server-Machine', platform.node())) start_response(status, headers, exc_info) return self.app(environ, local_response)
import os import platform class IncludeMachineName(object): def __init__(self, app, config): self.app = app self.config = config def __call__(self, environ, start_response): def local_response(status, headers, exc_info=None): machine_id = '%s:%s (PID %d)' % ( platform.node(), environ.get('SERVER_PORT'), os.getpid()) headers.append(('X-Server-Machine', machine_id)) start_response(status, headers, exc_info) return self.app(environ, local_response)
Add Server Port and PID to the X-Server-Machine header
Add Server Port and PID to the X-Server-Machine header Fixes hhucn/adhocracy.hhu_theme#429
Python
agpl-3.0
liqd/adhocracy,liqd/adhocracy,DanielNeugebauer/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,liqd/adhocracy,alkadis/vcv,phihag/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,phihag/adhocracy,liqd/adhocracy,phihag/adhocracy,phihag/adhocracy,alkadis/vcv,phihag/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,DanielNeugebauer/adhocracy
60c4534b1d375aecfe39948e27bc06d0f34907f3
bioagents/resources/trips_ont_manager.py
bioagents/resources/trips_ont_manager.py
import os from indra.preassembler.hierarchy_manager import HierarchyManager # Make a TRIPS ontology _fname = os.path.join(os.path.dirname(__file__), 'trips_ontology.rdf') trips_ontology = HierarchyManager(_fname, uri_as_name=False) trips_ontology.relations_prefix = 'http://trips.ihmc.us/relations/' trips_ontology.initialize() def trips_isa(concept1, concept2): # Preprocess to make this more general concept1 = concept1.lower().replace('ont::', '') concept2 = concept2.lower().replace('ont::', '') if concept1 == concept2: return True isa = trips_ontology.isa('http://trips.ihmc.us/concepts/', concept1, 'http://trips.ihmc.us/concepts/', concept2) return isa
import os from indra.preassembler.hierarchy_manager import HierarchyManager # Make a TRIPS ontology _fname = os.path.join(os.path.dirname(__file__), 'trips_ontology.rdf') trips_ontology = HierarchyManager(_fname, uri_as_name=False, build_closure=True) trips_ontology.relations_prefix = 'http://trips.ihmc.us/relations/' trips_ontology.initialize() def trips_isa(concept1, concept2): # Preprocess to make this more general concept1 = concept1.lower().replace('ont::', '') concept2 = concept2.lower().replace('ont::', '') if concept1 == concept2: return True isa = trips_ontology.isa('http://trips.ihmc.us/concepts/', concept1, 'http://trips.ihmc.us/concepts/', concept2) return isa
Build closure for TRIPS ontology
Build closure for TRIPS ontology
Python
bsd-2-clause
sorgerlab/bioagents,bgyori/bioagents
89e2991109447893b06edf363f223c64e9cafb61
query_result_list.py
query_result_list.py
from query_result_document import QueryResultDocument class QueryResultList: def __init__(self, query, result_documents = []): self.result_documents = result_documents # Guaranteed to be in rank order self.query = query def add( self, rank, document ): self.result_documents.insert( int(rank) - 1, QueryResultDocument( self, rank, document ) ) def results_up_to_rank( self, rank ): return self.result_documents[:int(rank)]
from query_result_document import QueryResultDocument class QueryResultList: def __init__(self, query): self.result_documents = [] # Guaranteed to be in rank order self.query = query def add( self, rank, document ): self.result_documents.insert( int(rank) - 1, QueryResultDocument( self, rank, document ) ) def results_up_to_rank( self, rank ): return self.result_documents[:int(rank)] def length( self ): return len( self.result_documents )
Fix query result list having an empty list default parameter (default parameters get initialized only once!)
Fix query result list having an empty list default parameter (default parameters get initialized only once!)
Python
mit
fire-uta/iiix-data-parser
015bc46057db405107799d7214b0fe5264843277
run_deploy_job_wr.py
run_deploy_job_wr.py
#!/usr/bin/env python import json import os import subprocess import sys from tempfile import NamedTemporaryFile def main(): revision_build = os.environ['revision_build'] job_name = os.environ['JOB_NAME'] build_number = os.environ['BUILD_NUMBER'] prefix='juju-ci/products/version-{}/{}/build-{}'.format( revision_build, job_name, build_number) s3_config = join(os.environ['HOME'], 'cloud-city/juju-qa.s3cfg') command = [ '$HOME/juju-ci-tools/run-deploy-job-remote.bash', revision_build, job_name, ] command.extend(sys.argv[2:]) with NamedTemporaryFile() as config_file: json.dump({ 'command': command, 'install': {}, 'artifacts': {'artifacts': ['*']}, 'bucket': 'juju-qa-data', }, config_file) config_file.flush() subprocess.check_call([ 'workspace-run', config_file.name, sys.argv[1], prefix, '--s3-config', s3_config, ]) if __name__ == '__main__': main()
#!/usr/bin/env python import json import os from os.path import join import subprocess import sys from tempfile import NamedTemporaryFile def main(): revision_build = os.environ['revision_build'] job_name = os.environ['JOB_NAME'] build_number = os.environ['BUILD_NUMBER'] prefix='juju-ci/products/version-{}/{}/build-{}'.format( revision_build, job_name, build_number) s3_config = join(os.environ['HOME'], 'cloud-city/juju-qa.s3cfg') command = [ '$HOME/juju-ci-tools/run-deploy-job-remote.bash', revision_build, job_name, ] command.extend(sys.argv[2:]) with NamedTemporaryFile() as config_file: json.dump({ 'command': command, 'install': {}, 'artifacts': {'artifacts': [ 'artifacts/machine*/*log*', 'artifacts/*.jenv', ]}, 'bucket': 'juju-qa-data', }, config_file) config_file.flush() subprocess.check_call([ 'workspace-run', config_file.name, sys.argv[1], prefix, '--s3-config', s3_config, '-v', ]) if __name__ == '__main__': main()
Fix artifact spec for deploy-job.
Fix artifact spec for deploy-job.
Python
agpl-3.0
mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju
f1e5e2cc7fd35e0446f105d619dc01d3ba837865
byceps/blueprints/admin/party/forms.py
byceps/blueprints/admin/party/forms.py
""" byceps.blueprints.admin.party.forms ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from wtforms import BooleanField, DateTimeField, IntegerField, StringField from wtforms.validators import InputRequired, Length, Optional from ....util.l10n import LocalizedForm class UpdateForm(LocalizedForm): title = StringField('Titel', validators=[Length(min=1, max=40)]) starts_at = DateTimeField('Beginn', format='%d.%m.%Y %H:%M', validators=[InputRequired()]) ends_at = DateTimeField('Ende', format='%d.%m.%Y %H:%M', validators=[InputRequired()]) max_ticket_quantity = IntegerField('Maximale Anzahl Tickets', validators=[Optional()]) shop_id = StringField('Shop-ID', validators=[Optional()]) archived = BooleanField('archiviert') class CreateForm(UpdateForm): id = StringField('ID', validators=[Length(min=1, max=40)])
""" byceps.blueprints.admin.party.forms ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from wtforms import BooleanField, DateTimeField, IntegerField, StringField from wtforms.validators import InputRequired, Length, Optional from ....util.l10n import LocalizedForm class _BaseForm(LocalizedForm): title = StringField('Titel', validators=[Length(min=1, max=40)]) starts_at = DateTimeField('Beginn', format='%d.%m.%Y %H:%M', validators=[InputRequired()]) ends_at = DateTimeField('Ende', format='%d.%m.%Y %H:%M', validators=[InputRequired()]) max_ticket_quantity = IntegerField('Maximale Anzahl Tickets', validators=[Optional()]) shop_id = StringField('Shop-ID', validators=[Optional()]) class CreateForm(_BaseForm): id = StringField('ID', validators=[Length(min=1, max=40)]) class UpdateForm(_BaseForm): archived = BooleanField('archiviert')
Introduce base party form, limit `archived` flag to update form
Introduce base party form, limit `archived` flag to update form
Python
bsd-3-clause
m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps
f9a0b8395adcf70c23c975a06e7667d673f74ac5
stoneridge_uploader.py
stoneridge_uploader.py
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. import glob import os import requests import stoneridge class StoneRidgeUploader(object): """Takes the upload files created by the collator and uploads them to the graph server """ def __init__(self): self.url = stoneridge.get_config('upload', 'url') def run(self): file_pattern = os.path.join(stoneridge.outdir, 'upload_*.json') upload_files = glob.glob(file_pattern) files = {os.path.basename(fname): open(fname, 'rb') for fname in upload_files} requests.post(self.url, files=files) for f in files.values(): f.close() @stoneridge.main def main(): parser = stoneridge.ArgumentParser() args = parser.parse_args() uploader = StoneRidgeUploader() uploader.run()
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. import glob import os import requests import stoneridge class StoneRidgeUploader(object): """Takes the upload files created by the collator and uploads them to the graph server """ def __init__(self): self.url = stoneridge.get_config('upload', 'url') def run(self): file_pattern = os.path.join(stoneridge.outdir, 'upload_*.json') upload_files = glob.glob(file_pattern) if not upload_files: # Nothing to do, so forget it! return files = {os.path.basename(fname): open(fname, 'rb') for fname in upload_files} requests.post(self.url, files=files) for f in files.values(): f.close() @stoneridge.main def main(): parser = stoneridge.ArgumentParser() args = parser.parse_args() uploader = StoneRidgeUploader() uploader.run()
Fix uploader when there is nothing to upload
Fix uploader when there is nothing to upload
Python
mpl-2.0
mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge
32d7921de5768fd74983ebff6fa37212aed24e83
all/shellenv/_win.py
all/shellenv/_win.py
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import os import locale from ._types import str_cls _sys_encoding = locale.getpreferredencoding() def get_env(shell=None): """ Return environment variables for the current user :param shell: The shell to get the env from - unused on Windows :return: A 2-element tuple: - [0] unicode string shell path - [1] env dict with keys and values as unicode strings """ shell = os.environ['ComSpec'] if not isinstance(shell, str_cls): shell = shell.decode(_sys_encoding) return (shell, dict(os.environ))
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import os import locale import sys import ctypes from ._types import str_cls _sys_encoding = locale.getpreferredencoding() kernel32 = ctypes.windll.kernel32 kernel32.GetEnvironmentStringsW.argtypes = [] kernel32.GetEnvironmentStringsW.restype = ctypes.c_void_p def get_env(shell=None): """ Return environment variables for the current user :param shell: The shell to get the env from - unused on Windows :return: A 2-element tuple: - [0] unicode string shell path - [1] env dict with keys and values as unicode strings """ shell = os.environ['ComSpec'] if not isinstance(shell, str_cls): shell = shell.decode(_sys_encoding) if sys.version_info < (3,): str_pointer = kernel32.GetEnvironmentStringsW() string = ctypes.wstring_at(str_pointer) values = {} while string != '': if string[0].isalpha(): name, value = string.split(u'=', 1) values[name] = value # Include the trailing null byte, and measure each # char as 2 bytes since Windows uses UTF-16 for # wide chars str_pointer += (len(string) + 1) * 2 string = ctypes.wstring_at(str_pointer) else: values = dict(os.environ) return (shell, values)
Use kernel32 with ST2 on Windows to get unicode environmental variable values
Use kernel32 with ST2 on Windows to get unicode environmental variable values
Python
mit
codexns/shellenv
3eaf93f2ecee68fafa1ff4f75d4c6e7f09a37043
api/streams/views.py
api/streams/views.py
from api.streams.models import StreamConfiguration from django.http import JsonResponse from django.http.request import HttpRequest import requests def get_stream_status(request: HttpRequest, stream_slug: str): stream = StreamConfiguration.objects.get(slug=stream_slug) r = requests.get('http://{stream.host}:{stream.port}/status-json.xsl'.format(stream=stream)) r.raise_for_status() return JsonResponse(r.json())
from api.streams.models import StreamConfiguration from django.http import JsonResponse from django.http.request import HttpRequest import requests def get_stream_status(request: HttpRequest, stream_slug: str): stream = StreamConfiguration.objects.get(slug=stream_slug) r = requests.get('http://{stream.host}:{stream.port}/status-json.xsl'.format(stream=stream), timeout=5) r.raise_for_status() return JsonResponse(r.json())
Add timeout to Icecast status request
Add timeout to Icecast status request
Python
mit
urfonline/api,urfonline/api,urfonline/api
655f46a10245de0b7f4d9727f816815c6493d230
tests/test_settings.py
tests/test_settings.py
# -*- coding:utf-8 -*- import os try: import unittest2 as unittest except ImportError: import unittest # NOQA from sigal.settings import read_settings class TestSettings(unittest.TestCase): "Read a settings file and check that the configuration is well done." def setUp(self): "Read the sample config file" self.path = os.path.abspath(os.path.dirname(__file__)) default_conf = os.path.join(self.path, 'sample', 'sigal.conf.py') self.settings = read_settings(default_conf) def test_sizes(self): "Test that image sizes are correctly read" self.assertTupleEqual(self.settings['img_size'], (640, 480)) self.assertTupleEqual(self.settings['thumb_size'], (200, 150)) def test_settings(self): self.assertEqual(self.settings['thumb_suffix'], '.tn')
# -*- coding:utf-8 -*- import os try: import unittest2 as unittest except ImportError: import unittest # NOQA from sigal.settings import read_settings, get_thumb class TestSettings(unittest.TestCase): "Read a settings file and check that the configuration is well done." def setUp(self): "Read the sample config file" self.path = os.path.abspath(os.path.dirname(__file__)) default_conf = os.path.join(self.path, 'sample', 'sigal.conf.py') self.settings = read_settings(default_conf) def test_sizes(self): "Test that image sizes are correctly read" self.assertTupleEqual(self.settings['img_size'], (640, 480)) self.assertTupleEqual(self.settings['thumb_size'], (200, 150)) def test_settings(self): self.assertEqual(self.settings['thumb_suffix'], '.tn') def test_thumb(self): self.assertEqual(get_thumb(self.settings, 'example.jpg'), 'thumbnails/example.tn.jpg') self.assertEqual(get_thumb(self.settings, 'test/example.jpg'), 'test/thumbnails/example.tn.jpg')
Add a test for the get_thumb function.
Add a test for the get_thumb function.
Python
mit
jdn06/sigal,Ferada/sigal,elaOnMars/sigal,kontza/sigal,kontza/sigal,t-animal/sigal,kontza/sigal,franek/sigal,cbosdo/sigal,cbosdo/sigal,saimn/sigal,saimn/sigal,jasuarez/sigal,xouillet/sigal,t-animal/sigal,muggenhor/sigal,saimn/sigal,elaOnMars/sigal,Ferada/sigal,franek/sigal,muggenhor/sigal,cbosdo/sigal,jdn06/sigal,xouillet/sigal,jasuarez/sigal,Ferada/sigal,t-animal/sigal,jdn06/sigal,xouillet/sigal,jasuarez/sigal
bba325111b47c9ba7dfc0bc9556a655e3f5afcee
tools/jtag/discover.py
tools/jtag/discover.py
#! /usr/bin/env python ''' Simplistic chain discovery ''' import sys sys.path.append('../..') from playtag.cables.digilent import Jtagger from playtag.jtag.discover import Chain print Chain(Jtagger())
#! /usr/bin/env python ''' Simplistic chain discovery ''' import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../..')) from playtag.cables.digilent import Jtagger from playtag.jtag.discover import Chain print Chain(Jtagger())
Make it work when executed from a different directory
Make it work when executed from a different directory
Python
mit
E3V3A/playtag,proteus-cpi/playtag
6ecbcfd1b132b0c4acd2d413818348a2fe2b6bfe
Cauldron/utils/referencecompat.py
Cauldron/utils/referencecompat.py
# -*- coding: utf-8 -*- try: from __builtins__ import ReferenceError except (NameError, ImportError): # pragma: no cover from weakref import ReferenceError __all__ = ['ReferenceError']
# -*- coding: utf-8 -*- import sys try: if sys.version_info[0] < 3: from __builtins__ import ReferenceError else: from builtins import ReferenceError except (NameError, ImportError): # pragma: no cover from weakref import ReferenceError __all__ = ['ReferenceError']
Fix a py3 bug in reference compatibility
Fix a py3 bug in reference compatibility
Python
bsd-3-clause
alexrudy/Cauldron
492004049da87744cd96a6e6afeb9a6239a8ac44
ocradmin/lib/nodetree/registry.py
ocradmin/lib/nodetree/registry.py
""" Registry class and global node registry. """ class NotRegistered(KeyError): pass __all__ = ["NodeRegistry", "nodes"] class NodeRegistry(dict): NotRegistered = NotRegistered def register(self, node): """Register a node in the node registry. The node will be automatically instantiated if not already an instance. """ self[node.name] = inspect.isclass(node) and node() or node def unregister(self, name): """Unregister node by name.""" try: # Might be a node class name = name.name except AttributeError: pass self.pop(name) def filter_types(self, type): """Return all nodes of a specific type.""" return dict((name, node) for name, node in self.iteritems() if node.type == type) def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: raise self.NotRegistered(key) def pop(self, key, *args): try: return dict.pop(self, key, *args) except KeyError: raise self.NotRegistered(key) nodes = NodeRegistry()
""" Registry class and global node registry. """ import inspect class NotRegistered(KeyError): pass class NodeRegistry(dict): NotRegistered = NotRegistered def register(self, node): """Register a node class in the node registry.""" self[node.name] = inspect.isclass(node) and node or node.__class__ def unregister(self, name): """Unregister node by name.""" try: # Might be a node class name = name.name except AttributeError: pass self.pop(name) def get_by_attr(self, attr, value=None): """Return all nodes of a specific type that have a matching attr. If `value` is given, only return nodes where the attr value matches.""" ret = {} for name, node in self.iteritems(): if hasattr(node, attr) and value is None\ or hasattr(node, name) and getattr(node, name) == value: ret[name] = node return ret def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: raise self.NotRegistered(key) def pop(self, key, *args): try: return dict.pop(self, key, *args) except KeyError: raise self.NotRegistered(key) nodes = NodeRegistry()
Fix missing import. Add method to get all nodes with a particular attribute
Fix missing import. Add method to get all nodes with a particular attribute
Python
apache-2.0
vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium
0225177c39df95bc12d9d9b53433f310d083905f
tests/test_heroku.py
tests/test_heroku.py
"""Tests for the Wallace API.""" import subprocess import re import os import requests class TestHeroku(object): """The Heroku test class.""" sandbox_output = subprocess.check_output( "cd examples/bartlett1932; wallace sandbox --verbose", shell=True) os.environ['app_id'] = re.search( 'Running as experiment (.*)...', sandbox_output).group(1) @classmethod def teardown_class(cls): """Remove the app from Heroku.""" app_id = os.environ['app_id'] subprocess.call( "heroku apps:destroy --app {} --confirm {}".format(app_id, app_id), shell=True) def test_summary(self): """Launch the experiment on Heroku.""" app_id = os.environ['app_id'] r = requests.get("http://{}.herokuapp.com/summary".format(app_id)) assert r.json()['status'] == [] def test_robots(self): """Ensure that robots.txt can be accessed.""" app_id = os.environ['app_id'] r = requests.get("http://{}.herokuapp.com/robots.txt".format(app_id)) assert r.status_code == 200
"""Tests for the Wallace API.""" import subprocess import re import os import requests class TestHeroku(object): """The Heroku test class.""" sandbox_output = subprocess.check_output( "cd examples/bartlett1932; wallace sandbox --verbose", shell=True) os.environ['app_id'] = re.search( 'Running as experiment (.*)...', sandbox_output).group(1) @classmethod def teardown_class(cls): """Remove the app from Heroku.""" app_id = os.environ['app_id'] subprocess.call( "heroku apps:destroy --app {} --confirm {}".format(app_id, app_id), shell=True) def test_summary(self): """Launch the experiment on Heroku.""" app_id = os.environ['app_id'] r = requests.get("http://{}.herokuapp.com/summary".format(app_id)) assert r.json()['status'] == [] def test_robots(self): """Ensure that robots.txt can be accessed.""" app_id = os.environ['app_id'] r = requests.get("http://{}.herokuapp.com/robots.txt".format(app_id)) assert r.status_code == 200 def test_nonexistent_route(self): """Ensure that a nonexistent route returns a 500 error.""" app_id = os.environ['app_id'] r = requests.get("http://{}.herokuapp.com/nope".format(app_id)) assert r.status_code == 500
Add test for correct error for nonexistent routes
Add test for correct error for nonexistent routes
Python
mit
berkeley-cocosci/Wallace,jcpeterson/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,suchow/Wallace,Dallinger/Dallinger,berkeley-cocosci/Wallace,berkeley-cocosci/Wallace,jcpeterson/Dallinger,jcpeterson/Dallinger,suchow/Wallace,suchow/Wallace,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger
f97d9d6462ce9e60c1811bd40428a1f30835ce95
hb_res/storage/FileExplanationStorage.py
hb_res/storage/FileExplanationStorage.py
from hb_res.storage import ExplanationStorage __author__ = 'skird' import codecs from hb_res.explanations.Explanation import Explanation class FileExplanationStorage(ExplanationStorage): """ Class representing explanation resource connected with some text file """ def __init__(self, path_to_file): self.file_name = path_to_file self.descriptor = codecs.open(self.file_name, mode='a', encoding='utf-8') def entries(self): self.descriptor.flush() for line in open(self.file_name): yield Explanation.decode(line.strip()) def add_entry(self, entry: Explanation) -> None: print(entry, file=self.descriptor) def clear(self) -> None: self.descriptor = codecs.open(self.file_name, mode='w', encoding='utf-8') def close(self) -> None: self.descriptor.flush() def __getitem__(self, key): for explanation in self.entries(): if explanation.key == key: return explanation
from hb_res.storage import ExplanationStorage from hb_res.explanations.Explanation import Explanation __author__ = 'skird' class FileExplanationStorage(ExplanationStorage): """ Class representing explanation resource connected with some text file """ def __init__(self, path_to_file): self.file_name = path_to_file self.write_desc = None def entries(self): if self.write_desc is not None: self.write_desc.flush() with open(self.file_name, encoding='utf-8') as read_desc: for line in read_desc: yield Explanation.decode(line.strip()) def add_entry(self, entry: Explanation) -> None: if self.write_desc is None: self.write_desc = open(self.file_name, mode='a', encoding='utf-8') print(entry, file=self.write_desc) def clear(self) -> None: if self.write_desc is not None: self.write_desc.close() self.write_desc = open(self.file_name, mode='w', encoding='utf-8') def close(self) -> None: if self.write_desc is not None: self.write_desc.close() def __getitem__(self, key): for explanation in self.entries(): if explanation.key == key: return explanation
Fix permission-denied error in read-only context
Fix permission-denied error in read-only context
Python
mit
hatbot-team/hatbot_resources
c471a5d6421e32e9c6e3ca2db0f07eae45a85408
fuckit_commit.py
fuckit_commit.py
''' This module will send SMS reminders periodically, using Twilio. The aim is to encourage user to code, commit and push to GitHub everyday ''' import requests def set_configuration(): ''' Set Twilio configuration ''' pass def get_twilio_client(): ''' Connect to Twilio Client ''' pass def send_sms(): ''' Send SMS reminder ''' pass def main(): pass if __name__ == "__main__": main()
''' This module will send SMS reminders periodically, using Twilio. The aim is to encourage user to code, commit and push to GitHub everyday ''' import requests from twilio.rest import TwilioRestClient def get_configuration(): ''' Set Twilio configuration ''' pass def get_twilio_client(config): ''' Connect to Twilio Client ''' return TwilioRestClient(config.account_sid, config.auth_token) def send_sms(client): ''' Send SMS reminder ''' pass def main(): config = get_configuration() client = get_configuration(config) send_sms(client) if __name__ == "__main__": main()
Add code to send sms
Add code to send sms
Python
mit
ueg1990/fuckit_commit
048994463cda7df1bbaf502bef2bf84036e73403
i18n/loaders/python_loader.py
i18n/loaders/python_loader.py
import os.path import sys from .loader import Loader, I18nFileLoadError class PythonLoader(Loader): """class to load python files""" def __init__(self): super(PythonLoader, self).__init__() def load_file(self, filename): path, name = os.path.split(filename) module_name, ext = os.path.splitext(name) if path not in sys.path: sys.path.append(path) try: return __import__(module_name) except ImportError as e: raise I18nFileLoadError("error loading file {0}: {1}".format(filename, e.msg)) def parse_file(self, file_content): return file_content def check_data(self, data, root_data): return hasattr(data, root_data) def get_data(self, data, root_data): return getattr(data, root_data)
import os.path import sys from .loader import Loader, I18nFileLoadError class PythonLoader(Loader): """class to load python files""" def __init__(self): super(PythonLoader, self).__init__() def load_file(self, filename): path, name = os.path.split(filename) module_name, ext = os.path.splitext(name) if path not in sys.path: sys.path.append(path) try: return __import__(module_name) except ImportError: raise I18nFileLoadError("error loading file {0}".format(filename)) def parse_file(self, file_content): return file_content def check_data(self, data, root_data): return hasattr(data, root_data) def get_data(self, data, root_data): return getattr(data, root_data)
Fix bug in python loader.
Fix bug in python loader.
Python
mit
tuvistavie/python-i18n
7bc247550f136c5f0e34f411b868f9e5949e1ec4
api/tests/destinations/endpoint_tests.py
api/tests/destinations/endpoint_tests.py
import unittest from peewee import SqliteDatabase from playhouse.test_utils import test_database import api.tests.helpers as helpers from api.destinations.endpoint import * from api.destinations.endpoint import _get_destinations test_db = SqliteDatabase(':memory:') class DestinationsTests(unittest.TestCase): def setUp(self): self._all_stations = helpers.create_station_test_data() for station in self._all_stations: station.save(force_insert=True) def tearDown(self): Station.delete() def run(self, result=None): # All queries will be run in `test_db` with test_database(test_db, [Station]): super(DestinationsTests, self).run(result) def test_get_destinations_filters_zone(self): self.assertEqual(2, len(_get_destinations())) def test_get_destinations_filters_orders(self): self.assertEqual("BAR", _get_destinations()[0].sid)
from peewee import SqliteDatabase from api.destinations.endpoint import _get_destinations from api.tests.dbtestcase import DBTestCase test_db = SqliteDatabase(':memory:') class DestinationsTests(DBTestCase): def test_get_destinations_filters_zone(self): self.assertEqual(2, len(_get_destinations())) def test_get_destinations_filters_orders(self): self.assertEqual("BAR", _get_destinations()[0].sid)
Update destination endpoint tests to work with new version of peewee
Update destination endpoint tests to work with new version of peewee
Python
mit
mdowds/commutercalculator,mdowds/commutercalculator,mdowds/commutercalculator
4f9569037ad835b852e6389b082155d45a88774c
kokki/cookbooks/nginx/recipes/default.py
kokki/cookbooks/nginx/recipes/default.py
from kokki import * Package("nginx") Directory(env.config.nginx.log_dir, mode = 0755, owner = env.config.nginx.user, action = 'create') for nxscript in ('nxensite', 'nxdissite'): File("/usr/sbin/%s" % nxscript, content = Template("nginx/%s.j2" % nxscript), mode = 0755, owner = "root", group = "root") File("nginx.conf", path = "%s/nginx.conf" % env.config.nginx.dir, content = Template("nginx/nginx.conf.j2"), owner = "root", group = "root", mode = 0644) File("%s/sites-available/default" % env.config.nginx.dir, content = Template("nginx/default-site.j2"), owner = "root", group = "root", mode = 0644) Service("nginx", supports_status = True, supports_restart = True, supports_reload = True, action = "start", subscribes = [("reload", env.resources["File"]["nginx.conf"])])
from kokki import * Package("nginx") Directory(env.config.nginx.log_dir, mode = 0755, owner = env.config.nginx.user, action = 'create') for nxscript in ('nxensite', 'nxdissite'): File("/usr/sbin/%s" % nxscript, content = Template("nginx/%s.j2" % nxscript), mode = 0755, owner = "root", group = "root") File("nginx.conf", path = "%s/nginx.conf" % env.config.nginx.dir, content = Template("nginx/nginx.conf.j2"), owner = "root", group = "root", mode = 0644) File("%s/sites-available/default" % env.config.nginx.dir, content = Template("nginx/default-site.j2"), owner = "root", group = "root", mode = 0644) Service("nginx", supports_status = True, supports_restart = True, supports_reload = True, action = "start", subscribes = [("reload", env.resources["File"]["nginx.conf"])]) if "librato.silverline" in env.included_recipes: File("/etc/default/nginx", owner = "root", gorup = "root", mode = 0644, content = ( "export LM_CONTAINER_NAME=nginx\n" "export LM_TAG_NAMES=nginx:webserver:frontend\n" ), notifies = [("restart", env.resources["Service"]["nginx"])])
Add silverline environment to nginx
Add silverline environment to nginx
Python
bsd-3-clause
samuel/kokki
c1889a71be161400a42ad6b7c72b2559a84f69bf
src/nodeconductor_assembly_waldur/invoices/tests/test_report.py
src/nodeconductor_assembly_waldur/invoices/tests/test_report.py
from django.test import TestCase from nodeconductor_assembly_waldur.invoices.tasks import format_invoice_csv from .. import models from . import fixtures class TestReportFormatter(TestCase): def test_invoice_items_are_properly_formatted(self): fixture = fixtures.InvoiceFixture() package = fixture.openstack_package invoice = models.Invoice.objects.get(customer=package.tenant.service_project_link.project.customer) report = format_invoice_csv(invoice) self.assertEqual(2, len(report.splitlines()))
from django.test import TestCase from nodeconductor_assembly_waldur.invoices.tasks import format_invoice_csv from .. import models from . import fixtures class TestReportFormatter(TestCase): def setUp(self): fixture = fixtures.InvoiceFixture() package = fixture.openstack_package invoice = models.Invoice.objects.get(customer=package.tenant.service_project_link.project.customer) self.invoice = invoice def test_invoice_items_are_properly_formatted(self): report = format_invoice_csv(self.invoice) lines = report.splitlines() self.assertEqual(2, len(lines)) expected_header = 'customer_uuid;customer_name;project_uuid;project_name;' \ 'invoice_uuid;invoice_number;invoice_year;invoice_month;' \ 'invoice_date;due_date;invoice_price;invoice_tax;' \ 'invoice_total;name;article_code;product_code;' \ 'price;tax;total;daily_price;start;end;usage_days' self.assertEqual(lines[0], expected_header)
Add unit test for report formatter
Add unit test for report formatter [WAL-905]
Python
mit
opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur
11c30f5dd765475a9f5f0f847f31c47af8c40a39
user_agent/device.py
user_agent/device.py
import os.path import json PACKAGE_DIR = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(PACKAGE_DIR, 'data/smartphone_dev_id.json')) as f: SMARTPHONE_DEV_IDS = json.load(open(f)) with open(os.path.join(PACKAGE_DIR, 'data/tablet_dev_id.json')) as f: TABLET_DEV_IDS = json.load(open())
import os.path import json PACKAGE_DIR = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(PACKAGE_DIR, 'data/smartphone_dev_id.json')) as f: SMARTPHONE_DEV_IDS = json.load(f) with open(os.path.join(PACKAGE_DIR, 'data/tablet_dev_id.json')) as f: TABLET_DEV_IDS = json.load(f)
Fix uses of file objects
Fix uses of file objects
Python
mit
lorien/user_agent
2158edb92cba6c19fa258f19445191d0308c4153
utils/async_tasks.py
utils/async_tasks.py
from utils.redis_store import store def data_from_async_task(task_func, task_args, task_kwargs, store_key, refresh_time=60): # Get task results previously stored in store output, elapsed_time = store.get(store_key, include_elapsed_time=True) # If there are no previously stored results (elapsed_time will be a magically big number) or # if the previously stored results are older than refresh_time, then we trigger recompute of the # task so that results are ready for next load. if elapsed_time > refresh_time: task_func.delay(store_key, *task_args, **task_kwargs) return output
from utils.redis_store import store from celery.signals import task_postrun, task_prerun def data_from_async_task(task_func, task_args, task_kwargs, store_key, refresh_time=60, run_once=True): # Get task results previously stored in store output, elapsed_time = store.get(store_key, include_elapsed_time=True) # If there are no previously stored results (elapsed_time will be a magically big number) or # if the previously stored results are older than refresh_time, then we trigger recompute of the # task so that results are ready for next load. # If run_once=True, we only trigger the recompute if the task is not already running if elapsed_time > refresh_time: if run_once: # Check that it is not already running computing_store_key = 'computing-{0}.{1}'.format(task_func.__module__, task_func.__name__) if store.get(computing_store_key): # Task is already running, don't trigger running again print('Skip computing data for {0}, already running'.format(store_key)) return output task_func.delay(store_key, *task_args, **task_kwargs) return output @task_prerun.connect() def task_prerun(signal=None, sender=None, task_id=None, task=None, args=None, kwargs=None): # Set computing key computing_store_key = 'computing-{0}'.format(task.name) store.set(computing_store_key, {'running': True}) @task_postrun.connect() def task_postrun(signal=None, sender=None, task_id=None, task=None, args=None, kwargs=None, retval=None, state=None): # Delete computing key (if present) computing_store_key = 'computing-{0}'.format(task.name) store.delete(computing_store_key)
Add option to run async tasks only on at a time
Add option to run async tasks only on at a time This is implemented with a simple lock like mechanism using redis.
Python
agpl-3.0
MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets
43e86a3ac5f63c702ce409c45e3aaaac60990fe9
python/ensure_haddock_coverage.py
python/ensure_haddock_coverage.py
#!/usr/bin/env python """ Tiny utility script to check that coverage statistics output by stack haddock are all 100%. """ import sys import re def main(): """Entry point to ensure-haddock-coverage.py.""" # Verify that the number of arguments is correct. if len(sys.argv) != 2: print("Usage: ./ensure-haddock-coverage.py $HADDOCK_OUT", file=sys.stderr) sys.exit(1) # Read contents of input file. filename = sys.argv[1] with open(filename, "r") as handle: contents = handle.read() # Find all coverage statistics. stats = [] for line in contents.split("\n"): pat = " ([0-9]*)% \\([ 0-9]* / [ 0-9]*\\) in '([a-zA-Z.0-9]*)'" match = re.search(pat, line) if match is not None: stats.append((int(match.group(1)), match.group(2))) insufficient_coverage = False for coverage, name in stats: if coverage != 100: print("Insufficient Haddock Coverage on {}: {}" .format(name, coverage)) insufficient_coverage = True if insufficient_coverage: sys.exit(1) if __name__ == '__main__': main()
#!/usr/bin/env python """ Tiny utility script to check that coverage statistics output by stack haddock are all 100%. """ import sys import re def main(): """Entry point to ensure-haddock-coverage.py.""" # Verify that the number of arguments is correct. if len(sys.argv) != 2: print("Usage: ./ensure-haddock-coverage.py $HADDOCK_OUT", file=sys.stderr) sys.exit(1) # Read contents of input file. filename = sys.argv[1] with open(filename, "r") as handle: contents = handle.read() # Find all coverage statistics. stats = [] for line in contents.split("\n"): pat = " ([0-9]*)% \\([ 0-9]* / [ 0-9]*\\) in '([a-zA-Z.0-9]*)'" match = re.search(pat, line) if match is not None: stats.append((int(match.group(1)), match.group(2))) insufficient_coverage = False for coverage, name in stats: if coverage != 100: print("Insufficient Haddock Coverage on {}: {}" .format(name, coverage)) insufficient_coverage = True if len(stats) < 8: print(("Expecting at least 8 Haddock-covered modules.\n" "Possibly Haddock output nothing, or number of modules " "has decreased.\nIf number of modules has decreased, edit " "ensure_haddock_coverage.py to be up to date."), file=sys.stderr) insufficient_coverage = True if insufficient_coverage: sys.exit(1) if __name__ == '__main__': main()
Check for number of modules in haddock-checking script
Check for number of modules in haddock-checking script
Python
mit
gibiansky/jupyter-haskell
8b9ebbad9e87af3f56570ba3c32dcdb2d7ca4a39
django_iceberg/models/base_models.py
django_iceberg/models/base_models.py
from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ DEFAULT_ICEBERG_ENV = getattr(settings, 'ICEBERG_DEFAULT_ENVIRO', "prod") class IcebergBaseModel(models.Model): ICEBERG_PROD, ICEBERG_SANDBOX, ICEBERG_STAGE, ICEBERG_SANDBOX_STAGE = "prod", "sandbox", "stage", "sandbox_stage" ENVIRONMENT_CHOICES = ( (ICEBERG_PROD, _('Iceberg - Prod')), (ICEBERG_STAGE, _('Iceberg - Prod Stage')), # PreProd (ICEBERG_SANDBOX, _('Iceberg - Sandbox')), (ICEBERG_SANDBOX_STAGE, _('Iceberg - Sandbox Stage')), ) environment = models.CharField(choices=ENVIRONMENT_CHOICES, default=DEFAULT_ICEBERG_ENV, max_length = 20) iceberg_id = models.PositiveIntegerField(blank=True, null=True) last_updated = models.DateTimeField(auto_now = True) API_RESOURCE_NAME = None class Meta: abstract = True def iceberg_sync(self, api_handler): """ Sync the local object from Iceberg version """ raise NotImplementedError
from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ DEFAULT_ICEBERG_ENV = getattr(settings, 'ICEBERG_DEFAULT_ENVIRO', "prod") class IcebergBaseModel(models.Model): ICEBERG_PROD, ICEBERG_SANDBOX, ICEBERG_STAGE, ICEBERG_SANDBOX_STAGE = "prod", "sandbox", "stage", "sandbox_stage" ENVIRONMENT_CHOICES = ( (ICEBERG_PROD, _('Iceberg - Prod')), (ICEBERG_STAGE, _('Iceberg - Prod Stage')), # PreProd (ICEBERG_SANDBOX, _('Iceberg - Sandbox')), (ICEBERG_SANDBOX_STAGE, _('Iceberg - Sandbox Stage')), ) environment = models.CharField(choices=ENVIRONMENT_CHOICES, default=DEFAULT_ICEBERG_ENV, max_length = 20) iceberg_id = models.PositiveIntegerField(blank=True, null=True) last_updated = models.DateTimeField(auto_now = True) API_RESOURCE_NAME = None class Meta: app_label = "django_iceberg" abstract = True def iceberg_sync(self, api_handler): """ Sync the local object from Iceberg version """ raise NotImplementedError
Add app_name for django < 1.7 compatibility
Add app_name for django < 1.7 compatibility
Python
mit
izberg-marketplace/django-izberg,izberg-marketplace/django-izberg,Iceberg-Marketplace/django-iceberg,Iceberg-Marketplace/django-iceberg
0c186d8e0fb5bd7170ec55943e546f1e4e335839
masters/master.tryserver.chromium/master_site_config.py
masters/master.tryserver.chromium/master_site_config.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ActiveMaster definition.""" from config_bootstrap import Master class TryServer(Master.Master4): project_name = 'Chromium Try Server' master_port = 8028 slave_port = 8128 master_port_alt = 8228 try_job_port = 8328 # Select tree status urls and codereview location. reply_to = 'chrome-troopers+tryserver@google.com' base_app_url = 'https://chromium-status.appspot.com' tree_status_url = base_app_url + '/status' store_revisions_url = base_app_url + '/revisions' last_good_url = base_app_url + '/lkgr' last_good_blink_url = 'http://blink-status.appspot.com/lkgr' svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try' buildbot_url = 'http://build.chromium.org/p/tryserver.chromium/'
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ActiveMaster definition.""" from config_bootstrap import Master class TryServer(Master.Master4): project_name = 'Chromium Try Server' master_port = 8028 slave_port = 8128 master_port_alt = 8228 try_job_port = 8328 # Select tree status urls and codereview location. reply_to = 'chrome-troopers+tryserver@google.com' base_app_url = 'https://chromium-status.appspot.com' tree_status_url = base_app_url + '/status' store_revisions_url = base_app_url + '/revisions' last_good_url = None last_good_blink_url = None svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try' buildbot_url = 'http://build.chromium.org/p/tryserver.chromium/'
Remove last good URL for tryserver.chromium
Remove last good URL for tryserver.chromium The expected behavior of this change is that the tryserver master no longer tries to resolve revisions to LKGR when trying jobs. BUG=372499, 386667 Review URL: https://codereview.chromium.org/394653002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@283469 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
94e344b48161e20fec5023fbeea4a14cdc736158
pynuts/filters.py
pynuts/filters.py
# -*- coding: utf-8 -*- """Jinja environment filters for Pynuts.""" from flask import escape from flask.ext.wtf import ( QuerySelectField, QuerySelectMultipleField, BooleanField) def data(field): """Field data beautifier. QuerySelectMultipleField Renders comma-separated data. QuerySelectField Renders the selected value. BooleanField Renders '✓' or '✕' Example: .. sourcecode:: html+jinja <dd>{{ field | data }}</dd> """ if isinstance(field, QuerySelectMultipleField): if field.data: return escape( u', '.join(field.get_label(data) for data in field.data)) elif isinstance(field, QuerySelectField): if field.data: return escape(field.get_label(field.data)) elif isinstance(field, BooleanField): return u'✓' if field.data else u'✕' return escape(field.data)
# -*- coding: utf-8 -*- """Jinja environment filters for Pynuts.""" from flask import escape from flask.ext.wtf import ( QuerySelectField, QuerySelectMultipleField, BooleanField) def data(field): """Field data beautifier. QuerySelectMultipleField Renders comma-separated data. QuerySelectField Renders the selected value. BooleanField Renders '✓' or '✕' Example: .. sourcecode:: html+jinja <dd>{{ field | data }}</dd> """ if isinstance(field, QuerySelectMultipleField): if field.data: return escape( u', '.join(field.get_label(data) for data in field.data)) else: return u'∅' elif isinstance(field, QuerySelectField): if field.data: return escape(field.get_label(field.data)) elif isinstance(field, BooleanField): return u'✓' if field.data else u'✕' return escape(field.data)
Return an "empty sequence" character instead of an empty list for empty select fields
Return an "empty sequence" character instead of an empty list for empty select fields
Python
bsd-3-clause
Kozea/Pynuts,Kozea/Pynuts,Kozea/Pynuts
7111860577c921dc3d1602fa16b22ddfb45b69ed
lots/migrations/0002_auto_20170717_2115.py
lots/migrations/0002_auto_20170717_2115.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-18 02:15 from __future__ import unicode_literals from django.db import models, migrations def load_data(apps, schema_editor): LotType = apps.get_model("lots", "LotType") LotType(name="Casa").save() LotType(name="Lote").save() class Migration(migrations.Migration): dependencies = [ ('lots', '0001_initial'), ] operations = [ migrations.RunPython(load_data) ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-18 02:15 from __future__ import unicode_literals from django.db import models, migrations from lots.models import LotType def load_data(apps, schema_editor): LotType = apps.get_model("lots", "LotType") LotType(name="Casa").save() LotType(name="Lote").save() def remove_data(apps, schema_editor): LotType.objects.all().delete() class Migration(migrations.Migration): dependencies = [ ('lots', '0001_initial'), ] operations = [ migrations.RunPython(load_data, remove_data) ]
Add reverse action to importing default lot types
Add reverse action to importing default lot types
Python
mpl-2.0
jackbravo/condorest-django,jackbravo/condorest-django,jackbravo/condorest-django
78f55cf57d88378e59cf1399d7ef80082d3f9555
bluebottle/partners/serializers.py
bluebottle/partners/serializers.py
from bluebottle.bluebottle_drf2.serializers import ImageSerializer from bluebottle.projects.models import PartnerOrganization from bluebottle.projects.serializers import ProjectPreviewSerializer as BaseProjectPreviewSerializer from rest_framework import serializers # This is a bit of a hack. We have an existing ProjectPreviewSerializer in /bb_projects/serializers. # However, that serializer depends on properties calculated in the ProjectPreview view. Therefore, we # cannot re-use the serializer. The serialzier below is the same, except it has the fields "people_requested" # and "people_registered" removed. from bluebottle.utils.serializer_dispatcher import get_serializer_class class ProjectPreviewSerializer(BaseProjectPreviewSerializer): task_count = serializers.IntegerField(source='task_count') owner = get_serializer_class('AUTH_USER_MODEL', 'preview')(source='owner') partner = serializers.SlugRelatedField(slug_field='slug', source='partner_organization') is_funding = serializers.Field() class Meta(BaseProjectPreviewSerializer): model = BaseProjectPreviewSerializer.Meta.model fields = ('id', 'title', 'image', 'status', 'pitch', 'country', 'task_count', 'allow_overfunding', 'latitude', 'longitude', 'is_campaign', 'amount_asked', 'amount_donated', 'amount_needed', 'amount_extra', 'deadline', 'status', 'owner', 'partner', 'is_funding') class PartnerOrganizationPreviewSerializer(serializers.ModelSerializer): id = serializers.CharField(source='slug', read_only=True) class Meta: model = PartnerOrganization fields = ('id', 'name', ) class PartnerOrganizationSerializer(PartnerOrganizationPreviewSerializer): projects = ProjectPreviewSerializer(source='projects') image = ImageSerializer(required=False) description = serializers.CharField(source='description') class Meta: model = PartnerOrganization fields = ('id', 'name', 'projects', 'description', 'image')
from bluebottle.bluebottle_drf2.serializers import ImageSerializer from bluebottle.projects.models import PartnerOrganization from bluebottle.projects.serializers import ProjectPreviewSerializer from rest_framework import serializers class PartnerOrganizationPreviewSerializer(serializers.ModelSerializer): id = serializers.CharField(source='slug', read_only=True) class Meta: model = PartnerOrganization fields = ('id', 'name', ) class PartnerOrganizationSerializer(PartnerOrganizationPreviewSerializer): projects = ProjectPreviewSerializer(source='projects') image = ImageSerializer(required=False) description = serializers.CharField(source='description') class Meta: model = PartnerOrganization fields = ('id', 'name', 'projects', 'description', 'image')
Fix partner project serializer. (The comment was outdated btw)
Fix partner project serializer. (The comment was outdated btw)
Python
bsd-3-clause
onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle
b973a1686f269044e670704b56c07ca79336c29c
mythril/laser/ethereum/strategy/basic.py
mythril/laser/ethereum/strategy/basic.py
class DepthFirstSearchStrategy: def __init__(self, content, max_depth): self.content = content self.max_depth = max_depth def __iter__(self): return self def __next__(self): try: global_state = self.content.pop(0) if global_state.mstate.depth >= self.max_depth: return self.__next__() return global_state except IndexError: raise StopIteration()
""" This module implements basic symbolic execution search strategies """ class DepthFirstSearchStrategy: """ Implements a depth first search strategy I.E. Follow one path to a leaf, and then continue to the next one """ def __init__(self, work_list, max_depth): self.work_list = work_list self.max_depth = max_depth def __iter__(self): return self def __next__(self): """ Picks the next state to execute """ try: # This strategies assumes that new states are appended at the end of the work_list # By taking the last element we effectively pick the "newest" states, which amounts to dfs global_state = self.work_list.pop() if global_state.mstate.depth >= self.max_depth: return self.__next__() return global_state except IndexError: raise StopIteration()
Add documentation and fix pop
Add documentation and fix pop
Python
mit
b-mueller/mythril,b-mueller/mythril,b-mueller/mythril,b-mueller/mythril
052c0cfd1ce21b36c9c9a44193e3a9c89ca871f1
ciscripts/coverage/bii/coverage.py
ciscripts/coverage/bii/coverage.py
# /ciscripts/coverage/bii/coverage.py # # Submit coverage totals for a bii project to coveralls # # See /LICENCE.md for Copyright information """Submit coverage totals for a bii project to coveralls.""" import errno import os from contextlib import contextmanager @contextmanager def _bii_deps_in_place(cont): """Move bii project dependencies into layout. The coverage step may require these dependencies to be present. """ bii_dir = os.path.join(cont.named_cache_dir("cmake-build"), "bii") try: os.rename(bii_dir, os.path.join(os.getcwd(), "bii")) except OSError as error: if error.errno != errno.ENOENT: raise error def run(cont, util, shell, argv=None): """Submit coverage total to coveralls, with bii specific preparation.""" with _bii_deps_in_place(cont): util.fetch_and_import("coverage/cmake/coverage.py").run(cont, util, shell, argv)
# /ciscripts/coverage/bii/coverage.py # # Submit coverage totals for a bii project to coveralls # # See /LICENCE.md for Copyright information """Submit coverage totals for a bii project to coveralls.""" import errno import os from contextlib import contextmanager def _move_ignore_enoent(src, dst): """Move src to dst, ignoring ENOENT.""" try: os.rename(src, dst) except OSError as error: if error.errno != errno.ENOENT: raise error @contextmanager def _bii_deps_in_place(cont): """Move bii project dependencies into layout. The coverage step may require these dependencies to be present. """ bii_dir = os.path.join(cont.named_cache_dir("cmake-build"), "bii") _move_ignore_enoent(bii_dir, os.path.join(os.getcwd(), "bii")) try: yield finally: _move_ignore_enoent(os.path.join(os.getcwd(), "bii"), bii_dir) def run(cont, util, shell, argv=None): """Submit coverage total to coveralls, with bii specific preparation.""" with _bii_deps_in_place(cont): util.fetch_and_import("coverage/cmake/coverage.py").run(cont, util, shell, argv)
Make _bii_deps_in_place actually behave like a context manager
bii: Make _bii_deps_in_place actually behave like a context manager
Python
mit
polysquare/polysquare-ci-scripts,polysquare/polysquare-ci-scripts
08300895dc8d2abb740dd71b027e9acda8bb84dd
chatterbot/ext/django_chatterbot/views.py
chatterbot/ext/django_chatterbot/views.py
from django.views.generic import View from django.http import JsonResponse from django.conf import settings class ChatterBotView(View): def post(self, request, *args, **kwargs): input_statement = request.POST.get('text') response_data = settings.CHATTERBOT.get_response(input_statement) return JsonResponse(response_data, status=200) def get(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.' } # Return a method not allowed response return JsonResponse(data, status=405) def patch(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.' } # Return a method not allowed response return JsonResponse(data, status=405) def delete(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.' } # Return a method not allowed response return JsonResponse(data, status=405)
from django.views.generic import View from django.http import JsonResponse from django.conf import settings from chatterbot import ChatBot class ChatterBotView(View): chatterbot = ChatBot( settings.CHATTERBOT['NAME'], storage_adapter='chatterbot.adapters.storage.DjangoStorageAdapter', input_adapter='chatterbot.adapters.input.VariableInputTypeAdapter', output_adapter='chatterbot.adapters.output.OutputFormatAdapter', output_format='json' ) def post(self, request, *args, **kwargs): input_statement = request.POST.get('text') response_data = self.chatterbot.get_response(input_statement) return JsonResponse(response_data, status=200) def get(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.' } # Return a method not allowed response return JsonResponse(data, status=405) def patch(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.' } # Return a method not allowed response return JsonResponse(data, status=405) def delete(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.' } # Return a method not allowed response return JsonResponse(data, status=405)
Initialize ChatterBot in django view module instead of settings.
Initialize ChatterBot in django view module instead of settings.
Python
bsd-3-clause
Reinaesaya/OUIRL-ChatBot,Reinaesaya/OUIRL-ChatBot,vkosuri/ChatterBot,davizucon/ChatterBot,gunthercox/ChatterBot,maclogan/VirtualPenPal,Gustavo6046/ChatterBot
5c0c2f470451c69a2b4cbba3746d26207c6b17a9
lang/__init__.py
lang/__init__.py
from . import tokenizer, ast, codegen import sys, os, subprocess TRIPLES = { 'darwin': 'x86_64-apple-darwin11.0.0', 'linux2': 'x86_64-pc-linux-gnu', } def llir(fn, full=True): src = codegen.source(ast.parse(tokenizer.tokenize(open(fn)))) if not full: return src std = [] for fn in sorted(os.listdir('rt')): with open(os.path.join('rt', fn)) as f: std.append(f.read() + '\n') triple = 'target triple = "%s"\n\n' % TRIPLES[sys.platform] return triple + ''.join(std) + src def compile(fn, outfn): llfn = fn + '.ll' with open(llfn, 'w') as f: f.write(llir(fn)) subprocess.check_call(('clang', '-o', outfn, llfn)) os.unlink(llfn)
from . import tokenizer, ast, codegen import sys, os, subprocess BASE = os.path.dirname(__path__[0]) RT_DIR = os.path.join(BASE, 'rt') TRIPLES = { 'darwin': 'x86_64-apple-darwin11.0.0', 'linux2': 'x86_64-pc-linux-gnu', } def llir(fn, full=True): src = codegen.source(ast.parse(tokenizer.tokenize(open(fn)))) if not full: return src std = [] for fn in sorted(os.listdir(RT_DIR)): with open(os.path.join(RT_DIR, fn)) as f: std.append(f.read() + '\n') triple = 'target triple = "%s"\n\n' % TRIPLES[sys.platform] return triple + ''.join(std) + src def compile(fn, outfn): llfn = fn + '.ll' with open(llfn, 'w') as f: f.write(llir(fn)) subprocess.check_call(('clang', '-o', outfn, llfn)) os.unlink(llfn)
Fix up path to runtime library directory.
Fix up path to runtime library directory.
Python
mit
djc/runa,djc/runa,djc/runa,djc/runa
129cd22de51d58cc956ca5586fc15cd2e247446b
gpkitmodels/GP/aircraft/prop/propeller.py
gpkitmodels/GP/aircraft/prop/propeller.py
" propeller model " from numpy import pi from gpkit import Model, parse_variables, SignomialsEnabled, SignomialEquality class Propeller(Model): """ Propeller Model Variables --------- R 10 [m] prop radius """ def setup(self): exec parse_variables(Propeller.__doc__) def performance(state): return Propeller_Performance(self, state) class Propeller_Performance(Model): """ Propeller Model Variables --------- T [N] thrust Tc [-] coefficient of thrust etaadd 0.7 [-] swirl and nonuniformity losses etav 0.85 [-] viscous losses etai [-] inviscid losses eta [-] overall efficiency z1 self.helper [-] efficiency helper 1 z2 [-] efficiency helper 2 """ def helper(self, c): return 2. - 1./c[self.etaadd] def setup(self, state): exec parse_variables(Propeller.__doc__) V = state.V rho = state.rho constraints = [eta <= etav*etai, Tc == T/(0.5*rho*V**2*pi*R**2), z2 >= Tc + 1, etai*(z1 + z2**0.5/etaadd) <= 2] return constraints
" propeller model " from numpy import pi from gpkit import Model, parse_variables, SignomialsEnabled, SignomialEquality class Propeller(Model): """ Propeller Model Variables --------- R 10 [m] prop radius W 10 [lbf] prop weight """ def setup(self): exec parse_variables(Propeller.__doc__) def performance(state): return Propeller_Performance(self, state) class Propeller_Performance(Model): """ Propeller Model Variables --------- T [N] thrust Tc [-] coefficient of thrust etaadd 0.7 [-] swirl and nonuniformity losses etav 0.85 [-] viscous losses etai [-] inviscid losses eta [-] overall efficiency z1 self.helper [-] efficiency helper 1 z2 [-] efficiency helper 2 """ def helper(self, c): return 2. - 1./c[self.etaadd] def setup(self,parent, state): exec parse_variables(Propeller.__doc__) V = state.V rho = state.rho R = parent.R constraints = [eta <= etav*etai, Tc == T/(0.5*rho*V**2*pi*R**2), z2 >= Tc + 1, etai*(z1 + z2**0.5/etaadd) <= 2] return constraints
Add prop structure and performance models
Add prop structure and performance models
Python
mit
convexengineering/gplibrary,convexengineering/gplibrary
570bbe3add6a19a7ec6c14adfa04da76d14aa740
common/templatetags/lutris.py
common/templatetags/lutris.py
import copy from django import template from django.conf import settings from games import models register = template.Library() def get_links(user_agent): systems = ['ubuntu', 'fedora', 'linux'] downloads = copy.copy(settings.DOWNLOADS) main_download = None for system in systems: if system in user_agent: main_download = {system: settings.DOWNLOADS[system]} downloads.pop(system) if not main_download: main_download = {'linux': downloads.pop('linux')} return (main_download, downloads) @register.inclusion_tag('includes/download_links.html', takes_context=True) def download_links(context): request = context['request'] user_agent = request.META.get('HTTP_USER_AGENT', '').lower() context['main_download'], context['downloads'] = get_links(user_agent) return context @register.inclusion_tag('includes/featured_slider.html', takes_context=True) def featured_slider(context): context['featured_contents'] = models.Featured.objects.all() return context @register.inclusion_tag('includes/latest_games.html', takes_context=True) def latest_games(context): games = models.Game.objects.published().order_by('-created')[:5] context['latest_games'] = games return context
import copy from django import template from django.conf import settings from games import models register = template.Library() def get_links(user_agent): systems = ['ubuntu', 'fedora', 'linux'] downloads = copy.copy(settings.DOWNLOADS) main_download = None for system in systems: if system in user_agent: main_download = {system: downloads[system]} downloads.pop(system) if not main_download: main_download = {'linux': downloads.pop('linux')} return (main_download, downloads) @register.inclusion_tag('includes/download_links.html', takes_context=True) def download_links(context): request = context['request'] user_agent = request.META.get('HTTP_USER_AGENT', '').lower() context['main_download'], context['downloads'] = get_links(user_agent) return context @register.inclusion_tag('includes/featured_slider.html', takes_context=True) def featured_slider(context): context['featured_contents'] = models.Featured.objects.all() return context @register.inclusion_tag('includes/latest_games.html', takes_context=True) def latest_games(context): games = models.Game.objects.published().order_by('-created')[:5] context['latest_games'] = games return context
Fix bug in download links
Fix bug in download links
Python
agpl-3.0
Turupawn/website,Turupawn/website,Turupawn/website,lutris/website,Turupawn/website,lutris/website,lutris/website,lutris/website
2c63efeb705637a068c909be7dc72f18e90561bf
cloudbridge/cloud/providers/azure/test/test_azure_resource_group.py
cloudbridge/cloud/providers/azure/test/test_azure_resource_group.py
from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase class AzureResourceGroupTestCase(ProviderTestBase): def test_resource_group_create(self): resource_group_params = {'location': self.provider.region_name} rg = self.provider.azure_client. \ create_resource_group(self.provider.resource_group, resource_group_params) print("Create Resource - " + str(rg)) self.assertTrue( rg.name == "cloudbridge", "Resource Group should be Cloudbridge") def test_resource_group_get(self): rg = self.provider.azure_client.get_resource_group('MyGroup') print("Get Resource - " + str(rg)) self.assertTrue( rg.name == "testResourceGroup", "Resource Group should be Cloudbridge")
from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase class AzureResourceGroupTestCase(ProviderTestBase): def test_resource_group_create(self): resource_group_params = {'location': self.provider.region_name} rg = self.provider.azure_client. \ create_resource_group(self.provider.resource_group, resource_group_params) print("Create Resource - " + str(rg)) self.assertTrue( rg.name == self.provider.resource_group, "Resource Group should be {0}".format(rg.name)) def test_resource_group_get(self): rg = self.provider.azure_client.get_resource_group('MyGroup') print("Get Resource - " + str(rg)) self.assertTrue( rg.name == "testResourceGroup", "Resource Group should be {0}".format(rg.name))
Update resource group unit test
Update resource group unit test
Python
mit
ms-azure-cloudbroker/cloudbridge
d535cf76b3129c0e5b6908a720bdf3e3a804e41b
mopidy/mixers/gstreamer_software.py
mopidy/mixers/gstreamer_software.py
import multiprocessing from mopidy.mixers import BaseMixer from mopidy.utils.process import pickle_connection class GStreamerSoftwareMixer(BaseMixer): """Mixer which uses GStreamer to control volume in software.""" def __init__(self, *args, **kwargs): super(GStreamerSoftwareMixer, self).__init__(*args, **kwargs) def _get_volume(self): my_end, other_end = multiprocessing.Pipe() self.backend.output_queue.put({ 'command': 'get_volume', 'reply_to': pickle_connection(other_end), }) my_end.poll(None) return my_end.recv() def _set_volume(self, volume): self.backend.output_queue.put({ 'command': 'set_volume', 'volume': volume, })
from mopidy.mixers import BaseMixer class GStreamerSoftwareMixer(BaseMixer): """Mixer which uses GStreamer to control volume in software.""" def __init__(self, *args, **kwargs): super(GStreamerSoftwareMixer, self).__init__(*args, **kwargs) def _get_volume(self): return self.backend.output.get_volume() def _set_volume(self, volume): self.backend.output.set_volume(volume)
Update GStreamer software mixer to use new output API
Update GStreamer software mixer to use new output API
Python
apache-2.0
SuperStarPL/mopidy,bacontext/mopidy,dbrgn/mopidy,ali/mopidy,quartz55/mopidy,adamcik/mopidy,liamw9534/mopidy,ali/mopidy,swak/mopidy,liamw9534/mopidy,abarisain/mopidy,swak/mopidy,mopidy/mopidy,pacificIT/mopidy,swak/mopidy,diandiankan/mopidy,adamcik/mopidy,bencevans/mopidy,hkariti/mopidy,glogiotatidis/mopidy,vrs01/mopidy,ZenithDK/mopidy,diandiankan/mopidy,bencevans/mopidy,tkem/mopidy,mokieyue/mopidy,jodal/mopidy,ali/mopidy,priestd09/mopidy,quartz55/mopidy,mopidy/mopidy,rawdlite/mopidy,kingosticks/mopidy,woutervanwijk/mopidy,jmarsik/mopidy,ali/mopidy,kingosticks/mopidy,dbrgn/mopidy,vrs01/mopidy,bacontext/mopidy,mopidy/mopidy,bencevans/mopidy,ZenithDK/mopidy,pacificIT/mopidy,swak/mopidy,rawdlite/mopidy,tkem/mopidy,dbrgn/mopidy,priestd09/mopidy,jcass77/mopidy,jcass77/mopidy,abarisain/mopidy,quartz55/mopidy,mokieyue/mopidy,quartz55/mopidy,jcass77/mopidy,hkariti/mopidy,SuperStarPL/mopidy,glogiotatidis/mopidy,vrs01/mopidy,kingosticks/mopidy,priestd09/mopidy,diandiankan/mopidy,SuperStarPL/mopidy,tkem/mopidy,jmarsik/mopidy,rawdlite/mopidy,dbrgn/mopidy,SuperStarPL/mopidy,jodal/mopidy,adamcik/mopidy,jmarsik/mopidy,vrs01/mopidy,rawdlite/mopidy,jodal/mopidy,ZenithDK/mopidy,mokieyue/mopidy,glogiotatidis/mopidy,glogiotatidis/mopidy,ZenithDK/mopidy,bacontext/mopidy,hkariti/mopidy,pacificIT/mopidy,hkariti/mopidy,mokieyue/mopidy,diandiankan/mopidy,bacontext/mopidy,pacificIT/mopidy,bencevans/mopidy,jmarsik/mopidy,woutervanwijk/mopidy,tkem/mopidy
104c136488d468f26c7fe247d0548636cbf3c6fe
random_4.py
random_4.py
""" How to generate a random 4 digit number not starting with 0 and having unique digits in python? """ import random l = [0,1,2,3,4,5,6,7,8,9] random.shuffle(l) if l[0] == 0: print(''.join(map(str, l[1:5]))) else: print(''.join(map(str, l[0:4])))
""" How to generate a random 4 digit number not starting with 0 and having unique digits in python? """ import random # 1. l = [0,1,2,3,4,5,6,7,8,9] random.shuffle(l) if l[0] == 0: pos = random.choice(range(1, len(l))) l[0], l[pos] = l[pos], l[0] print(''.join(map(str, l[0:4]))) # 2. # We create a set of digits: {0, 1, .... 9} digits = set(range(10)) # We generate a random integer, 1 <= first <= 9 first = random.randint(1, 9) # We remove it from our set, then take a sample of # 3 distinct elements from the remaining values last_3 = random.sample(digits - {first}, 3) print(str(first) + ''.join(map(str, last_3))) # 3. numbers = [0] while numbers[0] == 0: numbers = random.sample(range(10), 4) print(''.join(map(str, numbers)))
Fix of shuffle. There should be random swap of leading zero with one from nine (non-zero) positions.
Fix of shuffle. There should be random swap of leading zero with one from nine (non-zero) positions.
Python
mit
foobar167/junkyard,foobar167/junkyard,foobar167/junkyard,foobar167/junkyard,foobar167/junkyard,foobar167/junkyard
863b12e503559b24de29407cd674d432bdcbbfc0
cs251tk/referee/send_email.py
cs251tk/referee/send_email.py
import smtplib def send_email(msg): # Send the message via our own SMTP server. with smtplib.SMTP_SSL('smtp.gmail.com', 465) as s: # s.starttls() s.set_debuglevel(2) s.send_message(msg)
import smtplib def send_email(msg): # Send the message via our own SMTP server. with smtplib.SMTP_SSL('smtp.gmail.com', 465) as s: s.send_message(msg)
Remove somore more lines related to email
Remove somore more lines related to email
Python
mit
StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit
1c0d42889b721cf68deb199711d8ae7700c40b66
marcottimls/tools/logsetup.py
marcottimls/tools/logsetup.py
import os import json import logging import logging.config def setup_logging(log_path, settings_path="logging.json", default_level=logging.INFO): """Setup logging configuration""" path = settings_path if os.path.exists(path): with open(path, 'rt') as f: config = json.load(f) config['handlers']['main']['filename'] = log_path logging.config.dictConfig(config) else: logging.basicConfig(level=default_level)
import os import json import logging import logging.config def setup_logging(settings_path="logging.json", default_level=logging.INFO): """Setup logging configuration""" path = settings_path if os.path.exists(path): with open(path, 'rt') as f: config = json.load(f) logging.config.dictConfig(config) else: logging.basicConfig(level=default_level)
Remove kludge from setup_logging as no longer necessary
Remove kludge from setup_logging as no longer necessary
Python
mit
soccermetrics/marcotti-mls
93be3585d269360641091f18a6443979eb8f1f98
cito/dump_db.py
cito/dump_db.py
"""Delete all documents every second forever""" __author__ = 'tunnell' import sys import time import json import pymongo if __name__ == "__main__": c = pymongo.MongoClient() db = c.data collection = db.test # Key to sort by so we can use an index for quick query sort_key = [("_id", pymongo.ASCENDING), ("triggertime", pymongo.ASCENDING)] # Index for quick query collection.create_index(sort_key, dropDups=True) # Loop until Ctrl-C or error while (1): # This try-except catches Ctrl-C and error try: # Non-sense query that is in index query = {"triggertime": {'$gt': 0}} # Perform query cursor = collection.find(query, fields=['triggertime']).sort(sort_key) # Are we using index for quick queries? Not always true if there # are no documents in the collection... print('Using index:', cursor.explain()['indexOnly']) # Stats on how the delete worked. Write concern (w=1) is on. print(json.dumps(collection.remove(query), indent=4, sort_keys=True, w=1)) # Wait a second so we don't query the DB too much time.sleep(1) except pymongo.errors.OperationFailure as e: print('MongoDB error:', e) except KeyboardInterrupt: print("Ctrl-C caught so exiting.") sys.exit(0)
"""Delete all documents every second forever""" __author__ = 'tunnell' import sys import time import json import pymongo if __name__ == "__main__": c = pymongo.MongoClient() db = c.data collection = db.test # Key to sort by so we can use an index for quick query sort_key = [("_id", pymongo.ASCENDING), ("triggertime", pymongo.ASCENDING)] # Index for quick query collection.create_index(sort_key, dropDups=True) # Loop until Ctrl-C or error while (1): # This try-except catches Ctrl-C and error try: # Non-sense query that is in index query = {"triggertime": {'$gt': 0}} # Perform query cursor = collection.find(query, fields=['triggertime']).sort(sort_key) # Are we using index for quick queries? Not always true if there # are no documents in the collection... print('Using index:', cursor.explain()['indexOnly']) # Stats on how the delete worked. Write concern is on. print(json.dumps(collection.remove(query), indent=4, sort_keys=True)) # Wait a second so we don't query the DB too much time.sleep(1) except pymongo.errors.OperationFailure as e: print('MongoDB error:', e) except KeyboardInterrupt: print("Ctrl-C caught so exiting.") sys.exit(0)
Write concern bug fix in constantly deleting DB. It's on by default and w=1 does nothing.
BUG: Write concern bug fix in constantly deleting DB. It's on by default and w=1 does nothing.
Python
bsd-3-clause
tunnell/wax,tunnell/wax,tunnell/wax
44ed4ceffcbf95ed42e4bdebcc87a7137a97de50
been/source/markdown.py
been/source/markdown.py
from been.core import DirectorySource, source_registry class Markdown(DirectorySource): kind = 'markdown' def process_event(self, event): lines = event['content'].splitlines() event['title'] = lines[0] event['content'] = "\n".join(lines[1:]) event['summary'] = event['content'] return event source_registry.add(Markdown)
from been.core import DirectorySource, source_registry class MarkdownDirectory(DirectorySource): kind = 'markdown' def process_event(self, event): lines = event['content'].splitlines() event['title'] = lines[0] event['content'] = "\n".join(lines[1:]) event['summary'] = event['content'] return event source_registry.add(MarkdownDirectory)
Rename Markdown source to MarkdownDirectory.
Rename Markdown source to MarkdownDirectory.
Python
bsd-3-clause
chromakode/been
a28f6a45f37d906a9f9901d46d683c3ca5406da4
code/csv2map.py
code/csv2map.py
# csv2map.py -- Convert .csv into a .map format # Description of MAP format: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#map # # jean-daniel.granet@mines-paristech.fr import sys import argparse def main(): parser = argparse.ArgumentParser(description='Convert .csv to .map') parser.add_argument('csv', help="""CSV file to convert. Fields are : Index,Illumina_SNP_Name,Alternative_SNP_Name,Chromosome,Build36_Position,Build37_Position,new_rsname,Strand,TopAlleles,ForwardAlleles,DesignAlleles """) parser.add_argument('map', help='MAP file to create') args = parser.parse_args() # read the csv file and convert it into a MAP file with open(args.csv, 'r') as fdr: with open(args.map, 'w') as fdw: for line in fdr: line_split = line.split(',') fdw.write("%s\n" % "\n".join(["%s %s 0 %s" % (line_split[3], line_split[2], line_split[5])])) fdw.close() fdr.close() if __name__ == "__main__": main()
# csv2map.py -- Convert .csv into a .map format # Description of MAP format: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#map # # jean-daniel.granet@mines-paristech.fr import sys import argparse def main(): parser = argparse.ArgumentParser(description='Convert .csv to .map') parser.add_argument('csv', help="""CSV file to convert. Fields are : Index,Illumina_SNP_Name,Alternative_SNP_Name,Chromosome,Build36_Position,Build37_Position,new_rsname,Strand,TopAlleles,ForwardAlleles,DesignAlleles """) parser.add_argument('map', help='MAP file to create. Fields will be : num chromosome (1-22, X, Y or 0 if unplaced), snp identifier, Genetic distance (morgans) = 0, Base-pair position (bp units)') args = parser.parse_args() # read the csv file and convert it into a MAP file with open(args.csv, 'r') as fdr: with open(args.map, 'w') as fdw: for line in fdr: line_split = line.split(',') fdw.write("%s\n" % "\n".join(["%s %s 0 %s" % (line_split[3], line_split[2], line_split[5])])) fdw.close() fdr.close() if __name__ == "__main__": main()
Add infos about MAP file
Add infos about MAP file
Python
mit
chagaz/sfan,chagaz/sfan,chagaz/sfan,chagaz/sfan,chagaz/sfan
75225c176135b6d17c8f10ea67dabb4b0fc02505
nodeconductor/iaas/migrations/0009_add_min_ram_and_disk_to_image.py
nodeconductor/iaas/migrations/0009_add_min_ram_and_disk_to_image.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django_fsm class Migration(migrations.Migration): dependencies = [ ('iaas', '0008_add_instance_restarting_state'), ] operations = [ migrations.AddField( model_name='image', name='min_disk', field=models.PositiveIntegerField(default=0, help_text='Minimum disk size in MiB'), preserve_default=True, ), migrations.AddField( model_name='image', name='min_ram', field=models.PositiveIntegerField(default=0, help_text='Minimum memory size in MiB'), preserve_default=True, ), migrations.AlterField( model_name='instance', name='state', field=django_fsm.FSMIntegerField(default=1, help_text='WARNING! Should not be changed manually unless you really know what you are doing.', max_length=1, choices=[(1, 'Provisioning Scheduled'), (2, 'Provisioning'), (3, 'Online'), (4, 'Offline'), (5, 'Starting Scheduled'), (6, 'Starting'), (7, 'Stopping Scheduled'), (8, 'Stopping'), (9, 'Erred'), (10, 'Deletion Scheduled'), (11, 'Deleting'), (13, 'Resizing Scheduled'), (14, 'Resizing'), (15, 'Restarting Scheduled'), (16, 'Restarting')]), preserve_default=True, ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django_fsm class Migration(migrations.Migration): dependencies = [ ('iaas', '0008_add_instance_restarting_state'), ] operations = [ migrations.AddField( model_name='image', name='min_disk', field=models.PositiveIntegerField(default=0, help_text='Minimum disk size in MiB'), preserve_default=True, ), migrations.AddField( model_name='image', name='min_ram', field=models.PositiveIntegerField(default=0, help_text='Minimum memory size in MiB'), preserve_default=True, ), ]
Remove field duplication from migrations(nc-301)
Remove field duplication from migrations(nc-301)
Python
mit
opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor
496fc83101155bd0cd2fb4256e2878007aec8eaa
api/base/exceptions.py
api/base/exceptions.py
from rest_framework import status from rest_framework.exceptions import APIException def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, list): for reason in value: errors.append({'detail': reason, 'meta': {'field': key}}) else: errors.append({'detail': value, 'meta': {'field': key}}) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.')
from rest_framework import status from rest_framework.exceptions import APIException def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, list): for reason in value: errors.append({'source': {key: reason}}) else: errors.append({'source': {key: value}}) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.')
Use source key instead of meta and detail fields
Use source key instead of meta and detail fields
Python
apache-2.0
asanfilippo7/osf.io,emetsger/osf.io,rdhyee/osf.io,cosenal/osf.io,haoyuchen1992/osf.io,haoyuchen1992/osf.io,DanielSBrown/osf.io,doublebits/osf.io,mluke93/osf.io,amyshi188/osf.io,monikagrabowska/osf.io,doublebits/osf.io,icereval/osf.io,sloria/osf.io,pattisdr/osf.io,ZobairAlijan/osf.io,adlius/osf.io,hmoco/osf.io,Johnetordoff/osf.io,zachjanicki/osf.io,mluke93/osf.io,cosenal/osf.io,chrisseto/osf.io,caseyrygt/osf.io,caseyrollins/osf.io,GageGaskins/osf.io,saradbowman/osf.io,HalcyonChimera/osf.io,petermalcolm/osf.io,CenterForOpenScience/osf.io,CenterForOpenScience/osf.io,billyhunt/osf.io,zamattiac/osf.io,chrisseto/osf.io,samchrisinger/osf.io,brandonPurvis/osf.io,Ghalko/osf.io,petermalcolm/osf.io,alexschiller/osf.io,felliott/osf.io,cwisecarver/osf.io,KAsante95/osf.io,DanielSBrown/osf.io,aaxelb/osf.io,hmoco/osf.io,kch8qx/osf.io,zachjanicki/osf.io,baylee-d/osf.io,emetsger/osf.io,alexschiller/osf.io,samanehsan/osf.io,billyhunt/osf.io,amyshi188/osf.io,mluo613/osf.io,abought/osf.io,KAsante95/osf.io,kwierman/osf.io,ticklemepierce/osf.io,aaxelb/osf.io,samchrisinger/osf.io,HalcyonChimera/osf.io,zachjanicki/osf.io,acshi/osf.io,chennan47/osf.io,ZobairAlijan/osf.io,CenterForOpenScience/osf.io,caneruguz/osf.io,mattclark/osf.io,kwierman/osf.io,cwisecarver/osf.io,DanielSBrown/osf.io,kwierman/osf.io,Nesiehr/osf.io,mluo613/osf.io,samanehsan/osf.io,mluke93/osf.io,RomanZWang/osf.io,Ghalko/osf.io,alexschiller/osf.io,ZobairAlijan/osf.io,danielneis/osf.io,mluo613/osf.io,TomBaxter/osf.io,chrisseto/osf.io,chennan47/osf.io,RomanZWang/osf.io,billyhunt/osf.io,mattclark/osf.io,chennan47/osf.io,saradbowman/osf.io,njantrania/osf.io,wearpants/osf.io,GageGaskins/osf.io,danielneis/osf.io,brianjgeiger/osf.io,felliott/osf.io,billyhunt/osf.io,TomBaxter/osf.io,leb2dg/osf.io,wearpants/osf.io,cwisecarver/osf.io,erinspace/osf.io,doublebits/osf.io,wearpants/osf.io,abought/osf.io,monikagrabowska/osf.io,emetsger/osf.io,icereval/osf.io,alexschiller/osf.io,amyshi188/osf.io,binoculars/osf.io,haoyuchen1992/osf.io,kch8qx/osf.io,RomanZWang/osf.io,acshi/osf.io,njantrania/osf.io,leb2dg/osf.io,kch8qx/osf.io,cslzchen/osf.io,mluo613/osf.io,CenterForOpenScience/osf.io,samanehsan/osf.io,Ghalko/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,njantrania/osf.io,brianjgeiger/osf.io,caseyrygt/osf.io,monikagrabowska/osf.io,ZobairAlijan/osf.io,RomanZWang/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,zachjanicki/osf.io,acshi/osf.io,hmoco/osf.io,GageGaskins/osf.io,cslzchen/osf.io,petermalcolm/osf.io,mattclark/osf.io,monikagrabowska/osf.io,doublebits/osf.io,ticklemepierce/osf.io,arpitar/osf.io,caseyrollins/osf.io,billyhunt/osf.io,Nesiehr/osf.io,ticklemepierce/osf.io,cosenal/osf.io,caseyrygt/osf.io,erinspace/osf.io,laurenrevere/osf.io,leb2dg/osf.io,rdhyee/osf.io,Johnetordoff/osf.io,SSJohns/osf.io,laurenrevere/osf.io,mluo613/osf.io,zamattiac/osf.io,SSJohns/osf.io,jnayak1/osf.io,mfraezz/osf.io,brianjgeiger/osf.io,ticklemepierce/osf.io,icereval/osf.io,emetsger/osf.io,pattisdr/osf.io,njantrania/osf.io,amyshi188/osf.io,adlius/osf.io,chrisseto/osf.io,DanielSBrown/osf.io,Nesiehr/osf.io,crcresearch/osf.io,pattisdr/osf.io,asanfilippo7/osf.io,caneruguz/osf.io,mfraezz/osf.io,brandonPurvis/osf.io,zamattiac/osf.io,wearpants/osf.io,rdhyee/osf.io,KAsante95/osf.io,baylee-d/osf.io,jnayak1/osf.io,jnayak1/osf.io,doublebits/osf.io,cwisecarver/osf.io,mfraezz/osf.io,caneruguz/osf.io,kch8qx/osf.io,crcresearch/osf.io,KAsante95/osf.io,brandonPurvis/osf.io,SSJohns/osf.io,sloria/osf.io,Nesiehr/osf.io,samanehsan/osf.io,jnayak1/osf.io,danielneis/osf.io,arpitar/osf.io,baylee-d/osf.io,sloria/osf.io,kch8qx/osf.io,cslzchen/osf.io,binoculars/osf.io,acshi/osf.io,caseyrollins/osf.io,monikagrabowska/osf.io,rdhyee/osf.io,Johnetordoff/osf.io,mluke93/osf.io,petermalcolm/osf.io,asanfilippo7/osf.io,kwierman/osf.io,abought/osf.io,caseyrygt/osf.io,Ghalko/osf.io,erinspace/osf.io,cslzchen/osf.io,brandonPurvis/osf.io,GageGaskins/osf.io,zamattiac/osf.io,haoyuchen1992/osf.io,mfraezz/osf.io,TomHeatwole/osf.io,acshi/osf.io,leb2dg/osf.io,laurenrevere/osf.io,TomHeatwole/osf.io,danielneis/osf.io,crcresearch/osf.io,samchrisinger/osf.io,abought/osf.io,adlius/osf.io,asanfilippo7/osf.io,adlius/osf.io,TomBaxter/osf.io,aaxelb/osf.io,cosenal/osf.io,felliott/osf.io,brandonPurvis/osf.io,felliott/osf.io,RomanZWang/osf.io,arpitar/osf.io,binoculars/osf.io,TomHeatwole/osf.io,GageGaskins/osf.io,HalcyonChimera/osf.io,KAsante95/osf.io,SSJohns/osf.io,caneruguz/osf.io,samchrisinger/osf.io,hmoco/osf.io,alexschiller/osf.io,TomHeatwole/osf.io,arpitar/osf.io
0223b6fc332bdbc8a641832ebd06b79969b65853
pyfibot/modules/module_btc.py
pyfibot/modules/module_btc.py
# -*- encoding: utf-8 -*- from __future__ import unicode_literals, print_function, division def command_btc(bot, user, channel, args): """Display BTC exchange rates""" r = bot.get_url("http://bitcoincharts.com/t/weighted_prices.json") data = r.json() eur_rate = float(data['EUR']['24h']) usd_rate = float(data['USD']['24h']) return bot.say(channel, "1 BTC = $%.2f / %.2f€" % (usd_rate, eur_rate))
# -*- encoding: utf-8 -*- from __future__ import unicode_literals, print_function, division def command_btc(bot, user, channel, args): """Display current BTC exchange rates from mtgox""" r = bot.get_url("http://data.mtgox.com/api/1/BTCUSD/ticker") btcusd = r.json()['return']['avg']['display_short'] r = bot.get_url("http://data.mtgox.com/api/1/BTCEUR/ticker") btceur = r.json()['return']['avg']['display_short'] return bot.say(channel, "1 BTC = %s / %s" % (btcusd, btceur))
Use mtgox as data source
Use mtgox as data source
Python
bsd-3-clause
rnyberg/pyfibot,lepinkainen/pyfibot,EArmour/pyfibot,huqa/pyfibot,aapa/pyfibot,huqa/pyfibot,rnyberg/pyfibot,EArmour/pyfibot,lepinkainen/pyfibot,aapa/pyfibot
0868bbd0e445cb39217351cd13d2c3f7a173416c
mws/__init__.py
mws/__init__.py
# -*- coding: utf-8 -*- from __future__ import absolute_import from .mws import MWS, MWSError from .apis import Feeds, Finances, InboundShipments, Inventory, MerchantFulfillment,\ OffAmazonPayments, Orders, OutboundShipments, Products, Recommendations,\ Reports, Sellers __all__ = [ 'Feeds', 'Finances', 'InboundShipments', 'Inventory', 'MerchantFulfillment', 'MWS', 'MWSError', 'OffAmazonPayments', 'Orders', 'OutboundShipments', 'Products', 'Recommendations', 'Reports', 'Sellers', # TODO Add Subscriptions ]
# -*- coding: utf-8 -*- from __future__ import absolute_import from .mws import MWS, MWSError from .apis import Feeds, Finances, InboundShipments, Inventory, MerchantFulfillment,\ OffAmazonPayments, Orders, OutboundShipments, Products, Recommendations,\ Reports, Sellers, Subscriptions __all__ = [ 'Feeds', 'Finances', 'InboundShipments', 'Inventory', 'MerchantFulfillment', 'MWS', 'MWSError', 'OffAmazonPayments', 'Orders', 'OutboundShipments', 'Products', 'Recommendations', 'Reports', 'Sellers', 'Subscriptions', ]
Include the new Subscriptions stub
Include the new Subscriptions stub
Python
unlicense
GriceTurrble/python-amazon-mws,Bobspadger/python-amazon-mws
a91a81c16a27d72cdc41de322130e97889657561
marbaloo_mako/__init__.py
marbaloo_mako/__init__.py
import cherrypy from mako.lookup import TemplateLookup class Tool(cherrypy.Tool): _lookups = {} def __init__(self): cherrypy.Tool.__init__(self, 'before_handler', self.callable, priority=40) def callable(self, filename=None, directories=None, module_directory=None, collection_size=-1): if filename is None or directories is None: return # Find the appropriate template lookup. key = (tuple(directories), module_directory) try: lookup = self._lookups[key] except KeyError: lookup = TemplateLookup(directories=directories, module_directory=module_directory, collection_size=collection_size, input_encoding='utf8') self._lookups[key] = lookup cherrypy.request.lookup = lookup # Replace the current handler. cherrypy.request.template = template = lookup.get_template(filename) inner_handler = cherrypy.serving.request.handler def wrapper(*args, **kwargs): context = inner_handler(*args, **kwargs) response = template.render(**context) return response cherrypy.serving.request.handler = wrapper
import cherrypy from mako.lookup import TemplateLookup class Tool(cherrypy.Tool): _lookups = {} def __init__(self): cherrypy.Tool.__init__(self, 'before_handler', self.callable, priority=40) def callable(self, filename=None, directories=None, module_directory=None, collection_size=-1): if filename is None or directories is None: return # Find the appropriate template lookup. key = (tuple(directories), module_directory) try: lookup = self._lookups[key] except KeyError: lookup = TemplateLookup(directories=directories, module_directory=module_directory, collection_size=collection_size, input_encoding='utf8') self._lookups[key] = lookup cherrypy.request.lookup = lookup cherrypy.request.template = lookup.get_template(filename) # Replace the current handler. inner_handler = cherrypy.serving.request.handler def wrapper(*args, **kwargs): context = inner_handler(*args, **kwargs) response = cherrypy.request.template.render(**context) return response cherrypy.serving.request.handler = wrapper
Load template from `cherrypy.request.template` in handler.
Load template from `cherrypy.request.template` in handler.
Python
mit
marbaloo/marbaloo_mako
90a94b1d511aa17f167d783992fe0f874ad529c1
examples/python_interop/python_interop.py
examples/python_interop/python_interop.py
#!/usr/bin/env python # Copyright 2017 Stanford University # # 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 print_function import legion @legion.task def f(ctx): print("inside task f") @legion.task def main_task(ctx): print("%x" % legion.c.legion_runtime_get_executing_processor(ctx.runtime, ctx.context).id) f(ctx)
#!/usr/bin/env python # Copyright 2017 Stanford University # # 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 print_function import legion @legion.task def f(ctx, *args): print("inside task f%s" % (args,)) @legion.task def main_task(ctx): print("inside main()") f(ctx, 1, "asdf", True)
Test Python support for arguments.
examples: Test Python support for arguments.
Python
apache-2.0
StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion
f1fcce8f0c2022948fb310268a7769d9c9ef04ad
runtests.py
runtests.py
#!/usr/bin/env python import sys import logging from optparse import OptionParser from coverage import coverage from tests.config import configure logging.disable(logging.CRITICAL) def run_tests(options, *test_args): from django_nose import NoseTestSuiteRunner test_runner = NoseTestSuiteRunner(verbosity=options.verbosity, pdb=options.pdb, ) if not test_args: test_args = ['tests'] num_failures = test_runner.run_tests(test_args) if num_failures: sys.exit(num_failures) if __name__ == '__main__': parser = OptionParser() parser.add_option('-c', '--coverage', dest='use_coverage', default=False, action='store_true', help="Generate coverage report") parser.add_option('-v', '--verbosity', dest='verbosity', default=1, type='int', help="Verbosity of output") parser.add_option('-d', '--pdb', dest='pdb', default=False, action='store_true', help="Whether to drop into PDB on failure/error") (options, args) = parser.parse_args() # If no args, then use 'progressive' plugin to keep the screen real estate # used down to a minimum. Otherwise, use the spec plugin nose_args = ['-s', '-x', '--with-progressive' if not args else '--with-spec'] configure(nose_args) if options.use_coverage: print 'Running tests with coverage' c = coverage(source=['oscar']) c.start() run_tests(options, *args) c.stop() print 'Generate HTML reports' c.html_report() else: run_tests(options, *args)
#!/usr/bin/env python import sys import logging from optparse import OptionParser from tests.config import configure logging.disable(logging.CRITICAL) def run_tests(*test_args): from django_nose import NoseTestSuiteRunner test_runner = NoseTestSuiteRunner() if not test_args: test_args = ['tests'] num_failures = test_runner.run_tests(test_args) if num_failures: sys.exit(num_failures) if __name__ == '__main__': parser = OptionParser() __, args = parser.parse_args() # If no args, then use 'progressive' plugin to keep the screen real estate # used down to a minimum. Otherwise, use the spec plugin nose_args = ['-s', '-x', '--with-progressive' if not args else '--with-spec'] nose_args.extend([ '--with-coverage', '--cover-package=oscar', '--cover-html', '--cover-html-dir=htmlcov']) configure(nose_args) run_tests(*args)
Rework test runner to generate coverage stats correctly.
Rework test runner to generate coverage stats correctly. Nose seems to pick up argv automatically - which is annoying. Will need to look into at some point.
Python
bsd-3-clause
michaelkuty/django-oscar,WillisXChen/django-oscar,lijoantony/django-oscar,Bogh/django-oscar,sasha0/django-oscar,okfish/django-oscar,nickpack/django-oscar,rocopartners/django-oscar,django-oscar/django-oscar,WillisXChen/django-oscar,makielab/django-oscar,jinnykoo/wuyisj.com,WillisXChen/django-oscar,jinnykoo/wuyisj.com,nfletton/django-oscar,jinnykoo/wuyisj,sasha0/django-oscar,spartonia/django-oscar,pdonadeo/django-oscar,okfish/django-oscar,eddiep1101/django-oscar,pdonadeo/django-oscar,bnprk/django-oscar,manevant/django-oscar,machtfit/django-oscar,ka7eh/django-oscar,sonofatailor/django-oscar,Idematica/django-oscar,marcoantoniooliveira/labweb,MatthewWilkes/django-oscar,pdonadeo/django-oscar,solarissmoke/django-oscar,monikasulik/django-oscar,ka7eh/django-oscar,dongguangming/django-oscar,elliotthill/django-oscar,django-oscar/django-oscar,kapari/django-oscar,eddiep1101/django-oscar,DrOctogon/unwash_ecom,monikasulik/django-oscar,spartonia/django-oscar,ahmetdaglarbas/e-commerce,binarydud/django-oscar,saadatqadri/django-oscar,mexeniz/django-oscar,manevant/django-oscar,thechampanurag/django-oscar,elliotthill/django-oscar,mexeniz/django-oscar,Bogh/django-oscar,jinnykoo/christmas,thechampanurag/django-oscar,QLGu/django-oscar,spartonia/django-oscar,nickpack/django-oscar,QLGu/django-oscar,jinnykoo/wuyisj,Jannes123/django-oscar,marcoantoniooliveira/labweb,bschuon/django-oscar,ahmetdaglarbas/e-commerce,kapt/django-oscar,ademuk/django-oscar,eddiep1101/django-oscar,django-oscar/django-oscar,faratro/django-oscar,adamend/django-oscar,ademuk/django-oscar,anentropic/django-oscar,saadatqadri/django-oscar,MatthewWilkes/django-oscar,jlmadurga/django-oscar,taedori81/django-oscar,taedori81/django-oscar,solarissmoke/django-oscar,DrOctogon/unwash_ecom,monikasulik/django-oscar,vovanbo/django-oscar,kapari/django-oscar,ahmetdaglarbas/e-commerce,sonofatailor/django-oscar,ademuk/django-oscar,john-parton/django-oscar,QLGu/django-oscar,jmt4/django-oscar,marcoantoniooliveira/labweb,josesanch/django-oscar,itbabu/django-oscar,saadatqadri/django-oscar,WillisXChen/django-oscar,monikasulik/django-oscar,itbabu/django-oscar,solarissmoke/django-oscar,kapari/django-oscar,WillisXChen/django-oscar,jmt4/django-oscar,Jannes123/django-oscar,bnprk/django-oscar,nfletton/django-oscar,mexeniz/django-oscar,taedori81/django-oscar,bschuon/django-oscar,vovanbo/django-oscar,anentropic/django-oscar,lijoantony/django-oscar,pasqualguerrero/django-oscar,thechampanurag/django-oscar,bschuon/django-oscar,ka7eh/django-oscar,jinnykoo/christmas,machtfit/django-oscar,saadatqadri/django-oscar,itbabu/django-oscar,lijoantony/django-oscar,kapari/django-oscar,vovanbo/django-oscar,nickpack/django-oscar,amirrpp/django-oscar,kapt/django-oscar,marcoantoniooliveira/labweb,Idematica/django-oscar,jinnykoo/wuyisj,dongguangming/django-oscar,sasha0/django-oscar,sasha0/django-oscar,itbabu/django-oscar,nickpack/django-oscar,michaelkuty/django-oscar,adamend/django-oscar,anentropic/django-oscar,john-parton/django-oscar,binarydud/django-oscar,WadeYuChen/django-oscar,QLGu/django-oscar,taedori81/django-oscar,rocopartners/django-oscar,dongguangming/django-oscar,jlmadurga/django-oscar,rocopartners/django-oscar,MatthewWilkes/django-oscar,jlmadurga/django-oscar,pdonadeo/django-oscar,Bogh/django-oscar,manevant/django-oscar,john-parton/django-oscar,ka7eh/django-oscar,bschuon/django-oscar,bnprk/django-oscar,rocopartners/django-oscar,manevant/django-oscar,faratro/django-oscar,django-oscar/django-oscar,jmt4/django-oscar,Jannes123/django-oscar,josesanch/django-oscar,sonofatailor/django-oscar,okfish/django-oscar,WadeYuChen/django-oscar,pasqualguerrero/django-oscar,michaelkuty/django-oscar,amirrpp/django-oscar,anentropic/django-oscar,Jannes123/django-oscar,nfletton/django-oscar,adamend/django-oscar,vovanbo/django-oscar,makielab/django-oscar,dongguangming/django-oscar,mexeniz/django-oscar,jinnykoo/wuyisj,binarydud/django-oscar,kapt/django-oscar,jinnykoo/wuyisj.com,makielab/django-oscar,binarydud/django-oscar,pasqualguerrero/django-oscar,amirrpp/django-oscar,ahmetdaglarbas/e-commerce,jlmadurga/django-oscar,faratro/django-oscar,john-parton/django-oscar,spartonia/django-oscar,josesanch/django-oscar,WillisXChen/django-oscar,Idematica/django-oscar,solarissmoke/django-oscar,makielab/django-oscar,michaelkuty/django-oscar,machtfit/django-oscar,jinnykoo/christmas,adamend/django-oscar,Bogh/django-oscar,lijoantony/django-oscar,jmt4/django-oscar,sonofatailor/django-oscar,pasqualguerrero/django-oscar,faratro/django-oscar,nfletton/django-oscar,bnprk/django-oscar,okfish/django-oscar,WadeYuChen/django-oscar,thechampanurag/django-oscar,amirrpp/django-oscar,MatthewWilkes/django-oscar,elliotthill/django-oscar,jinnykoo/wuyisj.com,DrOctogon/unwash_ecom,eddiep1101/django-oscar,WadeYuChen/django-oscar,ademuk/django-oscar
3c833053f6da71d1eed6d1a0720a1a8cb1997de7
runtests.py
runtests.py
#!/usr/bin/env python from os.path import dirname, abspath import sys from django.conf import settings if not settings.configured: from django import VERSION settings_dict = dict( INSTALLED_APPS=( 'localeurl', ), ROOT_URLCONF='localeurl.tests.test_urls', ) if VERSION >= (1, 2): settings_dict["DATABASES"] = { "default": { "ENGINE": "django.db.backends.sqlite3" }} else: settings_dict["DATABASE_ENGINE"] = "sqlite3" settings.configure(**settings_dict) def runtests(*test_args): if not test_args: test_args = ['localeurl'] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) try: from django.test.simple import DjangoTestSuiteRunner def run_tests(test_args, verbosity, interactive): runner = DjangoTestSuiteRunner( verbosity=verbosity, interactive=interactive) return runner.run_tests(test_args) except ImportError: # for Django versions that don't have DjangoTestSuiteRunner from django.test.simple import run_tests failures = run_tests(test_args, verbosity=1, interactive=True) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])
#!/usr/bin/env python from os.path import dirname, abspath import sys from django.conf import settings if not settings.configured: from django import VERSION settings_dict = dict( INSTALLED_APPS=( 'localeurl', 'django.contrib.sites', # for sitemap test ), ROOT_URLCONF='localeurl.tests.test_urls', ) if VERSION >= (1, 2): settings_dict["DATABASES"] = { "default": { "ENGINE": "django.db.backends.sqlite3" }} else: settings_dict["DATABASE_ENGINE"] = "sqlite3" settings.configure(**settings_dict) def runtests(*test_args): if not test_args: test_args = ['localeurl'] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) try: from django.test.simple import DjangoTestSuiteRunner def run_tests(test_args, verbosity, interactive): runner = DjangoTestSuiteRunner( verbosity=verbosity, interactive=interactive) return runner.run_tests(test_args) except ImportError: # for Django versions that don't have DjangoTestSuiteRunner from django.test.simple import run_tests failures = run_tests(test_args, verbosity=1, interactive=True) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])
Include contrib.sites when running tests; needed for sitemaps in Django >= 1.2.
Include contrib.sites when running tests; needed for sitemaps in Django >= 1.2.
Python
mit
extertioner/django-localeurl,gonnado/django-localeurl,carljm/django-localeurl
d873380a3ad382ac359ebf41f3f775f585b674f8
mopidy_gmusic/__init__.py
mopidy_gmusic/__init__.py
from __future__ import unicode_literals import os from mopidy import config, ext __version__ = '0.2.2' class GMusicExtension(ext.Extension): dist_name = 'Mopidy-GMusic' ext_name = 'gmusic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(GMusicExtension, self).get_config_schema() schema['username'] = config.String() schema['password'] = config.Secret() schema['deviceid'] = config.String(optional=True) return schema def get_backend_classes(self): from .actor import GMusicBackend return [GMusicBackend]
from __future__ import unicode_literals import os from mopidy import config, ext __version__ = '0.2.2' class GMusicExtension(ext.Extension): dist_name = 'Mopidy-GMusic' ext_name = 'gmusic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(GMusicExtension, self).get_config_schema() schema['username'] = config.String() schema['password'] = config.Secret() schema['deviceid'] = config.String(optional=True) return schema def setup(self, registry): from .actor import GMusicBackend registry.add('backend', GMusicBackend)
Use new extension setup() API
Use new extension setup() API
Python
apache-2.0
Tilley/mopidy-gmusic,jodal/mopidy-gmusic,mopidy/mopidy-gmusic,jaibot/mopidy-gmusic,hechtus/mopidy-gmusic,elrosti/mopidy-gmusic,jaapz/mopidy-gmusic
13f4373fc415faba717033f0e8b87a7c5cd83033
slackclient/_slackrequest.py
slackclient/_slackrequest.py
import json import requests import six class SlackRequest(object): @staticmethod def do(token, request="?", post_data=None, domain="slack.com"): post_data = post_data or {} for k, v in six.iteritems(post_data): if not isinstance(v, six.string_types): post_data[k] = json.dumps(v) url = 'https://{0}/api/{1}'.format(domain, request) post_data['token'] = token return requests.post(url, data=post_data)
import json import requests import six class SlackRequest(object): @staticmethod def do(token, request="?", post_data=None, domain="slack.com"): post_data = post_data or {} for k, v in six.iteritems(post_data): if not isinstance(v, six.string_types): post_data[k] = json.dumps(v) url = 'https://{0}/api/{1}'.format(domain, request) post_data['token'] = token files = {'file': post_data.pop('file')} if 'file' in post_data else None return requests.post(url, data=post_data, files=files)
Add support for files.upload API call.
Add support for files.upload API call. Closes #64, #88.
Python
mit
slackapi/python-slackclient,slackhq/python-slackclient,slackapi/python-slackclient,slackapi/python-slackclient
0676485054c01abb41b95901c1af0af63fdcb650
AFQ/utils/volume.py
AFQ/utils/volume.py
import scipy.ndimage as ndim from skimage.filters import gaussian def patch_up_roi(roi, sigma=0.5): """ After being non-linearly transformed, ROIs tend to have holes in them. We perform a couple of computational geometry operations on the ROI to fix that up. Parameters ---------- roi : 3D binary array The ROI after it has been transformed. sigma : float The sigma for initial Gaussian smoothing. Returns ------- ROI after dilation and hole-filling """ return ndim.binary_fill_holes( ndim.binary_dilation(gaussian(roi, sigma=sigma)).astype(float))
import scipy.ndimage as ndim from skimage.filters import gaussian def patch_up_roi(roi, sigma=0.5, truncate=2): """ After being non-linearly transformed, ROIs tend to have holes in them. We perform a couple of computational geometry operations on the ROI to fix that up. Parameters ---------- roi : 3D binary array The ROI after it has been transformed. sigma : float The sigma for initial Gaussian smoothing. truncate : float The truncation for the Gaussian. Returns ------- ROI after dilation and hole-filling """ return ndim.binary_fill_holes( ndim.binary_dilation(gaussian(roi, sigma=sigma, truncate=truncate)).astype(float))
Truncate ROI-smoothing Gaussian at 2 STD per default.
Truncate ROI-smoothing Gaussian at 2 STD per default.
Python
bsd-2-clause
yeatmanlab/pyAFQ,yeatmanlab/pyAFQ,arokem/pyAFQ,arokem/pyAFQ
a24fe6cb58439d295455116574463ebdaf621f2c
mgsv_names.py
mgsv_names.py
import random, os global adjectives, animals, rares with open(os.path.join(os.path.dirname(__file__), 'adjectives.txt')) as f: adjectives = f.readlines() with open(os.path.join(os.path.dirname(__file__), 'animals.txt')) as f: animals = f.readlines() with open(os.path.join(os.path.dirname(__file__), 'rares.txt')) as f: rares = f.readlines() uncommons = { # Adjectives: 'master': 'miller', 'raging': 'bull', 'hidden': 'dragon', 'humming': 'bird', 'spicy': 'sandworm', # Animals: 'ocelot': 'revolver', 'lion': 'snooping', 'tiger': 'crouching', 'hippo': 'hungry', 'falcon': 'punching', } def generate_name(): adj = random.choice(adjectives).strip() anim = random.choice(animals).strip() r = random.random() if r < 0.001 or r >= 0.999: return random.choice(rares).strip() elif r < 0.3 and adj in uncommons: return ' '.join((adj, uncommons[adj])) elif r >= 0.7 and anim in uncommons: return ' '.join((uncommons[anim], anim)) return ' '.join((adj, anim)) if __name__ == '__main__': print(generate_name())
from __future__ import unicode_literals, print_function import sqlite3, os, random _select = 'select {} from {} order by random() limit 1' _uncommon_select = 'select value from uncommons where key=?' def generate_name(): conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'names.db')) cursor = conn.cursor() adj = cursor.execute(_select.format('adjective', 'adjectives')).fetchone()[0] anim = cursor.execute(_select.format('animal', 'animals')).fetchone()[0] rare = cursor.execute(_select.format('name', 'rares')).fetchone()[0] uncommon_anim = cursor.execute(_uncommon_select, [adj]).fetchone() uncommon_adj = cursor.execute(_uncommon_select, [anim]).fetchone() conn.close() r = random.random() if r < 0.001 or r >= 0.999: return rare elif r < 0.3 and uncommon_anim is not None: return ' '.join((adj, uncommon_anim[0])) elif r >= 0.7 and uncommon_adj is not None: return ' '.join((uncommon_adj[0], anim)) return ' '.join((adj, anim)) if __name__ == '__main__': print(generate_name())
Replace text files with database access.
Replace text files with database access.
Python
unlicense
rotated8/mgsv_names
33903a72a48a6d36792cec0f1fb3a6999c04b486
blendergltf/exporters/base.py
blendergltf/exporters/base.py
import json def _is_serializable(value): try: json.dumps(value) return True except TypeError: return False _IGNORED_CUSTOM_PROPS = [ '_RNA_UI', 'cycles', 'cycles_visibility', ] # pylint: disable=unused-argument class BaseExporter: gltf_key = '' blender_key = '' @classmethod def get_custom_properties(cls, blender_data): return { k: v.to_list() if hasattr(v, 'to_list') else v for k, v in blender_data.items() if k not in _IGNORED_CUSTOM_PROPS and _is_serializable(v) } @classmethod def check(cls, state, blender_data): return True @classmethod def default(cls, state, blender_data): return { 'name': blender_data.name } @classmethod def export(cls, state, blender_data): return {}
import json def _is_serializable(value): try: json.dumps(value) return True except TypeError: return False _IGNORED_CUSTOM_PROPS = [ '_RNA_UI', 'cycles', 'cycles_visibility', ] # pylint: disable=unused-argument class BaseExporter: gltf_key = '' blender_key = '' @classmethod def get_custom_properties(cls, blender_data): custom_props = { key: value.to_list() if hasattr(value, 'to_list') else value for key, value in blender_data.items() if key not in _IGNORED_CUSTOM_PROPS } custom_props = { key: value for key, value in custom_props.items() if _is_serializable(value) } return custom_props @classmethod def check(cls, state, blender_data): return True @classmethod def default(cls, state, blender_data): return { 'name': blender_data.name } @classmethod def export(cls, state, blender_data): return {}
Convert custom properties before checking for serializability
Convert custom properties before checking for serializability
Python
apache-2.0
Kupoman/blendergltf
fc97832d0d96017ac71da125c3a7f29caceface6
app/mod_budget/model.py
app/mod_budget/model.py
from app import db from app.mod_auth.model import User class Category(db.Document): # The name of the category. name = db.StringField(required = True) class Entry(db.Document): # The amount of the entry. amount = db.DecimalField(precision = 2, required = True) # A short description for the entry. description = db.StringField(required = True) # The owner of the entry. # Should the owner be deleted, we also want to delete all of his entries. owner = db.ReferenceField(User, reverse_delete_rule = db.CASCADE, required = True) # The category of this entry. category = db.ReferenceField(Category, required = True)
from app import db from app.mod_auth.model import User class Category(db.Document): # The name of the category. name = db.StringField(required = True) class Entry(db.Document): # The amount of the entry. amount = db.DecimalField(precision = 2, required = True) # A short description for the entry. description = db.StringField(required = True) # The owner of the entry. # Should the owner be deleted, we also want to delete all of his entries. owner = db.ReferenceField(User, reverse_delete_rule = db.CASCADE, required = True) # The category of this entry. category = db.ReferenceField(Category)
Make category an optional field for an entry.
Make category an optional field for an entry. Income entries should not have a category. So the field should be made optional.
Python
mit
Zillolo/mana-vault,Zillolo/mana-vault,Zillolo/mana-vault
094cb428316ac0fceb0178d5a507e746550f4509
bin/task_usage_index.py
bin/task_usage_index.py
#!/usr/bin/env python3 import os, sys sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib')) import glob, json import numpy as np import task_usage def main(data_path, index_path): count = 0 index = [] for path in sorted(glob.glob('{}/**/*.sqlite3'.format(data_path))): data = task_usage.count_job_task_samples(path) for i in range(data.shape[0]): index.append({ 'path': path, 'job': int(data[i, 0]), 'task': int(data[i, 1]), 'count': int(data[i, 2]), }) count += 1 if count % 10000 == 0: print('Processed: {}'.format(count)) with open(index_path, 'w') as file: json.dump({'index': index}, file, indent=4) if __name__ == '__main__': assert(len(sys.argv) == 3) main(sys.argv[1], sys.argv[2])
#!/usr/bin/env python3 import os, sys sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib')) import glob, json import numpy as np import task_usage def main(data_path, index_path, report_each=10000): print('Looking for data in "{}"...'.format(data_path)) paths = sorted(glob.glob('{}/**/*.sqlite3'.format(data_path))) print('Processing {} databases...'.format(len(paths))) index = [] count = 0 for path in paths: data = task_usage.count_job_task_samples(path) for i in range(data.shape[0]): index.append({ 'path': path, 'job': int(data[i, 0]), 'task': int(data[i, 1]), 'length': int(data[i, 2]), }) count += 1 if count % report_each == 0: print('Processed: {}'.format(count)) print('Saving into "{}"...'.format(index_path)) with open(index_path, 'w') as file: json.dump({'index': index}, file, indent=4) if __name__ == '__main__': assert(len(sys.argv) == 3) main(sys.argv[1], sys.argv[2])
Print progress from the indexing script
Print progress from the indexing script
Python
mit
learning-on-chip/google-cluster-prediction
9ca46da9d0cf8b5f4b4a6e9234d7089665df5e8b
chef/tests/__init__.py
chef/tests/__init__.py
import os from unittest2 import TestCase from chef.api import ChefAPI TEST_ROOT = os.path.dirname(os.path.abspath(__file__)) def test_chef_api(): return ChefAPI('https://api.opscode.com/organizations/pycheftest', os.path.join(TEST_ROOT, 'client.pem'), 'unittests') class ChefTestCase(TestCase): """Base class for Chef unittests.""" def setUp(self): super(ChefTestCase, self).setUp() self.api = test_chef_api self.api.set_default()
import os import random from unittest2 import TestCase from chef.api import ChefAPI TEST_ROOT = os.path.dirname(os.path.abspath(__file__)) def test_chef_api(): return ChefAPI('https://api.opscode.com/organizations/pycheftest', os.path.join(TEST_ROOT, 'client.pem'), 'unittests') class ChefTestCase(TestCase): """Base class for Chef unittests.""" def setUp(self): super(ChefTestCase, self).setUp() self.api = test_chef_api self.api.set_default() def random(self, length=8, alphabet='0123456789abcdef'): return ''.join(random.choice(alphabet) for _ in xrange(length))
Add a method to generate random names for testing.
Add a method to generate random names for testing.
Python
apache-2.0
jarosser06/pychef,dipakvwarade/pychef,coderanger/pychef,jarosser06/pychef,Scalr/pychef,dipakvwarade/pychef,cread/pychef,Scalr/pychef,coderanger/pychef,cread/pychef
86a992dc15482087773f1591752a667a6014ba5d
docker/settings/celery.py
docker/settings/celery.py
from .docker_compose import DockerBaseSettings class CeleryDevSettings(DockerBaseSettings): pass CeleryDevSettings.load_settings(__name__)
from .docker_compose import DockerBaseSettings class CeleryDevSettings(DockerBaseSettings): # Since we can't properly set CORS on Azurite container # (see https://github.com/Azure/Azurite/issues/55#issuecomment-503380561) # trying to fetch ``objects.inv`` from celery container fails because the # URL is like http://docs.dev.readthedocs.io/... and it should be # http://storage:10000/... This setting fixes that. # Once we can use CORS, we should define this setting in the # ``docker_compose.py`` file instead. AZURE_MEDIA_STORAGE_HOSTNAME = 'storage:10000' CeleryDevSettings.load_settings(__name__)
Use proper domain for AZURE_MEDIA_STORAGE_HOSTNAME
Use proper domain for AZURE_MEDIA_STORAGE_HOSTNAME We can't access docs.dev.readthedocs.io from celery container because that domain points to 127.0.0.1 and we don't have the storage in that IP. So, we need to override the AZURE_MEDIA_STORAGE_HOSTNAME in the celery container to point to the storage. We should do this directly in `docker_compose.py` settings file, but since we can't configure CORS in Azurite we can't do it yet.
Python
mit
rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org
ac5ceee751b0c374ffcf1bd0e52ce085e8d7295c
nyucal/cli.py
nyucal/cli.py
# -*- coding: utf-8 -*- """Console script for nyucal. See click documentation at http://click.pocoo.org/ """ import io import click from nyucal import nyucal import requests @click.group() def main(args=None): """Console script for nyucal.""" click.echo("cli for nyucal") @main.command() def list(source=None): """List the available calendars in the calendar source""" if source is None: source = nyucal.SOURCE_URL # noqa store = nyucal.CalendarStore(source) for line in store.calendar_names: click.echo(line) if __name__ == "__main__": main()
# -*- coding: utf-8 -*- """Console script for nyucal. See click documentation at http://click.pocoo.org/ """ import io import click from nyucal import nyucal import requests @click.group() def main(args=None): """Console script for nyucal.""" pass @main.command() @click.option('--source', '-s', default=nyucal.SOURCE_URL, help="""Calendars source (URL, file path, or string). (default: {} """.format(nyucal.SOURCE_URL)) def list(source): """List the available calendars in the calendar source Since the calendar store is, by default, scraped from a web page, this command will fail if no source is specified and the computer is not online. """ store = nyucal.CalendarStore(source) for line in store.calendar_names: click.echo(line) @main.command() @click.argument('name', nargs=1) @click.option('--source', '-s', default=nyucal.SOURCE_URL, help="""Calendars source (URL, file path, or string). (default: {} """.format(nyucal.SOURCE_URL)) @click.option('--format', '-f', type=click.Choice(['gcalcsv']), default='gcalcsv', help='Write in this format') @click.option('--output', '-o', type=click.File('w'), default='-', help='Write to this file (default: stdout)') def get(source, name, format, output): """Get the calendar named NAME and output in the specified format If NAME contains a space, it will need to be quoted. Since the calendar store is, by default, scraped from a web page, this command will fail if no source is specified and the computer is not online. """ store = nyucal.CalendarStore(source) calendar = store.calendar(name) writers = {'gcalcsv': nyucal.GcalCsvWriter} writer = writers[format.lower()](output) writer.write(calendar) if __name__ == "__main__": main()
Add the `get` command to the CLI.
Add the `get` command to the CLI.
Python
mit
nyumathclinic/nyucal,nyumathclinic/nyucal
019bca440c46039954a6228bbd22f79a5449aecd
custom/fri/management/commands/dump_fri_message_bank.py
custom/fri/management/commands/dump_fri_message_bank.py
from __future__ import absolute_import from __future__ import unicode_literals from couchexport.export import export_raw from custom.fri.models import FRIMessageBankMessage, FRIRandomizedMessage, FRIExtraMessage from django.core.management.base import BaseCommand from io import open class Command(BaseCommand): def write_result_to_file(self, model_name, result, fields): with open('%s.xlsx' % model_name, 'wb') as f: headers = fields excel_data = [] for obj in result: excel_data.append((getattr(obj, field) for field in fields)) export_raw( ((model_name, headers), ), ((model_name, excel_data), ), f ) def handle(self, **options): self.write_result_to_file( 'FRIMessageBankMessage', FRIMessageBankMessage.view('fri/message_bank', include_docs=True).all(), ('_id', 'domain', 'risk_profile', 'message', 'fri_id') ) self.write_result_to_file( 'FRIRandomizedMessage', FRIRandomizedMessage.view('fri/randomized_message', include_docs=True).all(), ('_id', 'domain', 'case_id', 'message_bank_message_id', 'order') ) self.write_result_to_file( 'FRIExtraMessage', FRIExtraMessage.view('fri/extra_message', include_docs=True).all(), ('_id', 'domain', 'message_id', 'message') )
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from custom.fri.models import FRIMessageBankMessage, FRIRandomizedMessage, FRIExtraMessage from django.core.management.base import BaseCommand from six import moves class Command(BaseCommand): def delete_docs(self, model_name, result): print("\nHandling %s" % model_name) result = list(result) answer = moves.input("Delete %s docs? y/n" % len(result)) if answer == 'y': count = 0 for doc in result: if doc.doc_type != model_name: print("Deleted %s docs" % count) raise ValueError("Expected %s, got %s" % (model_name, doc.doc_type)) doc.delete() count += 1 print("Deleted %s docs" % count) def handle(self, **options): self.delete_docs( 'FRIMessageBankMessage', FRIMessageBankMessage.view('fri/message_bank', include_docs=True).all() ) self.delete_docs( 'FRIRandomizedMessage', FRIRandomizedMessage.view('fri/randomized_message', include_docs=True).all() ) self.delete_docs( 'FRIExtraMessage', FRIExtraMessage.view('fri/extra_message', include_docs=True).all() )
Update fri dump script to delete docs
Update fri dump script to delete docs
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
be82f1beac54f46fe9458c3ca26b8e3b786bc9f5
web/impact/impact/views/general_view_set.py
web/impact/impact/views/general_view_set.py
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from django.apps import apps from rest_framework import viewsets from rest_framework import permissions from rest_framework_tracking.mixins import LoggingMixin from impact.models.utils import snake_to_camel_case from impact.permissions import DynamicModelPermissions from impact.serializers import GeneralSerializer class GeneralViewSet(LoggingMixin, viewsets.ModelViewSet): permission_classes = ( permissions.IsAuthenticated, DynamicModelPermissions, ) @property def model(self): return apps.get_model( app_label=self.kwargs['app'], model_name=snake_to_camel_case(self.kwargs['model'])) def get_queryset(self): return self.model.objects.all() def get_serializer_class(self): GeneralSerializer.Meta.model = self.model return GeneralSerializer
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from django.apps import apps from rest_framework import viewsets from rest_framework import permissions from rest_framework_tracking.mixins import LoggingMixin from impact.models.utils import snake_to_camel_case from impact.permissions import DynamicModelPermissions from impact.serializers import GeneralSerializer model_attribute_calls = [ 'Startup_additional_industries', 'Startup_recommendation_tags', 'StartupLabel_startups', 'RefundCode_programs', 'UserLabel_users', 'Observer_newsletter_cc_roles', 'ExpertProfile_functional_expertise', 'ExpertProfile_additional_industries', 'ExpertProfile_mentoring_specialties', 'Newsletter_recipient_roles', 'Section_interest_categories', ] class GeneralViewSet(LoggingMixin, viewsets.ModelViewSet): permission_classes = ( permissions.IsAuthenticated, DynamicModelPermissions, ) @property def model(self): if self.kwargs['model'] in model_attribute_calls: return apps.get_model( app_label=self.kwargs['app'], model_name=self.kwargs['model']) else: return apps.get_model( app_label=self.kwargs['app'], model_name=snake_to_camel_case(self.kwargs['model'])) def get_queryset(self): return self.model.objects.all() def get_serializer_class(self): GeneralSerializer.Meta.model = self.model return GeneralSerializer
Create List of Model Attribute API Calls That Require Snake Case
[AC-5010] Create List of Model Attribute API Calls That Require Snake Case This commit creates a list of models that use attributes. Those calls have snake case in their model definition, and were breaking when converted back to camel case. This may not be the most efficient way to do this, but it is currently working.
Python
mit
masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api
81b5c5c29747d7f8622828c0036504a4a5023794
parse-demo.py
parse-demo.py
#!/usr/bin/python3 import sys, os import nltk if len(sys.argv) < 2: print("Please supply a filename.") sys.exit(1) filename = sys.argv[1] with open(filename, 'r') as f: data = f.read() # Break the input down into sentences, then into words, and position tag # those words. sentences = [nltk.pos_tag(nltk.word_tokenize(sentence)) \ for sentence in nltk.sent_tokenize(data)] # Define a grammar, and identify the noun phrases in the sentences. chunk_parser = nltk.RegexpParser(r"NP: {<DT>?<JJ>*<NN>}") trees = [chunk_parser.parse(sentence) for sentence in sentences] for tree in trees: print(tree) #for subtree in tree.subtrees(filter = lambda t: t.label() == 'NP'): #print(subtree)
#!/usr/bin/python3 import sys, os import nltk if len(sys.argv) < 2: print("Please supply a filename.") sys.exit(1) filename = sys.argv[1] with open(filename, 'r') as f: data = f.read() # Break the input down into sentences, then into words, and position tag # those words. raw_sentences = nltk.sent_tokenize(data) sentences = [nltk.pos_tag(nltk.word_tokenize(sentence)) \ for sentence in raw_sentences] # Define a grammar, and identify the noun phrases in the sentences. chunk_parser = nltk.RegexpParser(r"NP: {((<DT>|<PRP\$>)?<JJ>*(<NN>|<NNP>)+|<PRP>)}") trees = [chunk_parser.parse(sentence) for sentence in sentences] for index, tree in enumerate(trees): print("===\nSentence: %s\nNoun phrases:" % raw_sentences[index].replace('\n', ' ')) for subtree in tree.subtrees(filter = lambda t: t.label() == 'NP'): print(" %s" % subtree)
Develop the Regex grammar slightly further
Develop the Regex grammar slightly further
Python
mit
alexander-bauer/syllabus-summary
ac14efc0a8facbfe2fe7288734c86b27eb9b2770
openprocurement/tender/openeu/adapters.py
openprocurement/tender/openeu/adapters.py
# -*- coding: utf-8 -*- from openprocurement.tender.core.adapters import TenderConfigurator from openprocurement.tender.openeu.models import Tender from openprocurement.tender.openua.constants import ( TENDERING_EXTRA_PERIOD ) from openprocurement.tender.openeu.constants import ( TENDERING_DURATION, PREQUALIFICATION_COMPLAINT_STAND_STILL ) class TenderAboveThresholdEUConfigurator(TenderConfigurator): """ AboveThresholdEU Tender configuration adapter """ name = "AboveThresholdEU Tender configurator" model = Tender # duration of tendering period. timedelta object. tendering_period_duration = TENDERING_DURATION # duration of tender period extension. timedelta object tendering_period_extra = TENDERING_EXTRA_PERIOD # duration of pre-qualification stand-still period. timedelta object. prequalification_complaint_stand_still = PREQUALIFICATION_COMPLAINT_STAND_STILL block_tender_complaint_status = model.block_tender_complaint_status block_complaint_status = model.block_complaint_status
# -*- coding: utf-8 -*- from openprocurement.tender.core.adapters import TenderConfigurator from openprocurement.tender.openeu.models import Tender from openprocurement.tender.openua.constants import ( TENDERING_EXTRA_PERIOD, STATUS4ROLE ) from openprocurement.tender.openeu.constants import ( TENDERING_DURATION, PREQUALIFICATION_COMPLAINT_STAND_STILL ) class TenderAboveThresholdEUConfigurator(TenderConfigurator): """ AboveThresholdEU Tender configuration adapter """ name = "AboveThresholdEU Tender configurator" model = Tender # duration of tendering period. timedelta object. tendering_period_duration = TENDERING_DURATION # duration of tender period extension. timedelta object tendering_period_extra = TENDERING_EXTRA_PERIOD # duration of pre-qualification stand-still period. timedelta object. prequalification_complaint_stand_still = PREQUALIFICATION_COMPLAINT_STAND_STILL block_tender_complaint_status = model.block_tender_complaint_status block_complaint_status = model.block_complaint_status # Dictionary with allowed complaint statuses for operations for each role allowed_statuses_for_complaint_operations_for_roles = STATUS4ROLE
Add constant for complaint documents
Add constant for complaint documents
Python
apache-2.0
openprocurement/openprocurement.tender.openeu
7bdcc30612636d2c27ea01a7d14b1839696fa7a0
newsman/watchdog/clean_process.py
newsman/watchdog/clean_process.py
#!/usr/bin/env python #-*- coding: utf-8 -*- """ clean zombie processes """ # @author chengdujin # @contact chengdujin@gmail.com # @created Aug. 22, 2013 import sys reload(sys) sys.setdefaultencoding('UTF-8') import subprocess def clean(): """ kill zombie processes if there is any """ command = "kill -HUP `ps -A -ostat,ppid | grep -e '^[Zz]' | awk '{print $2}'`" subprocess.Popen(command, stderr=subprocess.PIPE, shell=True) if __name__ == '__main__': clean()
#!/usr/bin/env python #-*- coding: utf-8 -*- """ clean zombie processes """ # @author chengdujin # @contact chengdujin@gmail.com # @created Aug. 22, 2013 import sys reload(sys) sys.setdefaultencoding('UTF-8') import subprocess def clean(): """ kill zombie processes if there is any """ command = "kill -HUP `ps -A -ostat,ppid | grep -e '^[Zz]' | awk '{print $2}'`" subprocess.Popen(command, stderr=subprocess.PIPE, shell=True) command = "ps -xal | grep p[y]thon | grep '<defunct>' | awk '{print $4}' | xargs kill -9" subprocess.Popen(command, stderr=subprocess.PIPE, shell=True) if __name__ == '__main__': clean()
Add code to remove defunct python processes
Add code to remove defunct python processes
Python
agpl-3.0
chengdujin/newsman,chengdujin/newsman,chengdujin/newsman
b5e7cb7946d87fa39c2a006808a0c07975f9c4d4
endymion/box.py
endymion/box.py
from __future__ import unicode_literals, print_function import json import urllib2 class Box(object): """Downloads and parses metainformation about a Vagrant box""" def __init__(self, publisher, name): """Extract metainformation for a Vagrant box. publisher -- Atlas owner name -- Vagrant box name """ json_url = ("https://atlas.hashicorp.com/{0}/boxes/{1}/" .format(publisher, name)) request = urllib2.Request(json_url, None, {'Accept': 'application/json'}) json_file = urllib2.urlopen(request) self._data = json.loads(json_file.read()) def versions(self): """Return a tuple with all available box versions.""" return tuple(v['version'] for v in self._data['versions'] if v['status'] == 'active') def providers(self, version): """Return a list of providers for a specific box version.""" _ver = ([v for v in self._data['versions'] if v['version'] == version])[0] return [p['name'] for p in _ver['providers']] def url(self, version, provider): """Return the download URL for a specific box version and provider.""" _ver = ([v for v in self._data['versions'] if v['version'] == version])[0] return ([p for p in _ver['providers'] if p['name'] == provider])[0]['url']
from __future__ import unicode_literals, print_function import json import urllib2 class Box(object): """Downloads and parses metainformation about a Vagrant box""" def __init__(self, publisher, name): """Extract metainformation for a Vagrant box. publisher -- Atlas owner name -- Vagrant box name """ json_url = ("https://atlas.hashicorp.com/{0}/boxes/{1}/" .format(publisher, name)) request = urllib2.Request(json_url, None, {'Accept': 'application/json'}) json_file = urllib2.urlopen(request) self._data = json.loads(json_file.read()) # We need to preserve the order of the versions self._versions = tuple(v['version'] for v in self._data['versions']) # Prepare a data structure for quick lookups self._boxes = {} for v in self._data['versions']: _version = v['version'] self._boxes[_version] = {} for p in v['providers']: _provider = p['name'] self._boxes[_version][_provider] = {} self._boxes[_version][_provider]['url'] = p['url'] def versions(self): """Return a tuple with all available box versions.""" return self._versions def providers(self, version): """Return a list of providers for a specific box version.""" return self._boxes[version].keys() def url(self, version, provider): """Return the download URL for a specific box version and provider.""" return self._boxes[version][provider]['url']
Index the Atlas data by version and provider
Index the Atlas data by version and provider
Python
mit
lpancescu/atlas-lint
9a0f7e8b9da174008b33dd1d757b2e186b70e9f4
examples/network_correlations.py
examples/network_correlations.py
""" Cortical networks correlation matrix ==================================== """ import seaborn as sns import matplotlib.pyplot as plt sns.set(context="paper", font="monospace") df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0) corrmat = df.corr() f, ax = plt.subplots(figsize=(12, 9)) sns.heatmap(corrmat, vmax=.8, linewidths=0, square=True) networks = corrmat.columns.get_level_values("network").astype(int).values start, end = ax.get_ylim() rect_kws = dict(facecolor="none", edgecolor=".2", linewidth=1.5, capstyle="projecting") for n in range(1, 18): n_nodes = (networks == n).sum() rect = plt.Rectangle((start, end), n_nodes, -n_nodes, **rect_kws) start += n_nodes end -= n_nodes ax.add_artist(rect) f.tight_layout()
""" Cortical networks correlation matrix ==================================== """ import seaborn as sns import matplotlib.pyplot as plt sns.set(context="paper", font="monospace") df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0) corrmat = df.corr() f, ax = plt.subplots(figsize=(12, 9)) sns.heatmap(corrmat, vmax=.8, linewidths=0, square=True) networks = corrmat.columns.get_level_values("network") for i, network in enumerate(networks): if i and network != networks[i - 1]: ax.axhline(len(networks) - i, c="w") ax.axvline(i, c="w") f.tight_layout()
Improve networks heatmap gallery example
Improve networks heatmap gallery example
Python
bsd-3-clause
lukauskas/seaborn,mwaskom/seaborn,phobson/seaborn,parantapa/seaborn,drewokane/seaborn,cwu2011/seaborn,aashish24/seaborn,arokem/seaborn,bsipocz/seaborn,gef756/seaborn,mia1rab/seaborn,dimarkov/seaborn,muku42/seaborn,ebothmann/seaborn,petebachant/seaborn,anntzer/seaborn,lukauskas/seaborn,JWarmenhoven/seaborn,phobson/seaborn,Guokr1991/seaborn,mclevey/seaborn,olgabot/seaborn,jakevdp/seaborn,wrobstory/seaborn,anntzer/seaborn,clarkfitzg/seaborn,ashhher3/seaborn,lypzln/seaborn,sinhrks/seaborn,oesteban/seaborn,jat255/seaborn,Lx37/seaborn,sauliusl/seaborn,ischwabacher/seaborn,mwaskom/seaborn,arokem/seaborn,nileracecrew/seaborn,huongttlan/seaborn,q1ang/seaborn,tim777z/seaborn,aashish24/seaborn,dhimmel/seaborn,dotsdl/seaborn,kyleam/seaborn,uhjish/seaborn
393a2f5f0ccfedc1c5ebd7de987c870419ca2d89
scripts/calculate_lqr_gain.py
scripts/calculate_lqr_gain.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import scipy import control from dtk.bicycle import benchmark_state_space_vs_speed, benchmark_matrices def compute_whipple_lqr_gain(velocity): _, A, B = benchmark_state_space_vs_speed(*benchmark_matrices(), velocity) Q = np.diag([1e5, 1e3, 1e3, 1e2]) R = np.eye(2) gains = [control.lqr(Ai, Bi, Q, R)[0] for Ai, Bi in zip(A, B)] return gains if __name__ == '__main__': import sys v_low = 0 # m/s if len(sys.argv) > 1: v_high = int(sys.argv[1]) else: v_high = 1 # m/s velocities = [v_low, v_high] gains = compute_whipple_lqr_gain(velocities) for v, K in zip(velocities, gains): print('computed LQR controller feedback gain for v = {}'.format(v)) print(-K) print()
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import scipy import control from dtk.bicycle import benchmark_state_space_vs_speed, benchmark_matrices def compute_whipple_lqr_gain(velocity): _, A, B = benchmark_state_space_vs_speed(*benchmark_matrices(), velocity) Q = np.diag([1e5, 1e3, 1e3, 1e2]) R = np.eye(2) gains = [control.lqr(Ai, Bi, Q, R)[0] for Ai, Bi in zip(A, B)] return gains if __name__ == '__main__': import sys v_low = 0 # m/s if len(sys.argv) > 1: v_high = int(sys.argv[1]) else: v_high = 1 # m/s velocities = [v_low, v_high] gains = compute_whipple_lqr_gain(velocities) for v, K in zip(velocities, gains): print('computed LQR controller feedback gain for v = {}'.format(v)) K = -K for r in range(K.shape[0]): row = ', '.join(str(elem) for elem in K[r, :]) if r != K.shape[0] - 1: row += ',' print(row) print()
Change LQR gain element printing
Change LQR gain element printing Change printing of LQR gain elements for easier copying.
Python
bsd-2-clause
oliverlee/phobos,oliverlee/phobos,oliverlee/phobos,oliverlee/phobos
f2506c07caf66b3ad42f6f1c09325097edd2e169
src/django_healthchecks/contrib.py
src/django_healthchecks/contrib.py
import uuid from django.core.cache import cache from django.db import connection def check_database(): """Check if the application can perform a dummy sql query""" cursor = connection.cursor() cursor.execute('SELECT 1; -- Healthcheck') row = cursor.fetchone() return row[0] == 1 def check_cache_default(): """Check if the application can connect to the default cached and read/write some dummy data. """ dummy = str(uuid.uuid4()) key = 'healthcheck:%s' % dummy cache.set(key, dummy, timeout=5) cached_value = cache.get(key) return cached_value == dummy def check_dummy_true(): return True def check_dummy_false(): return False def check_remote_addr(request): return request.META['REMOTE_ADDR']
import uuid from django.core.cache import cache from django.db import connection def check_database(): """Check if the application can perform a dummy sql query""" with connection.cursor() as cursor: cursor.execute('SELECT 1; -- Healthcheck') row = cursor.fetchone() return row[0] == 1 def check_cache_default(): """Check if the application can connect to the default cached and read/write some dummy data. """ dummy = str(uuid.uuid4()) key = 'healthcheck:%s' % dummy cache.set(key, dummy, timeout=5) cached_value = cache.get(key) return cached_value == dummy def check_dummy_true(): return True def check_dummy_false(): return False def check_remote_addr(request): return request.META['REMOTE_ADDR']
Make sure the cursor is properly closed after usage
Make sure the cursor is properly closed after usage
Python
mit
mvantellingen/django-healthchecks
1947acc37d4f45a6b1969edfe3f7f10065e647b2
src/layeredconfig/strategy.py
src/layeredconfig/strategy.py
# -*- coding: utf-8 -*- def add(new, previous=None): if previous is None: return new return previous + new def collect(new, previous=None): if previous is None: return [new] return previous + [new] def merge(new, previous=None): return add(new, previous)
# -*- coding: utf-8 -*- def add(next_, previous=None): if previous is None: return next_ return previous + next_ def collect(next_, previous=None): if previous is None: return [next_] return previous + [next_] def merge(next_, previous=None): return add(next_, previous)
Rename misleading new to next
Rename misleading new to next
Python
bsd-3-clause
hakkeroid/lcconcept
bba433a582a96f5acd59eedb3286e284d81f431d
src/nodeconductor_openstack/tests/test_backend.py
src/nodeconductor_openstack/tests/test_backend.py
import mock from rest_framework import test class MockedSession(mock.MagicMock): auth_ref = 'AUTH_REF' class BaseBackendTestCase(test.APITransactionTestCase): def setUp(self): self.session_patcher = mock.patch('keystoneauth1.session.Session', MockedSession) self.session_patcher.start() self.session_recover_patcher = mock.patch('nodeconductor_openstack.backend.OpenStackSession.recover') self.session_recover_patcher.start() self.keystone_patcher = mock.patch('keystoneclient.v2_0.client.Client') self.mocked_keystone = self.keystone_patcher.start() self.nova_patcher = mock.patch('novaclient.v2.client.Client') self.mocked_nova = self.nova_patcher.start() self.cinder_patcher = mock.patch('cinderclient.v1.client.Client') self.mocked_cinder = self.cinder_patcher.start() def tearDown(self): super(BaseBackendTestCase, self).tearDown() self.session_patcher.stop() self.keystone_patcher.stop() self.nova_patcher.stop() self.cinder_patcher.stop()
import mock from rest_framework import test class MockedSession(mock.MagicMock): auth_ref = 'AUTH_REF' class BaseBackendTestCase(test.APITransactionTestCase): def setUp(self): self.session_patcher = mock.patch('keystoneauth1.session.Session', MockedSession) self.session_patcher.start() self.session_recover_patcher = mock.patch('nodeconductor_openstack.backend.OpenStackSession.recover') self.session_recover_patcher.start() self.keystone_patcher = mock.patch('keystoneclient.v2_0.client.Client') self.mocked_keystone = self.keystone_patcher.start() self.nova_patcher = mock.patch('novaclient.v2.client.Client') self.mocked_nova = self.nova_patcher.start() self.cinder_patcher = mock.patch('cinderclient.v1.client.Client') self.mocked_cinder = self.cinder_patcher.start() def tearDown(self): super(BaseBackendTestCase, self).tearDown() self.session_patcher.stop() self.session_recover_patcher.stop() self.keystone_patcher.stop() self.nova_patcher.stop() self.cinder_patcher.stop()
Stop patcher in tear down
Stop patcher in tear down - itacloud-7198
Python
mit
opennode/nodeconductor-openstack
3b21631f8c0d3820359c1163e7e5340f153c3938
twitter_bot.py
twitter_bot.py
# Import json parsing library import json # Import the necessary methods from "twitter" library from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream # Import "ConfigParser" library to load settings ("configparser" in python 3) from ConfigParser import SafeConfigParser # Load API variables from settings.cfg file parser = SafeConfigParser() parser.read('settings.cfg') settings_dict = dict(parser.items('twitter_settings')) oauth = OAuth(settings_dict['access_token'], settings_dict['access_secret'], settings_dict['consumer_key'], settings_dict['consumer_secret']) # Initiate the connection to Twitter REST API twitter = Twitter(auth=oauth) # Search for latest tweets about query term print twitter.search.tweets(q='satan')
# Import json parsing library import json # Import the necessary methods from "twitter" library from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream # Import "ConfigParser" library to load settings ("configparser" in python 3) from ConfigParser import SafeConfigParser # Load API variables from settings.cfg file parser = SafeConfigParser() parser.read('settings.cfg') settings_dict = dict(parser.items('twitter_settings')) oauth = OAuth(settings_dict['access_token'], settings_dict['access_secret'], settings_dict['consumer_key'], settings_dict['consumer_secret']) # Initiate the connection to Twitter REST API twitter = Twitter(auth=oauth) # Load query term from configuration file query_term = parser.get('query_settings','query_term') # Search for latest tweets about query term # Tweets has components 'search_metadata' and 'statuses' - we want the latter tweets = twitter.search.tweets(q=query_term)['statuses'] # Extract tweetID, username and text of tweets returned from search for tweet in tweets: print tweet['id_str'] print tweet['user']['screen_name'] print tweet['text']
Add initial tweet extraction / load query term from config file
Add initial tweet extraction / load query term from config file
Python
mit
benhoyle/social-media-bot
efbab142afc824f9b2ba4968ffe102c20e0ad7c3
rpp/encoder.py
rpp/encoder.py
from uuid import UUID from scanner import Symbol def tostr(value): if isinstance(value, Symbol): return str(value) elif isinstance(value, str): return '"%s"' % value elif isinstance(value, UUID): return '{%s}' % value elif value is None: return '-' else: return str(value) def encode(lists, indent=2, level=0): result = '<' for i, item in enumerate(lists): if not isinstance(item, list): raise TypeError("%r is not RPP serializable" % item) if i > 0: result += ' ' * (level + 1) * indent if all(not isinstance(x, list) for x in item): name, values = item[0].upper(), item[1:] strvalues = map(tostr, values) result += ' '.join([name] + strvalues) else: result += encode(item, level=(level + 1)) result += '\n' if indent else ' ' result += (' ' * level * indent) + '>' return result
from uuid import UUID from scanner import Symbol def tostr(value): if isinstance(value, Symbol): return str(value) elif isinstance(value, str): return '"%s"' % value elif isinstance(value, float): return '%.14f' % value elif isinstance(value, UUID): return '{%s}' % str(value).upper() elif value is None: return '-' else: return str(value) def encode(lists, indent=2, level=0): if indent == 0: raise ValueError('Indent should be present') result = '<' for i, item in enumerate(lists): if not isinstance(item, list): raise TypeError('%r is not RPP serializable' % item) if i > 0: result += ' ' * (level + 1) * indent if all(not isinstance(x, list) for x in item): name, values = item[0].upper(), item[1:] strvalues = map(tostr, values) result += ' '.join([name] + strvalues) else: result += encode(item, level=(level + 1)) result += '\n' if indent else ' ' result += (' ' * level * indent) + '>' return result
Correct representation of floats and uuids
Correct representation of floats and uuids
Python
bsd-3-clause
Perlence/rpp
fad97c21e2643e5df9759ebf260881b26e918d7c
api/api/views/hacker/get/csv/resume_links.py
api/api/views/hacker/get/csv/resume_links.py
""" Generates a CSV containing approved hackers' resumes """ from hackfsu_com.views.generic import StreamedCsvView from hackfsu_com.util import acl, files from django.conf import settings from api.models import Hackathon, HackerInfo class ResumeLinksCsv(StreamedCsvView): access_manager = acl.AccessManager(acl_accept=[acl.group_organizer]) file_name = 'HackFSU Approved Hackers\' Submitted Resumes.csv' @staticmethod def row_generator(request): h = Hackathon.objects.current() yield ['Approved Hackers\' Submitted Resumes'] yield [ 'First Name', 'Last Name', 'Email', 'School', 'Attended', 'Resume File Name', 'Resume URL' ] for hacker in HackerInfo.objects.filter( hackathon=h, approved=True ): row = [ hacker.user.first_name, hacker.user.last_name, hacker.user.email, str(hacker.school), hacker.attendee_status.checked_in_at is not None ] if len(hacker.resume_file_name) > 0: row.extend([ hacker.resume_file_name.split('/')[-1], settings.URL_BASE + files.get_url(hacker.resume_file_name) ]) yield row
""" Generates a CSV containing approved hackers' resumes """ from hackfsu_com.views.generic import StreamedCsvView from hackfsu_com.util import acl, files from django.conf import settings from api.models import Hackathon, HackerInfo, UserInfo class ResumeLinksCsv(StreamedCsvView): access_manager = acl.AccessManager(acl_accept=[acl.group_organizer]) file_name = 'HackFSU Approved Hackers\' Submitted Resumes.csv' @staticmethod def row_generator(request): h = Hackathon.objects.current() yield ['Approved Hackers\' Submitted Resumes'] yield [ 'First Name', 'Last Name', 'Email', 'School', 'Github', 'LinkedIn', 'Attended', 'Resume File Name', 'Resume URL' ] for hacker in HackerInfo.objects.filter( hackathon=h, approved=True ): user_info = UserInfo.objects.get(user=hacker.user) row = [ hacker.user.first_name, hacker.user.last_name, hacker.user.email, str(hacker.school), user_info.github, user_info.linkedin, hacker.attendee_status.checked_in_at is not None ] if len(hacker.resume_file_name) > 0: row.extend([ hacker.resume_file_name.split('/')[-1], settings.URL_BASE + files.get_url(hacker.resume_file_name) ]) yield row
Add Github+LinkedIn to Hacker Data export
Add Github+LinkedIn to Hacker Data export
Python
apache-2.0
andrewsosa/hackfsu_com,andrewsosa/hackfsu_com,andrewsosa/hackfsu_com,andrewsosa/hackfsu_com