commit
stringlengths
40
40
old_file
stringlengths
4
264
new_file
stringlengths
4
264
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
624
message
stringlengths
15
4.7k
lang
stringclasses
3 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
bcd009c442e42065ba1de313f4892c1a57642daa
TeleinfoParser.py
TeleinfoParser.py
#!/usr/bin/env python class TeleinfoParser: integerKeys = [ 'ISOUSC', 'BASE', 'HCHC', 'HCHP', 'EJPHN', 'EJPHPM', 'BBRHCJB', 'BBRHPJB', 'BBRHCJW', 'BBRHPJW', 'BBRHCJR', 'BBRHPJR', 'PEJP', 'IINST', 'IINST1', 'IINST2', 'IINST3', 'ADPS', 'IMAX', 'IMAX1', 'IMAX2', 'IMAX3', 'PAPP', 'ADIR1', 'ADIR2', 'ADIR3' ] def checksum (self, label, value): """Return the checksum of a value and label""" sum = 32 for c in label + value: sum += ord(c) return chr((sum & 63) + 32) def parse (self, message): """Read and verify Teleinfo datagram and return it as a dict""" trames = [trame.split(" ") for trame in message.strip("\r\n\x03\x02").split("\r\n")] return dict([ [trame[0], int(trame[1]) if trame[0] in self.integerKeys else trame[1]] for trame in trames if (len(trame) == 3) and (self.checksum(trame[0],trame[1]) == trame[2]) ])
#!/usr/bin/env python class TeleinfoParser: integerKeys = [ 'ISOUSC', 'BASE', 'HCHC', 'HCHP', 'EJPHN', 'EJPHPM', 'BBRHCJB', 'BBRHPJB', 'BBRHCJW', 'BBRHPJW', 'BBRHCJR', 'BBRHPJR', 'PEJP', 'IINST', 'IINST1', 'IINST2', 'IINST3', 'ADPS', 'IMAX', 'IMAX1', 'IMAX2', 'IMAX3', 'PAPP', 'ADIR1', 'ADIR2', 'ADIR3' ] def checksum (self, label, value): """Return the checksum of a value and label""" sum = 32 for c in label + value: sum += ord(c) return chr((sum & 63) + 32) def parse (self, message): """Read and verify Teleinfo datagram and return it as a dict""" trames = [trame.split(" ", 2) for trame in message.strip("\r\n\x03\x02").split("\r\n")] return dict([ [trame[0], int(trame[1]) if trame[0] in self.integerKeys else trame[1]] for trame in trames if (len(trame) == 3) and (self.checksum(trame[0],trame[1]) == trame[2]) ])
Fix incorrect checksum verification when checksum is 32 (0x20, space)
Fix incorrect checksum verification when checksum is 32 (0x20, space)
Python
mit
pyrou/UDPTeleinfoServer
ca96de4c3fdd788833e3f343de2c711c5bf6e40f
packages/dcos-integration-test/extra/get_test_group.py
packages/dcos-integration-test/extra/get_test_group.py
""" Usage: $ python test_group_name.py group_1 test_foo.py test_bar.py::TestClass $ This is used by CI to run only a certain set of tests on a particular builder. See ``test_groups.yaml`` for details. """ import yaml from pathlib import Path from typing import List import click def patterns_from_group(group_name: str) -> List[str]: """ Given a group name, return all the pytest patterns defined for that group in ``test_groups.yaml``. """ test_group_file = Path(__file__).parent / 'test_groups.yaml' test_group_file_contents = test_group_file.read_text() test_groups = yaml.load(test_group_file_contents)['groups'] return test_groups[group_name] @click.command('list-integration-test-patterns') @click.argument('group_name') def list_integration_test_patterns(group_name: str) -> None: """ Perform a release. """ test_patterns = patterns_from_group(group_name=group_name) click.echo(' '.join(test_patterns), nl=False) if __name__ == '__main__': list_integration_test_patterns()
""" Usage: $ python get_test_group.py group_1 test_foo.py test_bar.py::TestClass $ This is used by CI to run only a certain set of tests on a particular builder. See ``test_groups.yaml`` for details. """ import yaml from pathlib import Path from typing import List import click def patterns_from_group(group_name: str) -> List[str]: """ Given a group name, return all the pytest patterns defined for that group in ``test_groups.yaml``. """ test_group_file = Path(__file__).parent / 'test_groups.yaml' test_group_file_contents = test_group_file.read_text() test_groups = yaml.load(test_group_file_contents)['groups'] return test_groups[group_name] @click.command('list-integration-test-patterns') @click.argument('group_name') def list_integration_test_patterns(group_name: str) -> None: """ Perform a release. """ test_patterns = patterns_from_group(group_name=group_name) click.echo(' '.join(test_patterns), nl=False) if __name__ == '__main__': list_integration_test_patterns()
Fix usage comment to refer to the correct filename
Fix usage comment to refer to the correct filename
Python
apache-2.0
mesosphere-mergebot/dcos,dcos/dcos,GoelDeepak/dcos,mesosphere-mergebot/mergebot-test-dcos,dcos/dcos,kensipe/dcos,mesosphere-mergebot/mergebot-test-dcos,dcos/dcos,mesosphere-mergebot/dcos,kensipe/dcos,GoelDeepak/dcos,GoelDeepak/dcos,kensipe/dcos,kensipe/dcos,dcos/dcos,mesosphere-mergebot/dcos,mesosphere-mergebot/dcos,mesosphere-mergebot/mergebot-test-dcos,mesosphere-mergebot/mergebot-test-dcos,dcos/dcos,GoelDeepak/dcos
fbad1649e9939a3be4194e0d508ff5889f48bb6f
unleash/plugins/utils_assign.py
unleash/plugins/utils_assign.py
import re # regular expression for finding assignments _quotes = "['|\"|\"\"\"]" BASE_ASSIGN_PATTERN = r'({}\s*=\s*[ubr]?' + _quotes + r')(.*?)(' +\ _quotes + r')' def find_assign(data, varname): """Finds a substring that looks like an assignment. :param data: Source to search in. :param varname: Name of the variable for which an assignment should be found. """ ASSIGN_RE = re.compile(BASE_ASSIGN_PATTERN.format(varname)) if len(ASSIGN_RE.findall(data)) > 1: raise ValueError('Found multiple {}-strings.'.format(varname)) if len(ASSIGN_RE.findall(data)) < 1: raise ValueError('No version assignment ("{}") found.'.format(varname)) return ASSIGN_RE.search(data).group(2) def replace_assign(data, varname, new_value): ASSIGN_RE = re.compile(BASE_ASSIGN_PATTERN.format(varname)) def repl(m): return m.group(1) + new_value + m.group(3) return ASSIGN_RE.sub(repl, data)
from unleash.exc import PluginError import re # regular expression for finding assignments _quotes = "['|\"|\"\"\"]" BASE_ASSIGN_PATTERN = r'({}\s*=\s*[ubr]?' + _quotes + r')(.*?)(' +\ _quotes + r')' def find_assign(data, varname): """Finds a substring that looks like an assignment. :param data: Source to search in. :param varname: Name of the variable for which an assignment should be found. """ ASSIGN_RE = re.compile(BASE_ASSIGN_PATTERN.format(varname)) if len(ASSIGN_RE.findall(data)) > 1: raise PluginError('Found multiple {}-strings.'.format(varname)) if len(ASSIGN_RE.findall(data)) < 1: raise PluginError('No version assignment ("{}") found.' .format(varname)) return ASSIGN_RE.search(data).group(2) def replace_assign(data, varname, new_value): ASSIGN_RE = re.compile(BASE_ASSIGN_PATTERN.format(varname)) def repl(m): return m.group(1) + new_value + m.group(3) return ASSIGN_RE.sub(repl, data)
Raise PluginErrors instead of ValueErrors in versions.
Raise PluginErrors instead of ValueErrors in versions.
Python
mit
mbr/unleash
f339af2e48f0e485f13d368dad47f541264c4f58
web/processors/user.py
web/processors/user.py
from django.contrib.auth.models import User from django_countries import countries def get_user(user_id): user = User.objects.get(id=user_id) return user def get_user_profile(user_id): user = User.objects.get(id=user_id) return user.profile def get_ambassadors(): ambassadors = [] aambassadors = User.objects.filter(groups__name='ambassadors') for ambassador in aambassadors: ambassadors.append(ambassador.profile) return ambassadors def get_ambassadors_for_countries(): ambassadors = get_ambassadors() countries_ambassadors = [] for code, name in list(countries): readable_name = unicode(name) found_ambassadors = [] for ambassador in ambassadors: if ambassador.country == code: found_ambassadors.append(ambassador) countries_ambassadors.append((readable_name,found_ambassadors)) countries_ambassadors.sort() return countries_ambassadors def update_user_email(user_id, new_email): user = User.objects.get(id=user_id) user.email = new_email user.save(update_fields=["email"]) return user
from django.contrib.auth.models import User from django_countries import countries def get_user(user_id): user = User.objects.get(id=user_id) return user def get_user_profile(user_id): user = User.objects.get(id=user_id) return user.profile def get_ambassadors(): ambassadors = [] aambassadors = User.objects.filter(groups__name='ambassadors').order_by('date_joined') for ambassador in aambassadors: ambassadors.append(ambassador.profile) return ambassadors def get_ambassadors_for_countries(): ambassadors = get_ambassadors() countries_ambassadors = [] for code, name in list(countries): readable_name = unicode(name) found_ambassadors = [] for ambassador in ambassadors: if ambassador.country == code: found_ambassadors.append(ambassador) countries_ambassadors.append((readable_name,found_ambassadors)) countries_ambassadors.sort() return countries_ambassadors def update_user_email(user_id, new_email): user = User.objects.get(id=user_id) user.email = new_email user.save(update_fields=["email"]) return user
Sort listed ambassadors by date_joined
Sort listed ambassadors by date_joined
Python
mit
ercchy/coding-events,michelesr/coding-events,joseihf/coding-events,ioana-chiorean/coding-events,joseihf/coding-events,codeeu/coding-events,michelesr/coding-events,joseihf/coding-events,ercchy/coding-events,codeeu/coding-events,ercchy/coding-events,michelesr/coding-events,ioana-chiorean/coding-events,codeeu/coding-events,codeeu/coding-events,ioana-chiorean/coding-events,ioana-chiorean/coding-events,codeeu/coding-events,ercchy/coding-events,ercchy/coding-events,michelesr/coding-events,joseihf/coding-events,joseihf/coding-events,michelesr/coding-events,ioana-chiorean/coding-events
bb2234447039df6bee80842749b0ecdb19fb62fc
aerende/models.py
aerende/models.py
import uuid class Note(object): """ A note. Currently has a title, tags, texr and a priority.""" def __init__(self, title, tags, text, priority=1, unique_id=None): if unique_id is None: self.id = str(uuid.uuid4()) else: self.id = unique_id self.title = title self.tags = tags self.text = text self.priority = priority def __str__(self): return str(self.to_dictionary) def to_dictionary(self): return { self.id: { 'title': self.title, 'tags': str(self.tags), 'text': self.text, 'priority': self.priority, } } class Tag(object): """A note tag, for categorisation/filtering""" def __init__(self, type, frequency): self.type = type self.frequency = frequency def __str__(self): return "[{0}] {1}".format(self.frequency, self.type)
import uuid class Note(object): """ A note. Currently has a title, tags, texr and a priority.""" def __init__(self, title, tags, text, priority=1, unique_id=None): if unique_id is None: self.id = str(uuid.uuid4()) else: self.id = unique_id self.title = title self.tags = self.__verify_tags(tags) self.text = text self.priority = priority def __str__(self): return str(self.to_dictionary) def __verify_tags(self, tags): return list(set(tags)) def to_dictionary(self): return { self.id: { 'title': self.title, 'tags': str(self.tags), 'text': self.text, 'priority': self.priority, } } class Tag(object): """A note tag, for categorisation/filtering""" def __init__(self, type, frequency): self.type = type self.frequency = frequency def __str__(self): return "[{0}] {1}".format(self.frequency, self.type)
Remove duplicate tags during init
Remove duplicate tags during init
Python
mit
Autophagy/aerende
83919e74b7d20688811a4f782d4fccaf3bc3c055
comics/comics/hijinksensue.py
comics/comics/hijinksensue.py
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "HijiNKS Ensue" language = "en" url = "http://hijinksensue.com/" start_date = "2007-05-11" rights = "Joel Watson" class Crawler(CrawlerBase): history_capable_days = 180 time_zone = "US/Central" def crawl(self, pub_date): feed = self.parse_feed("http://hijinksensue.com/feed/") for entry in feed.for_date(pub_date): if "/comic/" not in entry.link: continue url = entry.content0.src('img[src*="-300x120"]') if not url: continue url = url.replace("-300x120", "") title = entry.title return CrawlerImage(url, title)
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "HijiNKS Ensue" language = "en" url = "http://hijinksensue.com/" start_date = "2007-05-11" rights = "Joel Watson" active = False class Crawler(CrawlerBase): history_capable_date = '2015-03-11' time_zone = "US/Central" def crawl(self, pub_date): feed = self.parse_feed("http://hijinksensue.com/feed/") for entry in feed.for_date(pub_date): if "/comic/" not in entry.link: continue url = entry.content0.src('img[srcset*="-300x120"]') if not url: continue url = url.replace("-300x120", "") title = entry.title return CrawlerImage(url, title)
Update "HijiNKS Ensue" after feed change
Update "HijiNKS Ensue" after feed change
Python
agpl-3.0
datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics,jodal/comics
7e025a5fa40d5f7ba5721ad01951ad2020ed2485
phoxpy/tests/test_client.py
phoxpy/tests/test_client.py
# -*- coding: utf-8 -*- # # Copyright (C) 2011 Alexander Shorin # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # import unittest from phoxpy import client from phoxpy.tests.lisserver import MockHttpSession class SessionTestCase(unittest.TestCase): def test_login(self): session = client.Session(login='John', password='Doe', client_id='foo-bar-baz') self.assertFalse(session.is_active()) session.open('localhost', http_session=MockHttpSession()) self.assertTrue(session.is_active()) def test_logout(self): session = client.Session(login='John', password='Doe', client_id='foo-bar-baz') self.assertFalse(session.is_active()) session.open('localhost', http_session=MockHttpSession()) self.assertTrue(session.is_active()) session.close() self.assertFalse(session.is_active()) if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- # # Copyright (C) 2011 Alexander Shorin # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # import unittest from phoxpy import client from phoxpy.server import MockHttpSession, SimpleLISServer class SessionTestCase(unittest.TestCase): def setUp(self): self.server = SimpleLISServer('4.2', '31415') self.server.ext_auth.add_license('foo-bar-baz') self.server.ext_auth.add_user('John', 'Doe') def test_login(self): session = client.Session(login='John', password='Doe', client_id='foo-bar-baz') self.assertFalse(session.is_active()) session.open('localhost', http_session=MockHttpSession(self.server)) self.assertTrue(session.is_active()) def test_logout(self): session = client.Session(login='John', password='Doe', client_id='foo-bar-baz') self.assertFalse(session.is_active()) session.open('localhost', http_session=MockHttpSession(self.server)) self.assertTrue(session.is_active()) session.close() self.assertFalse(session.is_active()) if __name__ == '__main__': unittest.main()
Update tests for new environment.
Update tests for new environment.
Python
bsd-3-clause
kxepal/phoxpy
20b13d500ea1cfa4b06413f0f02114bed60ca98f
apps/challenges/auth.py
apps/challenges/auth.py
OWNER_PERMISSIONS = ['challenges.%s_submission' % v for v in ['edit', 'delete']] class SubmissionBackend(object): """Provide custom permission logic for submissions.""" supports_object_permissions = True supports_anonymous_user = True def authenticate(self): """This backend doesn't provide any authentication functionality.""" return None def has_perm(self, user_obj, perm, obj=None): if perm in OWNER_PERMISSIONS: # Owners can edit and delete their own submissions if obj is not None and user_obj == obj.created_by.user: return True if perm == 'challenges.view_submission' and obj is not None: # Live, non-draft submissions are visible to anyone. Other # submissions are visible only to admins and their owners return ((obj.is_live and not obj.is_draft) or user_obj == obj.created_by.user) return False
OWNER_PERMISSIONS = ['challenges.%s_submission' % v for v in ['edit', 'delete']] class SubmissionBackend(object): """Provide custom permission logic for submissions.""" supports_object_permissions = True supports_anonymous_user = True def authenticate(self): """This backend doesn't provide any authentication functionality.""" return None def has_perm(self, user_obj, perm, obj=None): if perm in OWNER_PERMISSIONS: # Owners can edit and delete their own submissions if obj is not None and user_obj == obj.created_by.user: return True if perm == 'challenges.view_submission' and obj is not None: # Live, non-draft submissions are visible to anyone. Other # submissions are visible only to admins and their owners return ((not obj.is_draft) or user_obj == obj.created_by.user) return False
Remove 'is_live' from draft visibility check.
Remove 'is_live' from draft visibility check.
Python
bsd-3-clause
mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite
ba4c2dc22aae5dd4f862aad7c388eecf36acfbd8
app/main/forms.py
app/main/forms.py
from flask_wtf import Form from wtforms.validators import DataRequired, Email from dmutils.forms import StripWhitespaceStringField class EmailAddressForm(Form): email_address = StripWhitespaceStringField('Email address', validators=[ DataRequired(message="Email can not be empty"), Email(message="Please enter a valid email address") ]) class MoveUserForm(Form): user_to_move_email_address = StripWhitespaceStringField('Move an existing user to this supplier', validators=[ DataRequired(message="Email can not be empty"), Email(message="Please enter a valid email address") ]) class EmailDomainForm(Form): new_buyer_domain = StripWhitespaceStringField('Add a buyer email domain', validators=[ DataRequired(message="The domain field can not be empty.") ])
from flask_wtf import Form from wtforms import validators from dmutils.forms import StripWhitespaceStringField class EmailAddressForm(Form): email_address = StripWhitespaceStringField('Email address', validators=[ validators.DataRequired(message="Email can not be empty"), validators.Email(message="Please enter a valid email address") ]) class MoveUserForm(Form): user_to_move_email_address = StripWhitespaceStringField('Move an existing user to this supplier', validators=[ validators.DataRequired(message="Email can not be empty"), validators.Email(message="Please enter a valid email address") ]) class EmailDomainForm(Form): new_buyer_domain = StripWhitespaceStringField('Add a buyer email domain', validators=[ validators.DataRequired(message="The domain field can not be empty.") ])
Change import to indicate function of imported classes
Change import to indicate function of imported classes
Python
mit
alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend
b167b1c8099dc184c366416dab9a7c6e5be7423a
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): value = value[0] 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({'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.')
Handle cases where there are multiple values for a field.
Handle cases where there are multiple values for a field.
Python
apache-2.0
Ghalko/osf.io,caneruguz/osf.io,felliott/osf.io,binoculars/osf.io,icereval/osf.io,ticklemepierce/osf.io,caneruguz/osf.io,mattclark/osf.io,brianjgeiger/osf.io,HalcyonChimera/osf.io,brandonPurvis/osf.io,laurenrevere/osf.io,aaxelb/osf.io,MerlinZhang/osf.io,caseyrygt/osf.io,doublebits/osf.io,Nesiehr/osf.io,kch8qx/osf.io,acshi/osf.io,sbt9uc/osf.io,sloria/osf.io,danielneis/osf.io,erinspace/osf.io,billyhunt/osf.io,icereval/osf.io,erinspace/osf.io,baylee-d/osf.io,emetsger/osf.io,alexschiller/osf.io,kwierman/osf.io,felliott/osf.io,saradbowman/osf.io,KAsante95/osf.io,adlius/osf.io,njantrania/osf.io,leb2dg/osf.io,cslzchen/osf.io,arpitar/osf.io,petermalcolm/osf.io,danielneis/osf.io,RomanZWang/osf.io,adlius/osf.io,KAsante95/osf.io,sbt9uc/osf.io,brianjgeiger/osf.io,TomBaxter/osf.io,ticklemepierce/osf.io,GageGaskins/osf.io,ZobairAlijan/osf.io,abought/osf.io,mluo613/osf.io,HalcyonChimera/osf.io,GageGaskins/osf.io,njantrania/osf.io,samanehsan/osf.io,samanehsan/osf.io,asanfilippo7/osf.io,DanielSBrown/osf.io,jnayak1/osf.io,mluke93/osf.io,ticklemepierce/osf.io,MerlinZhang/osf.io,doublebits/osf.io,felliott/osf.io,arpitar/osf.io,adlius/osf.io,KAsante95/osf.io,icereval/osf.io,Ghalko/osf.io,zachjanicki/osf.io,KAsante95/osf.io,acshi/osf.io,TomHeatwole/osf.io,ckc6cz/osf.io,jmcarp/osf.io,rdhyee/osf.io,sbt9uc/osf.io,hmoco/osf.io,mattclark/osf.io,RomanZWang/osf.io,zamattiac/osf.io,leb2dg/osf.io,ZobairAlijan/osf.io,TomBaxter/osf.io,Ghalko/osf.io,Nesiehr/osf.io,binoculars/osf.io,billyhunt/osf.io,petermalcolm/osf.io,rdhyee/osf.io,crcresearch/osf.io,ZobairAlijan/osf.io,mluo613/osf.io,cslzchen/osf.io,SSJohns/osf.io,adlius/osf.io,haoyuchen1992/osf.io,monikagrabowska/osf.io,amyshi188/osf.io,amyshi188/osf.io,kwierman/osf.io,kch8qx/osf.io,alexschiller/osf.io,Ghalko/osf.io,sbt9uc/osf.io,chrisseto/osf.io,brandonPurvis/osf.io,caseyrollins/osf.io,cwisecarver/osf.io,wearpants/osf.io,zamattiac/osf.io,DanielSBrown/osf.io,amyshi188/osf.io,mfraezz/osf.io,kwierman/osf.io,haoyuchen1992/osf.io,caseyrygt/osf.io,asanfilippo7/osf.io,abought/osf.io,caseyrygt/osf.io,KAsante95/osf.io,abought/osf.io,GageGaskins/osf.io,mluke93/osf.io,caneruguz/osf.io,ZobairAlijan/osf.io,Nesiehr/osf.io,DanielSBrown/osf.io,mfraezz/osf.io,chennan47/osf.io,Nesiehr/osf.io,samanehsan/osf.io,TomHeatwole/osf.io,cslzchen/osf.io,alexschiller/osf.io,billyhunt/osf.io,jmcarp/osf.io,jnayak1/osf.io,acshi/osf.io,cosenal/osf.io,TomBaxter/osf.io,cwisecarver/osf.io,kch8qx/osf.io,kch8qx/osf.io,brianjgeiger/osf.io,Johnetordoff/osf.io,baylee-d/osf.io,mluke93/osf.io,doublebits/osf.io,RomanZWang/osf.io,arpitar/osf.io,HalcyonChimera/osf.io,brandonPurvis/osf.io,Johnetordoff/osf.io,TomHeatwole/osf.io,zamattiac/osf.io,samchrisinger/osf.io,leb2dg/osf.io,sloria/osf.io,RomanZWang/osf.io,jnayak1/osf.io,erinspace/osf.io,TomHeatwole/osf.io,SSJohns/osf.io,cwisecarver/osf.io,rdhyee/osf.io,sloria/osf.io,monikagrabowska/osf.io,Johnetordoff/osf.io,alexschiller/osf.io,ckc6cz/osf.io,caseyrollins/osf.io,SSJohns/osf.io,leb2dg/osf.io,Johnetordoff/osf.io,pattisdr/osf.io,chrisseto/osf.io,cslzchen/osf.io,ckc6cz/osf.io,doublebits/osf.io,monikagrabowska/osf.io,MerlinZhang/osf.io,pattisdr/osf.io,aaxelb/osf.io,jmcarp/osf.io,CenterForOpenScience/osf.io,monikagrabowska/osf.io,jmcarp/osf.io,mluo613/osf.io,caseyrygt/osf.io,danielneis/osf.io,chennan47/osf.io,hmoco/osf.io,mluo613/osf.io,zamattiac/osf.io,samanehsan/osf.io,felliott/osf.io,abought/osf.io,njantrania/osf.io,SSJohns/osf.io,emetsger/osf.io,wearpants/osf.io,wearpants/osf.io,laurenrevere/osf.io,danielneis/osf.io,binoculars/osf.io,CenterForOpenScience/osf.io,caseyrollins/osf.io,GageGaskins/osf.io,emetsger/osf.io,asanfilippo7/osf.io,kch8qx/osf.io,acshi/osf.io,CenterForOpenScience/osf.io,GageGaskins/osf.io,zachjanicki/osf.io,mattclark/osf.io,jnayak1/osf.io,mfraezz/osf.io,samchrisinger/osf.io,samchrisinger/osf.io,arpitar/osf.io,chennan47/osf.io,zachjanicki/osf.io,acshi/osf.io,amyshi188/osf.io,haoyuchen1992/osf.io,caneruguz/osf.io,MerlinZhang/osf.io,hmoco/osf.io,billyhunt/osf.io,haoyuchen1992/osf.io,zachjanicki/osf.io,hmoco/osf.io,cosenal/osf.io,chrisseto/osf.io,ticklemepierce/osf.io,aaxelb/osf.io,alexschiller/osf.io,crcresearch/osf.io,monikagrabowska/osf.io,cosenal/osf.io,mluo613/osf.io,mluke93/osf.io,samchrisinger/osf.io,mfraezz/osf.io,brandonPurvis/osf.io,brianjgeiger/osf.io,petermalcolm/osf.io,laurenrevere/osf.io,aaxelb/osf.io,RomanZWang/osf.io,cwisecarver/osf.io,CenterForOpenScience/osf.io,HalcyonChimera/osf.io,billyhunt/osf.io,wearpants/osf.io,ckc6cz/osf.io,doublebits/osf.io,emetsger/osf.io,asanfilippo7/osf.io,chrisseto/osf.io,crcresearch/osf.io,kwierman/osf.io,brandonPurvis/osf.io,rdhyee/osf.io,njantrania/osf.io,pattisdr/osf.io,cosenal/osf.io,saradbowman/osf.io,baylee-d/osf.io,DanielSBrown/osf.io,petermalcolm/osf.io
b9f6939ea0569ecd54141cbee064a3f15fcf1937
arrow/api.py
arrow/api.py
# -*- coding: utf-8 -*- ''' Provides the default implementation of :class:`ArrowFactory <arrow.factory.ArrowFactory>` methods for use as a module API. ''' from __future__ import absolute_import from arrow.factory import ArrowFactory # internal default factory. _factory = ArrowFactory() def get(*args, **kwargs): ''' Implements the default :class:`ArrowFactory <arrow.factory.ArrowFactory>` ``get`` method. ''' return _factory.get(*args, **kwargs) def utcnow(): ''' Implements the default :class:`ArrowFactory <arrow.factory.ArrowFactory>` ``utcnow`` method. ''' return _factory.utcnow() def now(tz=None): ''' Implements the default :class:`ArrowFactory <arrow.factory.ArrowFactory> ``now`` method. ''' return _factory.now(tz) def factory(type): ''' Returns an :class:`.ArrowFactory` for the specified :class:`Arrow <arrow.arrow.Arrow>` or derived type. :param type: the type, :class:`Arrow <arrow.arrow.Arrow>` or derived. ''' return ArrowFactory(type) __all__ = ['get', 'utcnow', 'now', 'factory', 'iso']
# -*- coding: utf-8 -*- ''' Provides the default implementation of :class:`ArrowFactory <arrow.factory.ArrowFactory>` methods for use as a module API. ''' from __future__ import absolute_import from arrow.factory import ArrowFactory # internal default factory. _factory = ArrowFactory() def get(*args, **kwargs): ''' Implements the default :class:`ArrowFactory <arrow.factory.ArrowFactory>` ``get`` method. ''' return _factory.get(*args, **kwargs) def utcnow(): ''' Implements the default :class:`ArrowFactory <arrow.factory.ArrowFactory>` ``utcnow`` method. ''' return _factory.utcnow() def now(tz=None): ''' Implements the default :class:`ArrowFactory <arrow.factory.ArrowFactory>` ``now`` method. ''' return _factory.now(tz) def factory(type): ''' Returns an :class:`.ArrowFactory` for the specified :class:`Arrow <arrow.arrow.Arrow>` or derived type. :param type: the type, :class:`Arrow <arrow.arrow.Arrow>` or derived. ''' return ArrowFactory(type) __all__ = ['get', 'utcnow', 'now', 'factory', 'iso']
Fix typo in reference ":class:`ArrowFactory <...>"
Fix typo in reference ":class:`ArrowFactory <...>"
Python
apache-2.0
crsmithdev/arrow
0155ed7c37fd4cafa2650911d4f902a3a8982761
test/test_bot.py
test/test_bot.py
import re import unittest from gather.bot import ListenerBot class TestGatherBot(unittest.TestCase): def test_register(self): bot = ListenerBot() self.assertEqual({}, bot.actions) regex = r'^test' action = unittest.mock.Mock() bot.register_action(regex, action) self.assertEqual( {regex: (re.compile(regex, re.IGNORECASE), action)}, bot.actions ) if __name__ == '__main__': unittest.main()
import asyncio import re import unittest from unittest import mock from gather.bot import ListenerBot def async_test(f): # http://stackoverflow.com/a/23036785/304210 def wrapper(*args, **kwargs): coro = asyncio.coroutine(f) future = coro(*args, **kwargs) loop = asyncio.get_event_loop() loop.run_until_complete(future) return wrapper class TestGatherBot(unittest.TestCase): def test_register(self): bot = ListenerBot() self.assertEqual({}, bot.actions) regex = r'^test' action = mock.Mock() bot.register_action(regex, action) self.assertEqual( {regex: (re.compile(regex, re.IGNORECASE), action)}, bot.actions ) @async_test def test_on_message_from_bot(self): bot = ListenerBot() bot.username = 'testuser' regex = r'^test' action = mock.Mock() bot.actions = {regex: (re.compile(regex, re.IGNORECASE), action)} bot.on_message(mock.Mock(), mock.Mock, 'test') action.assert_not_called() if __name__ == '__main__': unittest.main()
Add a test for on_message
Add a test for on_message
Python
mit
veryhappythings/discord-gather
158f1101c3c13db5df916329a66517c7bb85e132
plata/context_processors.py
plata/context_processors.py
import plata def plata_context(request): """ Adds a few variables from Plata to the context if they are available: * ``plata.shop``: The current :class:`plata.shop.views.Shop` instance * ``plata.order``: The current order * ``plata.contact``: The current contact instance * ``plata.price_includes_tax``: Whether prices include tax or not """ shop = plata.shop_instance() return {'plata': { 'shop': shop, 'order': shop.order_from_request(request), 'contact': (shop.contact_from_user(request.user) if hasattr(request, 'user') else None), }} if shop else {}
import plata def plata_context(request): """ Adds a few variables from Plata to the context if they are available: * ``plata.shop``: The current :class:`plata.shop.views.Shop` instance * ``plata.order``: The current order * ``plata.contact``: The current contact instance * ``plata.price_includes_tax``: Whether prices include tax or not """ shop = plata.shop_instance() return {'plata': { 'shop': shop, 'order': shop.order_from_request(request), 'contact': (shop.contact_from_user(request.user) if hasattr(request, 'user') else None), 'price_includes_tax': shop.price_includes_tax(request), }} if shop else {}
Add current value for price_includes_tax to context
Add current value for price_includes_tax to context
Python
bsd-3-clause
armicron/plata,armicron/plata,armicron/plata
22c7da6d3de76cf6c36b4206f204a9ee979ba5f7
strides/graphs.py
strides/graphs.py
import pandas as pd import matplotlib matplotlib.use("pdf") import matplotlib.pyplot as plt import sys import os.path figdir = "figures" df = pd.read_csv(sys.stdin, " ", header=None, index_col=0, names=[2**(i) for i in range(6)]+["rand"]) print(df) #print(df["X2"]/2**df.index) df.plot(logy=True) plt.title("run time for array access") plt.xlabel("scale") plt.ylabel("seconds") plt.savefig(os.path.join([figdir,"graph.pdf"])) plt.figure() sizes = 2**df.index print(sizes) petf = (df.T/sizes).T print( petf ) petf.plot(logy=True) plt.title("normalized running time") plt.xlabel("scale") plt.ylabel("nanoseconds per element") plt.savefig(os.path.join([figdir,"perelement.pdf"]))
import pandas as pd import matplotlib matplotlib.use("pdf") import matplotlib.pyplot as plt import sys df = pd.read_csv(sys.stdin, " ", header=None, index_col=0) print(df) print(df["X2"]/2**df.index) df.plot(logy=True) plt.savefig("graph.pdf")
Add perelement figures write figures into subdirectory
Add perelement figures write figures into subdirectory
Python
bsd-3-clause
jpfairbanks/cse6140,jpfairbanks/cse6140,jpfairbanks/cse6140
47e4e74dcf5e2a10f1e231d2fa8af453213e77fb
Lib/test/test_winsound.py
Lib/test/test_winsound.py
# Rediculously simple test of the winsound module for Windows. import winsound for i in range(100, 2000, 100): winsound.Beep(i, 75) print "Hopefully you heard some sounds increasing in frequency!"
# Ridiculously simple test of the winsound module for Windows. import winsound for i in range(100, 2000, 100): winsound.Beep(i, 75) print "Hopefully you heard some sounds increasing in frequency!"
Fix spelling error and remove Windows line endings.
Fix spelling error and remove Windows line endings.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
1579eb8d2de5aa49ad7012ab08350659a20725e1
basis/managers.py
basis/managers.py
from django.db import models class BasisModelManager(models.Manager): def get_query_set(self): return super(BasisModelManager, self).get_query_set().filter(deleted=False)
from django.db import models from .compat import DJANGO16 if DJANGO16: class BasisModelManager(models.Manager): def get_queryset(self): return super(BasisModelManager, self).get_queryset().filter(deleted=False) else: class BasisModelManager(models.Manager): def get_query_set(self): return super(BasisModelManager, self).get_query_set().filter(deleted=False)
Fix deprecation warning for get_query_set
Fix deprecation warning for get_query_set get_query_set was renamed get_queryset in django 1.6
Python
mit
frecar/django-basis
4b000960edc30d9917b80646a0374fb8bf99efcb
storage/tests/testtools.py
storage/tests/testtools.py
""" Test tools for the storage service. """ import unittest from storage.storage import app as storage_app, db class InMemoryStorageTests(unittest.TestCase): """ Set up and tear down an application with an in memory database for testing. """ def setUp(self): storage_app.config['TESTING'] = True storage_app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' self.storage_app = storage_app.test_client() self.storage_url_map = storage_app.url_map with storage_app.app_context(): db.create_all() def tearDown(self): with storage_app.app_context(): db.session.remove() db.drop_all()
""" Test tools for the storage service. """ import unittest from storage.storage import app, db class InMemoryStorageTests(unittest.TestCase): """ Set up and tear down an application with an in memory database for testing. """ def setUp(self): app.config['TESTING'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' self.storage_app = app.test_client() self.storage_url_map = app.url_map with app.app_context(): db.create_all() def tearDown(self): with app.app_context(): db.session.remove() db.drop_all()
Remove unnecessary rename on input
Remove unnecessary rename on input
Python
mit
jenca-cloud/jenca-authentication
505456fed7bdbd6b2cd78eae10b3b64657cd377b
tests/unit/test_commands.py
tests/unit/test_commands.py
import pytest from pip._internal.commands import commands_dict, create_command def test_commands_dict__order(): """ Check the ordering of commands_dict. """ names = list(commands_dict) # A spot-check is sufficient to check that commands_dict encodes an # ordering. assert names[0] == 'install' assert names[-1] == 'help' @pytest.mark.parametrize('name', list(commands_dict)) def test_create_command(name): """Test creating an instance of each available command.""" command = create_command(name) assert command.name == name assert command.summary == commands_dict[name].summary
import pytest from pip._internal.cli.req_command import ( IndexGroupCommand, RequirementCommand, SessionCommandMixin, ) from pip._internal.commands import commands_dict, create_command def check_commands(pred, expected): """ Check the commands satisfying a predicate. """ commands = [create_command(name) for name in sorted(commands_dict)] actual = [command.name for command in commands if pred(command)] assert actual == expected, 'actual: {}'.format(actual) def test_commands_dict__order(): """ Check the ordering of commands_dict. """ names = list(commands_dict) # A spot-check is sufficient to check that commands_dict encodes an # ordering. assert names[0] == 'install' assert names[-1] == 'help' @pytest.mark.parametrize('name', list(commands_dict)) def test_create_command(name): """Test creating an instance of each available command.""" command = create_command(name) assert command.name == name assert command.summary == commands_dict[name].summary def test_session_commands(): """ Test which commands inherit from SessionCommandMixin. """ def is_session_command(command): return isinstance(command, SessionCommandMixin) expected = ['download', 'install', 'list', 'search', 'uninstall', 'wheel'] check_commands(is_session_command, expected) def test_index_group_commands(): """ Test the commands inheriting from IndexGroupCommand. """ expected = ['download', 'install', 'list', 'wheel'] def is_index_group_command(command): return isinstance(command, IndexGroupCommand) check_commands(is_index_group_command, expected) # Also check that the commands inheriting from IndexGroupCommand are # exactly the commands with the --no-index option. def has_option_no_index(command): return command.parser.has_option('--no-index') check_commands(has_option_no_index, expected) def test_requirement_commands(): """ Test which commands inherit from RequirementCommand. """ def is_requirement_command(command): return isinstance(command, RequirementCommand) check_commands(is_requirement_command, ['download', 'install', 'wheel'])
Test the command class inheritance for each command.
Test the command class inheritance for each command.
Python
mit
pradyunsg/pip,xavfernandez/pip,pfmoore/pip,rouge8/pip,xavfernandez/pip,pypa/pip,sbidoul/pip,pfmoore/pip,pypa/pip,rouge8/pip,rouge8/pip,pradyunsg/pip,xavfernandez/pip,sbidoul/pip
e183578b6211d7311d62100ad643cbaf8408de99
tests/__init__.py
tests/__init__.py
import unittest.mock def _test_module_init(module, main_name="main"): with unittest.mock.patch.object(module, main_name, return_value=0): with unittest.mock.patch.object(module, "__name__", "__main__"): with unittest.mock.patch.object(module.sys, "exit") as exit: module.module_init() return exit.call_args[0][0] == 0
import unittest.mock def _test_module_init(module, main_name="main"): with unittest.mock.patch.object( module, main_name, return_value=0 ), unittest.mock.patch.object( module, "__name__", "__main__" ), unittest.mock.patch.object( module.sys, "exit" ) as exit: module.module_init() return exit.call_args[0][0] == 0
Use multiple context managers on one with statement (thanks Anna)
Use multiple context managers on one with statement (thanks Anna)
Python
mpl-2.0
rfinnie/2ping,rfinnie/2ping
d96e52c346314622afc904a2917416028c6784e3
swampdragon_live/models.py
swampdragon_live/models.py
# -*- coding: utf-8 -*- from django.contrib.contenttypes.models import ContentType from django.db.models.signals import post_save from django.dispatch import receiver from .tasks import push_new_content @receiver(post_save) def post_save_handler(sender, instance, **kwargs): instance_type = ContentType.objects.get_for_model(instance.__class__) push_new_content.apply_async(countdown=1, kwargs={'instance_type_pk': instance_type.pk, 'instance_pk': instance.pk})
# -*- coding: utf-8 -*- from django.contrib.contenttypes.models import ContentType from django.db.models.signals import post_save from django.dispatch import receiver from .tasks import push_new_content @receiver(post_save) def post_save_handler(sender, instance, **kwargs): if ContentType.objects.exists(): instance_type = ContentType.objects.get_for_model(instance.__class__) push_new_content.apply_async(countdown=1, kwargs={'instance_type_pk': instance_type.pk, 'instance_pk': instance.pk})
Fix initial migration until ContentType is available
Fix initial migration until ContentType is available
Python
mit
mback2k/swampdragon-live,mback2k/swampdragon-live
06d98438f9535a0477cdc85acf4c001fa7657b26
qtpy/tests/test_qtopengl.py
qtpy/tests/test_qtopengl.py
import pytest from qtpy import PYSIDE2, PYSIDE6, PYQT5, PYQT6 def test_qtopengl(): """Test the qtpy.QtOpenGL namespace""" from qtpy import QtOpenGL assert QtOpenGL.QOpenGLBuffer is not None assert QtOpenGL.QOpenGLContext is not None assert QtOpenGL.QOpenGLContextGroup is not None assert QtOpenGL.QOpenGLDebugLogger is not None assert QtOpenGL.QOpenGLDebugMessage is not None assert QtOpenGL.QOpenGLFramebufferObject is not None assert QtOpenGL.QOpenGLFramebufferObjectFormat is not None assert QtOpenGL.QOpenGLPixelTransferOptions is not None assert QtOpenGL.QOpenGLShader is not None assert QtOpenGL.QOpenGLShaderProgram is not None assert QtOpenGL.QOpenGLTexture is not None assert QtOpenGL.QOpenGLTextureBlitter is not None # These are not present on some architectures # assert QtOpenGL.QOpenGLTimeMonitor is not None # assert QtOpenGL.QOpenGLTimerQuery is not None assert QtOpenGL.QOpenGLVersionProfile is not None assert QtOpenGL.QOpenGLVertexArrayObject is not None assert QtOpenGL.QOpenGLWindow is not None
import pytest from qtpy import PYSIDE2, PYSIDE6, PYQT5, PYQT6 def test_qtopengl(): """Test the qtpy.QtOpenGL namespace""" from qtpy import QtOpenGL assert QtOpenGL.QOpenGLBuffer is not None assert QtOpenGL.QOpenGLContext is not None assert QtOpenGL.QOpenGLContextGroup is not None assert QtOpenGL.QOpenGLDebugLogger is not None assert QtOpenGL.QOpenGLDebugMessage is not None assert QtOpenGL.QOpenGLFramebufferObject is not None assert QtOpenGL.QOpenGLFramebufferObjectFormat is not None assert QtOpenGL.QOpenGLPixelTransferOptions is not None assert QtOpenGL.QOpenGLShader is not None assert QtOpenGL.QOpenGLShaderProgram is not None assert QtOpenGL.QOpenGLTexture is not None assert QtOpenGL.QOpenGLTextureBlitter is not None assert QtOpenGL.QOpenGLVersionProfile is not None assert QtOpenGL.QOpenGLVertexArrayObject is not None assert QtOpenGL.QOpenGLWindow is not None # We do not test for QOpenGLTimeMonitor or QOpenGLTimerQuery as # they are not present on some architectures
Remove commented code and replace by improved comment
Remove commented code and replace by improved comment
Python
mit
spyder-ide/qtpy
1c2b6c0daea1d04985ef6ddff35527ba207ec191
qual/tests/test_calendar.py
qual/tests/test_calendar.py
import unittest from datetime import date import qual class TestProlepticGregorianCalendar(unittest.TestCase): def setUp(self): self.calendar = qual.ProlepticGregorianCalendar() def check_valid_date(self, year, month, day): d = self.calendar.date(year, month, day) self.assertIsNotNone(d) def test_leap_year_from_before_1582(self): """Pope Gregory introduced the calendar in 1582""" self.check_valid_date(1200, 2, 29)
import unittest from datetime import date import qual class TestProlepticGregorianCalendar(unittest.TestCase): def setUp(self): self.calendar = qual.ProlepticGregorianCalendar() def check_valid_date(self, year, month, day): d = self.calendar.date(year, month, day) self.assertIsNotNone(d) def check_invalid_date(self, year, month, day): self.assertRaises(Exception, lambda : self.calendar(year, month, day)) def test_leap_year_from_before_1582(self): """Pope Gregory introduced the calendar in 1582""" self.check_valid_date(1200, 2, 29) def test_Julian_leap_day_is_not_a_valid_date(self): """This day /was/ a leap day contemporaneously, but is not a valid date of the Gregorian calendar.""" self.check_invalid_date(1300, 2, 29)
Check that a certain date is invalid.
Check that a certain date is invalid. This distinguishes correctly between the proleptic Gregorian calendar, and the historical or astronomical calendars, where this date would be valid.
Python
apache-2.0
jwg4/calexicon,jwg4/qual
e50655479c0d3a96edd4005f834541889839fca3
binary_to_text.py
binary_to_text.py
#! /usr/bin/env python import Gen.caffe_pb2 as pb2 import google.protobuf.text_format as pb2_text import sys def binary_to_text(binary_file, text_file): msg = pb2.NetParameter() with open(binary_file) as f: msg.ParseFromString(f.read()) with open(text_file, "w") as f: f.write(pb2_text.MessageToString(msg)) if __name__ == "__main__": binary_file = sys.argv[1] text_file = sys.argv[2] binary_to_text(binary_file, text_file)
#! /usr/bin/env python import Gen.caffe_pb2 as pb2 import google.protobuf.text_format as pb2_text import sys class ParameterTypeException(Exception): pass def binary_to_text(binary_file, text_file, parameter_type): if (parameter_type == "Net"): msg = pb2.NetParameter() elif (parameter_type == "Solver"): msg = pb2.SolverParameter() else: raise ParameterTypeException("Unexpected Parameter Type: " + parameter_type) with open(binary_file) as f: msg.ParseFromString(f.read()) with open(text_file, "w") as f: f.write(pb2_text.MessageToString(msg)) if __name__ == "__main__": binary_file = sys.argv[1] text_file = sys.argv[2] try: parameter_type = sys.argv[3] except IndexError: parameter_type = "Net" binary_to_text(binary_file, text_file, parameter_type)
Add option to process SolverParameters.
Add option to process SolverParameters.
Python
bsd-3-clause
BeautifulDestinations/dnngraph,BeautifulDestinations/dnngraph
86ac48a3dcb71a4e504dcf04e30a00262d168e5f
test/parseJaguar.py
test/parseJaguar.py
import os from cclib.parser import Jaguar os.chdir(os.path.join("..","data","Jaguar","basicJaguar")) os.chdir("eg01") for file in ["dvb_gopt.out"]: t = Jaguar(file) t.parse() print t.moenergies[0,:] print t.homos[0] print t.moenergies[0,t.homos[0]]
import os from cclib.parser import Jaguar os.chdir(os.path.join("..","data","Jaguar","basicJaguar")) files = [ ["eg01","dvb_gopt.out"], ["eg02","dvb_sp.out"], ["eg03","dvb_ir.out"], ["eg06","dvb_un_sp.out"] ] for f in files: t = Jaguar(os.path.join(f[0],f[1])) t.parse() if f[0]!="eg03": print t.scfvalues
Test the parsing of all of the uploaded Jaguar files
Test the parsing of all of the uploaded Jaguar files
Python
bsd-3-clause
jchodera/cclib,ben-albrecht/cclib,Schamnad/cclib,cclib/cclib,berquist/cclib,jchodera/cclib,berquist/cclib,gaursagar/cclib,ben-albrecht/cclib,Clyde-fare/cclib,andersx/cclib,berquist/cclib,andersx/cclib,gaursagar/cclib,ATenderholt/cclib,ghutchis/cclib,Schamnad/cclib,cclib/cclib,langner/cclib,cclib/cclib,Clyde-fare/cclib,langner/cclib,ATenderholt/cclib,ghutchis/cclib,langner/cclib
651663d2af72f46e7952d2835126f1512741f635
UserInput.py
UserInput.py
"""Like the raw_input built-in, but with bells and whistles.""" import getpass def user_input(field, default='', choices=None, password=False, empty_ok=False, accept=False): """Prompt user for input until a value is retrieved or default is accepted. Return the input. Arguments: field Description of the input being prompted for. default Default value for the input accepted with a Return-key. password Whether the user input should not be echoed to screen. empty_ok Whether it's okay to accept an empty input. accept Whether to skip getting actual user input and just accept the default value, unless prevented by the combination of arguments "empty_ok" and "default". That is, unless "default" is an empty string and "empty_ok" is False. """ result = '' while not result: prompt = field if default: prompt += ' [{:}]'.format(default) prompt += ': ' if accept and not (not default and not empty_ok): print(prompt) result = '{:}'.format(default) else: if password: result = getpass.getpass(prompt) else: result = raw_input(prompt) result = result.strip() if not result: result = default if choices and result not in choices: print('Must be one of {:}'.format(choices)) result = '' if empty_ok: break return result
"""Like the input built-in, but with bells and whistles.""" import getpass # Use raw_input for Python 2.x try: input = raw_input except NameError: pass def user_input(field, default='', choices=None, password=False, empty_ok=False, accept=False): """Prompt user for input until a value is retrieved or default is accepted. Return the input. Arguments: field Description of the input being prompted for. default Default value for the input accepted with a Return-key. password Whether the user input should not be echoed to screen. empty_ok Whether it's okay to accept an empty input. accept Whether to skip getting actual user input and just accept the default value, unless prevented by the combination of arguments "empty_ok" and "default". That is, unless "default" is an empty string and "empty_ok" is False. """ result = '' while not result: prompt = field if default: prompt += ' [{0}]'.format(default) prompt += ': ' if accept and not (not default and not empty_ok): print(prompt) result = '{0}'.format(default) else: if password: result = getpass.getpass(prompt) else: result = input(prompt) result = result.strip() if not result: result = default if choices and result not in choices: print('Must be one of {0}'.format(choices)) result = '' if empty_ok: break return result
Fix for Python 2.6 and Python 3.
Fix for Python 2.6 and Python 3.
Python
mit
vmlaker/coils
b503881ae6229bddd7ef65d95f9c38d6d0ad5ec2
chain/functions/relu.py
chain/functions/relu.py
import numpy import pycuda.gpuarray as gpuarray from chain import Function class ReLU(Function): """Rectified Linear Unit.""" # TODO(beam2d): Implement in-place version. def forward_cpu(self, x): return numpy.maximum(0, x[0]), def forward_gpu(self, x): return gpuarray.maximum(0, x[0]), def backward_cpu(self, x, gy): return gy[0] * (x[0] > 0), def backward_gpu(self, x, gy): # TODO(beam2d): Unify kernel return gy[0] * (x[0] > 0), def relu(x): return ReLU()(x)
import ctypes import libcudnn import numpy import pycuda.gpuarray as gpuarray from chain import Function, cudnn _mode = libcudnn.cudnnActivationMode['CUDNN_ACTIVATION_RELU'] class ReLU(Function): """Rectified Linear Unit.""" # TODO(beam2d): Implement in-place version. def forward_cpu(self, x): return numpy.maximum(0, x[0]), def forward_gpu(self, x): handle = cudnn.get_default_handle() desc = cudnn.get_tensor_desc(x[0], 1, 1) y = gpuarray.empty_like(x[0]) libcudnn.cudnnActivationForward( handle, _mode, 1, desc, cudnn.get_ptr(x[0]), 0, desc, cudnn.get_ptr(y)) return y, def backward_cpu(self, x, gy): return gy[0] * (x[0] > 0), def backward_gpu(self, x, gy): y, gy = self.outputs[0].data, gy[0] handle = cudnn.get_default_handle() desc = cudnn.get_tensor_desc(y, 1, 1) gx = gpuarray.empty_like(y) libcudnn.cudnnActivationBackward( handle, _mode, 1, desc, cudnn.get_ptr(y), desc, cudnn.get_ptr(gy), desc, cudnn.get_ptr(x[0]), 0, desc, cudnn.get_ptr(gx)) return gx, def relu(x): return ReLU()(x)
Use CuDNN implementation for ReLU on GPU
Use CuDNN implementation for ReLU on GPU
Python
mit
jnishi/chainer,chainer/chainer,masia02/chainer,truongdq/chainer,umitanuki/chainer,cemoody/chainer,ronekko/chainer,ttakamura/chainer,okuta/chainer,laysakura/chainer,kikusu/chainer,keisuke-umezawa/chainer,hvy/chainer,wavelets/chainer,hvy/chainer,niboshi/chainer,ikasumi/chainer,kashif/chainer,wkentaro/chainer,ysekky/chainer,minhpqn/chainer,chainer/chainer,wkentaro/chainer,AlpacaDB/chainer,tkerola/chainer,niboshi/chainer,ttakamura/chainer,kuwa32/chainer,t-abe/chainer,chainer/chainer,kiyukuta/chainer,t-abe/chainer,keisuke-umezawa/chainer,Kaisuke5/chainer,AlpacaDB/chainer,benob/chainer,benob/chainer,jnishi/chainer,nushio3/chainer,chainer/chainer,sou81821/chainer,truongdq/chainer,okuta/chainer,kikusu/chainer,cupy/cupy,bayerj/chainer,anaruse/chainer,tereka114/chainer,sinhrks/chainer,ktnyt/chainer,okuta/chainer,pfnet/chainer,hvy/chainer,elviswf/chainer,niboshi/chainer,wkentaro/chainer,rezoo/chainer,ytoyama/yans_chainer_hackathon,cupy/cupy,cupy/cupy,tscohen/chainer,woodshop/chainer,jfsantos/chainer,ktnyt/chainer,wkentaro/chainer,yanweifu/chainer,tigerneil/chainer,hidenori-t/chainer,muupan/chainer,aonotas/chainer,delta2323/chainer,1986ks/chainer,cupy/cupy,ktnyt/chainer,ktnyt/chainer,jnishi/chainer,woodshop/complex-chainer,jnishi/chainer,muupan/chainer,niboshi/chainer,nushio3/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,hvy/chainer,sinhrks/chainer,okuta/chainer
58fc39ae95522ce152b4ff137071f74c5490e14e
chatterbot/constants.py
chatterbot/constants.py
""" ChatterBot constants """ ''' The maximum length of characters that the text of a statement can contain. This should be enforced on a per-model basis by the data model for each storage adapter. ''' STATEMENT_TEXT_MAX_LENGTH = 400 ''' The maximum length of characters that the text label of a conversation can contain. The number 32 was chosen because that is the length of the string representation of a UUID4 with no hyphens. ''' CONVERSATION_LABEL_MAX_LENGTH = 32 ''' The maximum length of text that can be stored in the persona field of the statement model. ''' PERSONA_MAX_LENGTH = 50 # The maximum length of characters that the name of a tag can contain TAG_NAME_MAX_LENGTH = 50 DEFAULT_DJANGO_APP_NAME = 'django_chatterbot'
""" ChatterBot constants """ ''' The maximum length of characters that the text of a statement can contain. The number 255 is used because that is the maximum length of a char field in most databases. This value should be enforced on a per-model basis by the data model for each storage adapter. ''' STATEMENT_TEXT_MAX_LENGTH = 255 ''' The maximum length of characters that the text label of a conversation can contain. The number 32 was chosen because that is the length of the string representation of a UUID4 with no hyphens. ''' CONVERSATION_LABEL_MAX_LENGTH = 32 ''' The maximum length of text that can be stored in the persona field of the statement model. ''' PERSONA_MAX_LENGTH = 50 # The maximum length of characters that the name of a tag can contain TAG_NAME_MAX_LENGTH = 50 DEFAULT_DJANGO_APP_NAME = 'django_chatterbot'
Change statement text max-length to 255
Change statement text max-length to 255
Python
bsd-3-clause
vkosuri/ChatterBot,gunthercox/ChatterBot
27021bfa7062219a41ad29c40b97643ecf16f72b
doc/mkapidoc.py
doc/mkapidoc.py
#!/usr/bin/env python # Generates the *public* API documentation. # Remember to hide your private parts, people! import os, re, sys project = 'Exscript' base_dir = os.path.join('..', 'src', project) doc_dir = 'api' # Create the documentation directory. if not os.path.exists(doc_dir): os.makedirs(doc_dir) # Generate the API documentation. os.system('epydoc ' + ' '.join(['--name', project, '--exclude Exscript.AccountManager', '--exclude Exscript.HostAction', '--exclude Exscript.Log', '--exclude Exscript.Logfile', '--exclude Exscript.QueueLogger', '--exclude Exscript.QueueListener', '--exclude Exscript.util.otp', '--exclude Exscript.interpreter', '--exclude Exscript.protocols.AbstractMethod', '--exclude Exscript.protocols.telnetlib', '--exclude Exscript.stdlib', '--exclude Exscript.workqueue', '--exclude Exscript.version', '--html', '--no-private', '--no-source', '--no-frames', '--inheritance=included', '-v', '-o %s' % doc_dir, base_dir]))
#!/usr/bin/env python # Generates the *public* API documentation. # Remember to hide your private parts, people! import os, re, sys project = 'Exscript' base_dir = os.path.join('..', 'src', project) doc_dir = 'api' # Create the documentation directory. if not os.path.exists(doc_dir): os.makedirs(doc_dir) # Generate the API documentation. os.system('epydoc ' + ' '.join(['--name', project, '--exclude Exscript.AbstractMethod', '--exclude Exscript.AccountManager', '--exclude Exscript.HostAction', '--exclude Exscript.Log', '--exclude Exscript.Logfile', '--exclude Exscript.QueueLogger', '--exclude Exscript.QueueListener', '--exclude Exscript.util.otp', '--exclude Exscript.interpreter', '--exclude Exscript.protocols.AbstractMethod', '--exclude Exscript.protocols.telnetlib', '--exclude Exscript.stdlib', '--exclude Exscript.workqueue', '--exclude Exscript.version', '--html', '--no-private', '--no-source', '--no-frames', '--inheritance=included', '-v', '-o %s' % doc_dir, base_dir]))
Hide AbstractMethod class from the docs.
Hide AbstractMethod class from the docs.
Python
mit
knipknap/exscript,maximumG/exscript,knipknap/exscript,maximumG/exscript
208760340d3314f666d7e6437817cc96e0e16194
organizer/urls/tag.py
organizer/urls/tag.py
from django.conf.urls import url from ..views import ( TagCreate, TagDelete, TagDetail, TagList, TagUpdate) urlpatterns = [ url(r'^$', TagList.as_view(), name='organizer_tag_list'), url(r'^create/$', TagCreate.as_view(), name='organizer_tag_create'), url(r'^(?P<slug>[\w\-]+)/$', TagDetail.as_view(), name='organizer_tag_detail'), url(r'^(?P<slug>[\w-]+)/delete/$', TagDelete.as_view(), name='organizer_tag_delete'), url(r'^(?P<slug>[\w\-]+)/update/$', TagUpdate.as_view(), name='organizer_tag_update'), ]
from django.conf.urls import url from django.contrib.auth.decorators import \ login_required from ..views import ( TagCreate, TagDelete, TagDetail, TagList, TagUpdate) urlpatterns = [ url(r'^$', TagList.as_view(), name='organizer_tag_list'), url(r'^create/$', login_required( TagCreate.as_view()), name='organizer_tag_create'), url(r'^(?P<slug>[\w\-]+)/$', TagDetail.as_view(), name='organizer_tag_detail'), url(r'^(?P<slug>[\w-]+)/delete/$', TagDelete.as_view(), name='organizer_tag_delete'), url(r'^(?P<slug>[\w\-]+)/update/$', TagUpdate.as_view(), name='organizer_tag_update'), ]
Use login_required decorator in URL pattern.
Ch20: Use login_required decorator in URL pattern.
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
1f253c5bdf90055ff2d00a3b8d18c152c3b7031f
versions.py
versions.py
#!/usr/bin/env python import os import warnings warnings.filterwarnings('ignore', category=DeprecationWarning) def test_for_version(filename): stdin, stdout = os.popen4('%s -V' % filename, 'r') response = stdout.read() if response.find('command not found') > 0: return False return '.'.join(response.strip().split(' ')[1].split('.')[:-1]) versions = ['python', 'python2.4', 'python2.5', 'python2.6'] valid = {} for filename in versions: version = test_for_version(filename) if version and version not in valid: valid[version] = filename # Prefer the latest version of python output = [] if '2.6' in valid: output.append(valid['2.6']) for version in valid.keys(): if valid[version] not in output: output.append(valid[version]) print ' '.join(output)
#!/usr/bin/env python import os import warnings warnings.filterwarnings('ignore', category=DeprecationWarning) def test_for_version(filename): stdin, stdout = os.popen4('%s -V' % filename, 'r') response = stdout.read() if response.find('command not found') > 0: return False return '.'.join(response.strip().split(' ')[1].split('.')[:-1]) versions = ['python', 'python2.4', 'python2.5', 'python2.6', 'python2.7'] valid = {} for filename in versions: version = test_for_version(filename) if version and version not in valid: valid[version] = filename # Prefer 2.6 major version of python since that's my main development env output = [] if '2.6' in valid: output.append(valid['2.6']) for version in valid.keys(): if valid[version] not in output: output.append(valid[version]) print ' '.join(output)
Check for Python 2.7 as well
Check for Python 2.7 as well
Python
bsd-3-clause
hugoxia/pika,vrtsystems/pika,vitaly-krugl/pika,fkarb/pika-python3,Tarsbot/pika,Zephor5/pika,zixiliuyue/pika,renshawbay/pika-python3,reddec/pika,jstnlef/pika,skftn/pika,pika/pika,shinji-s/pika,knowsis/pika,benjamin9999/pika
539bd8a9df362f285bda375732ec71b3df1bcaae
orbeon_xml_api/tests/test_runner.py
orbeon_xml_api/tests/test_runner.py
from .test_common import CommonTestCase from ..runner import Runner, RunnerForm from ..utils import xml_from_file class RunnerTestCase(CommonTestCase): def setUp(self): super(RunnerTestCase, self).setUp() self.runner_xml = xml_from_file('tests/data', 'test_controls_runner.xml') self.builder_xml = xml_from_file('tests/data', 'test_controls_builder.xml') self.runner = Runner(self.runner_xml, None, self.builder_xml) # TODO def _test_constructor(self): self.assertRaisesRegex( Runner(self.runner_xml) ) self.assertRaisesRegex( Runner(self.runner_xml, self.builder_xml) ) self.assertRaisesRegex( Runner(self.runner_xml, self.builder) ) self.assertRaisesRegex( Runner(self.runner_xml, self.builder_xml, self.builder) ) # Ok tests runner = Runner(self.runner_xml, None, self.builder_xml) self.assertIsInstance(runner, Runner) runner = Runner(self.runner_xml, self.builder) self.assertIsInstance(runner, Runner) self.assertIsInstance(self.runner.form, RunnerForm)
from xmlunittest import XmlTestCase from .test_common import CommonTestCase from ..runner import Runner, RunnerForm from ..utils import xml_from_file class RunnerTestCase(CommonTestCase, XmlTestCase): def setUp(self): super(RunnerTestCase, self).setUp() self.runner_xml = xml_from_file('tests/data', 'test_controls_runner_no-image-attachments-iteration.xml') self.builder_xml = xml_from_file('tests/data', 'test_controls_builder_no-image-attachments-iteration.xml') self.runner = Runner(self.runner_xml, None, self.builder_xml) def test_constructor_validation_ok(self): runner = Runner(self.runner_xml, None, self.builder_xml) self.assertIsInstance(runner, Runner) runner = Runner(self.runner_xml, self.builder) self.assertIsInstance(runner, Runner) self.assertIsInstance(self.runner.form, RunnerForm) def test_constructor_validation_fails(self): with self.assertRaisesRegexp(Exception, "Provide either the argument: builder or builder_xml."): Runner(self.runner_xml) with self.assertRaisesRegexp(Exception, "Constructor accepts either builder or builder_xml."): Runner(self.runner_xml, self.builder, self.builder_xml)
Add Runner unit-tests: constructor with validation.
Add Runner unit-tests: constructor with validation.
Python
mit
bobslee/orbeon-xml-api
cde7dbd5a1bb83e85e15559120189d108f6f66aa
tortilla/utils.py
tortilla/utils.py
# -*- coding: utf-8 -*- import six from formats import FormatBank, discover_json, discover_yaml formats = FormatBank() discover_json(formats, content_type='application/json') discover_yaml(formats, content_type='application/x-yaml') def run_from_ipython(): return getattr(__builtins__, "__IPYTHON__", False) class Bunch(dict): def __init__(self, kwargs=None): if kwargs is None: kwargs = {} for key, value in six.iteritems(kwargs): kwargs[key] = bunchify(value) super().__init__(kwargs) self.__dict__ = self def bunchify(obj): if isinstance(obj, (list, tuple)): return [bunchify(item) for item in obj] if isinstance(obj, dict): return Bunch(obj) return obj
# -*- coding: utf-8 -*- import six from formats import FormatBank, discover_json, discover_yaml formats = FormatBank() discover_json(formats, content_type='application/json') discover_yaml(formats, content_type='application/x-yaml') def run_from_ipython(): return getattr(__builtins__, "__IPYTHON__", False) class Bunch(dict): def __init__(self, kwargs=None): if kwargs is None: kwargs = {} for key, value in six.iteritems(kwargs): kwargs[key] = bunchify(value) super(Bunch, self).__init__(kwargs) self.__dict__ = self def bunchify(obj): if isinstance(obj, (list, tuple)): return [bunchify(item) for item in obj] if isinstance(obj, dict): return Bunch(obj) return obj
Fix super() call for python <= 3.2
Fix super() call for python <= 3.2
Python
mit
redodo/tortilla
0de0818e5a0c52dde8c841d8e8254e2f4a3f9633
app/sense.py
app/sense.py
#!/usr/bin/env python3 from Sensor import SenseController from KeyDispatcher import KeyDispatcher from Display import Display from DataLogger import SQLiteLogger import time DEVICE = "PiSense" DELAY = 0.0 class Handler: def __init__(self, display, logger, sensor): self.display = display self.logger = logger self.sensor = sensor self.logger.log(DEVICE, "running", 1) def read(self): values = {} for reading in self.sensor.get_data(): values[reading[1]] = reading[2] self.logger.log(DEVICE, reading[1], reading[2], reading[0]) display.show_properties(values, self.sensor.get_properties()) return True def quit(self): self.logger.log(DEVICE, "running", 0) return False with SenseController() as sensor, KeyDispatcher() as dispatcher, SQLiteLogger() as logger: # setup display display = Display("PiSense") # setup key handlers handler = Handler(display, logger, sensor) dispatcher.add("q", handler, "quit") # start processing key presses while True: if dispatcher.can_process_key(): if not dispatcher.process_key(): break else: handler.read() time.sleep(DELAY)
#!/usr/bin/env python3 from Sensor import SenseController from KeyDispatcher import KeyDispatcher from Display import Display from DataLogger import SQLiteLogger import time DEVICE = "PiSense" DELAY = 0.25 class Handler: def __init__(self, display, logger, sensor): self.display = display self.logger = logger self.sensor = sensor self.recording = False self.logger.log(DEVICE, "running", 1) def read(self): values = {} if self.recording: for reading in self.sensor.get_data(): values[reading[1]] = reading[2] self.logger.log(DEVICE, reading[1], reading[2], reading[0]) display.show_properties(values, self.sensor.get_properties()) else: values["recording"] = False display.show_properties(values) return True def record(self): self.recording = not self.recording if self.recording: self.logger.log(DEVICE, "recording", 1) else: self.logger.log(DEVICE, "recording", 0) return True def quit(self): self.logger.log(DEVICE, "running", 0) return False with SenseController() as sensor, KeyDispatcher() as dispatcher, SQLiteLogger() as logger: # setup display display = Display("PiSense", "[r]ecord [q]uit") # setup key handlers handler = Handler(display, logger, sensor) dispatcher.add("r", handler, "record") dispatcher.add("q", handler, "quit") # start processing key presses while True: if dispatcher.can_process_key(): if not dispatcher.process_key(): break else: handler.read() time.sleep(DELAY)
Allow PiSense readings to be toggled on/off
Allow PiSense readings to be toggled on/off
Python
mit
gizmo-cda/g2x,thelonious/g2x,thelonious/g2x,gizmo-cda/g2x,gizmo-cda/g2x,gizmo-cda/g2x
990f4f3ec850525ac4fcb78b33031b60dbe25ce4
versebot/verse.py
versebot/verse.py
""" VerseBot for reddit By Matthieu Grieger verse.py Copyright (c) 2015 Matthieu Grieger (MIT License) """ class Verse: """ Class that holds the properties and methods of a Verse object. """ def __init__(self, book, chapter, verse, translation): """ Initializes a Verse object with book, chapter, verse (if exists), and translation (if exists). """ self.book = book self.chapter = chapter self.verse = verse self.translation = translation
""" VerseBot for reddit By Matthieu Grieger verse.py Copyright (c) 2015 Matthieu Grieger (MIT License) """ class Verse: """ Class that holds the properties and methods of a Verse object. """ def __init__(self, book, chapter, verse, translation): """ Initializes a Verse object with book, chapter, verse (if exists), and translation (if exists). """ self.book = book.lower().replace(" ", "") self.chapter = int(chapter.replace(" ", "")) self.verse = verse.replace(" ", "") self.translation = translation.replace(" ", "")
Remove spaces and set to lowercase
Remove spaces and set to lowercase
Python
mit
Matthew-Arnold/slack-versebot,Matthew-Arnold/slack-versebot
fd87d09b03be003dcd13d778c175f796c4fdf7d6
test_http2_server.py
test_http2_server.py
from echo_client import client def test_ok(): response = client('GET a_web_page.html HTTP/1.1').split('\r\n') first_line = response[0] assert first_line == 'HTTP/1.1 200 OK' def test_body(): response = client('GET sample.txt HTTP/1.1').split('\r\n') body = response[4] assert 'This is a very simple text file.' in body def test_directory(): response = client('GET / HTTP/1.1').split('\r\n') body = response[4] assert 'make_time.py' in body def test_404(): response = client('GET does/not/exist.html HTTP/1.1').split('\r\n') first_line = response[0] assert first_line == 'HTTP/1.1 404 Not Found'
from echo_client import client def test_ok(): response = client('GET a_web_page.html HTTP/1.1').split('\r\n') first_line = response[0] assert first_line == 'HTTP/1.1 200 OK' def test_body(): response = client('GET sample.txt HTTP/1.1').split('\r\n') body = response[4] assert 'This is a very simple text file.' in body def test_directory(): response = client('GET / HTTP/1.1').split('\r\n') body = response[4] assert "<a href='make_time.py'>make_time.py</a>" in body def test_404(): response = client('GET does/not/exist.html HTTP/1.1').split('\r\n') first_line = response[0] assert first_line == 'HTTP/1.1 404 Not Found'
Change directory test to look for link, rather than just file name
Change directory test to look for link, rather than just file name
Python
mit
jwarren116/network-tools,jwarren116/network-tools
e94f2cb6dd144cec7b10aecb29669e7ba2ef98b1
chatterbot/__init__.py
chatterbot/__init__.py
""" ChatterBot is a machine learning, conversational dialog engine. """ from .chatterbot import ChatBot __version__ = '0.6.0' __author__ = 'Gunther Cox' __email__ = '[email protected]' __url__ = 'https://github.com/gunthercox/ChatterBot' __all__ = ( 'ChatBot', )
""" ChatterBot is a machine learning, conversational dialog engine. """ from .chatterbot import ChatBot __version__ = '0.6.1' __author__ = 'Gunther Cox' __email__ = '[email protected]' __url__ = 'https://github.com/gunthercox/ChatterBot' __all__ = ( 'ChatBot', )
Update release version to 0.6.1
Update release version to 0.6.1
Python
bsd-3-clause
gunthercox/ChatterBot,vkosuri/ChatterBot
666d9c999ebf0cc388d8f045a04756424c2d9b62
gdemo/util.py
gdemo/util.py
"""Share utility functions.""" from urllib import parse def get_route_value(environ, name): value = environ['wsgiorg.routing_args'][1][name] value = parse.unquote(value) return value.replace('%2F', '/')
"""Share utility functions.""" try: from urllib import parse except ImportError: import urllib as parse def get_route_value(environ, name): value = environ['wsgiorg.routing_args'][1][name] value = parse.unquote(value) return value.replace('%2F', '/')
Make it work for Python 2
Make it work for Python 2 Gabbi is designed to work with both Python 2.7 and 3.4.
Python
apache-2.0
cdent/gabbi-demo,cdent/gabbi-demo
be3cfd7033097bbc073e05c232f702bbcbfbd4db
xgcm/__init__.py
xgcm/__init__.py
from mdsxray import open_mdsdataset from gridops import GCMDataset from regridding import regrid_vertical
from .mdsxray import open_mdsdataset from .gridops import GCMDataset from .regridding import regrid_vertical
Fix the imports for Python 3
Fix the imports for Python 3
Python
mit
rabernat/xmitgcm,xgcm/xmitgcm,sambarluc/xmitgcm,xgcm/xgcm,rabernat/xgcm
f60363b3d24d2f4af5ddb894cc1f6494b371b18e
mass_mailing_switzerland/wizards/mailchimp_export_update_wizard.py
mass_mailing_switzerland/wizards/mailchimp_export_update_wizard.py
############################################################################## # # Copyright (C) 2020 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <[email protected]> # # The licence is in the file __manifest__.py # ############################################################################## from odoo import api, models, fields, _ from odoo.exceptions import UserError class ExportMailchimpWizard(models.TransientModel): _inherit = "partner.export.mailchimp" @api.multi def get_mailing_contact_id(self, partner_id, force_create=False): # Avoid exporting opt_out partner if force_create: partner = self.env["res.partner"].browse(partner_id) if partner.opt_out: return False # Push the partner_id in mailing_contact creation return super( ExportMailchimpWizard, self.with_context(default_partner_id=partner_id) ).get_mailing_contact_id(partner_id, force_create)
############################################################################## # # Copyright (C) 2020 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <[email protected]> # # The licence is in the file __manifest__.py # ############################################################################## from odoo import api, models, fields, _ from odoo.exceptions import UserError class ExportMailchimpWizard(models.TransientModel): _inherit = "partner.export.mailchimp" @api.multi def get_mailing_contact_id(self, partner_id, force_create=False): # Avoid exporting opt_out partner if force_create and partner_id.opt_out: return False # Push the partner_id in mailing_contact creation return super( ExportMailchimpWizard, self.with_context(default_partner_id=partner_id) ).get_mailing_contact_id(partner_id, force_create)
FIX opt_out prevention for mailchimp export
FIX opt_out prevention for mailchimp export
Python
agpl-3.0
CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland
3ef1531f6934055a416cdddc694f6ca75694d649
voltron/common.py
voltron/common.py
import logging import logging.config LOG_CONFIG = { 'version': 1, 'formatters': { 'standard': {'format': 'voltron: [%(levelname)s] %(message)s'} }, 'handlers': { 'default': { 'class': 'logging.StreamHandler', 'formatter': 'standard' } }, 'loggers': { 'voltron': { 'handlers': ['default'], 'level': 'INFO', 'propogate': True, } } } VOLTRON_DIR = '~/.voltron/' VOLTRON_CONFIG = VOLTRON_DIR + 'config' def configure_logging(): logging.config.dictConfig(LOG_CONFIG) log = logging.getLogger('voltron') return log
import logging import logging.config LOG_CONFIG = { 'version': 1, 'formatters': { 'standard': {'format': 'voltron: [%(levelname)s] %(message)s'} }, 'handlers': { 'default': { 'class': 'logging.StreamHandler', 'formatter': 'standard' } }, 'loggers': { 'voltron': { 'handlers': ['default'], 'level': 'INFO', 'propogate': True, } } } VOLTRON_DIR = os.path.expanduser('~/.voltron/') VOLTRON_CONFIG = VOLTRON_DIR + 'config' def configure_logging(): logging.config.dictConfig(LOG_CONFIG) log = logging.getLogger('voltron') return log
Make use of expanduser() more sane
Make use of expanduser() more sane
Python
mit
snare/voltron,snare/voltron,snare/voltron,snare/voltron
22207247c286ad3c656c3f6b550d869cf92f6e92
fs/sshfs/__init__.py
fs/sshfs/__init__.py
from __future__ import absolute_import from __future__ import unicode_literals from .sshfs import SSHFS
from __future__ import absolute_import from __future__ import unicode_literals from .sshfs import SSHFS from ..opener import Opener, registry @registry.install class SSHOpener(Opener): protocols = ['ssh'] def open_fs(self, fs_url, parse_result, writeable, create, cwd): #from .sshfs import SSHFS ssh_host, _, dir_path = parse_result.resource.partition('/') ssh_host, _, ftp_port = ssh_host.partition(':') ssh_port = int(ftp_port) if ftp_port.isdigit() else 22 ssh_fs = SSHFS( ssh_host, port=ssh_port, user=parse_result.username, passwd=parse_result.password, ) return ssh_fs.opendir(dir_path) if dir_path else ssh_fs
Add fs Opener based on the builtin FTPFS opener
Add fs Opener based on the builtin FTPFS opener
Python
lgpl-2.1
althonos/fs.sshfs
d0bf235af3742a17c722488fe3679d5b73a0d945
thinc/neural/_classes/softmax.py
thinc/neural/_classes/softmax.py
from .affine import Affine from ... import describe from ...describe import Dimension, Synapses, Biases from ...check import has_shape from ... import check @describe.attributes( W=Synapses("Weights matrix", lambda obj: (obj.nO, obj.nI), lambda W, ops: None) ) class Softmax(Affine): name = 'softmax' @check.arg(1, has_shape(('nB', 'nI'))) def predict(self, input__BI): output__BO = self.ops.affine(self.W, self.b, input__BI) output__BO = self.ops.softmax(output__BO, inplace=False) return output__BO @check.arg(1, has_shape(('nB', 'nI'))) def begin_update(self, input__BI, drop=0.): output__BO = self.predict(input__BI) @check.arg(0, has_shape(('nB', 'nO'))) def finish_update(grad__BO, sgd=None): self.d_W += self.ops.batch_outer(grad__BO, input__BI) self.d_b += grad__BO.sum(axis=0) grad__BI = self.ops.dot(grad__BO, self.W) if sgd is not None: sgd(self._mem.weights, self._mem.gradient, key=self.id) return grad__BI return output__BO, finish_update
from .affine import Affine from ... import describe from ...describe import Dimension, Synapses, Biases from ...check import has_shape from ... import check @describe.attributes( W=Synapses("Weights matrix", lambda obj: (obj.nO, obj.nI), lambda W, ops: None) ) class Softmax(Affine): name = 'softmax' @check.arg(1, has_shape(('nB', 'nI'))) def predict(self, input__BI): output__BO = self.ops.affine(self.W, self.b, input__BI) output__BO = self.ops.softmax(output__BO, inplace=False) return output__BO @check.arg(1, has_shape(('nB', 'nI'))) def begin_update(self, input__BI, drop=0.): output__BO = self.predict(input__BI) @check.arg(0, has_shape(('nB', 'nO'))) def finish_update(grad__BO, sgd=None): self.d_W += self.ops.gemm(grad__BO, input__BI, trans1=True) self.d_b += grad__BO.sum(axis=0) grad__BI = self.ops.gemm(grad__BO, self.W) if sgd is not None: sgd(self._mem.weights, self._mem.gradient, key=self.id) return grad__BI return output__BO, finish_update
Fix gemm calls in Softmax
Fix gemm calls in Softmax
Python
mit
spacy-io/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc
246971d8dd7d6c5fdc480c55e4e79ffd7a840b9b
Cura/View/View.py
Cura/View/View.py
#Abstract for all views class View(object): def __init__(self): self._renderer = None
#Abstract for all views class View(object): def __init__(self): self._renderer = None def render(self, glcontext): pass
Add a render method to view that should be reimplemented
Add a render method to view that should be reimplemented
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
ca674b743b6d48593f45d999335ae893cf2a90d6
base/config/production.py
base/config/production.py
" Production settings must be here. " from .core import * from os import path as op SECRET_KEY = 'SecretKeyForSessionSigning' ADMINS = frozenset([MAIL_USERNAME]) # flask.ext.collect # ----------------- COLLECT_STATIC_ROOT = op.join(op.dirname(ROOTDIR), 'static') # auth.oauth # ---------- OAUTH_TWITTER = dict( # flask-base-template app consumer_key='ydcXz2pWyePfc3MX3nxJw', consumer_secret='Pt1t2PjzKu8vsX5ixbFKu5gNEAekYrbpJrlsQMIwquc' ) # dealer DEALER_PARAMS = dict( backends=('git', 'mercurial', 'simple', 'null') ) # pymode:lint_ignore=W0614,W404
" Production settings must be here. " from .core import * from os import path as op SECRET_KEY = 'SecretKeyForSessionSigning' ADMINS = frozenset([MAIL_USERNAME]) # flask.ext.collect # ----------------- COLLECT_STATIC_ROOT = op.join(op.dirname(ROOTDIR), 'static') # auth.oauth # ---------- OAUTH_TWITTER = dict( consumer_key='750sRyKzvdGPJjPd96yfgw', consumer_secret='UGcyjDCUOb1q44w1nUk8FA7aXxvwwj1BCbiFvYYI', ) OAUTH_FACEBOOK = dict( consumer_key='413457268707622', consumer_secret='48e9be9f4e8abccd3fb916a3f646dd3f', ) OAUTH_GITHUB = dict( consumer_key='8bdb217c5df1c20fe632', consumer_secret='a3aa972b2e66e3fac488b4544d55eda2aa2768b6', ) # dealer DEALER_PARAMS = dict( backends=('git', 'mercurial', 'simple', 'null') ) # pymode:lint_ignore=W0614,W404
Add github and facebook oauth credentials.
Add github and facebook oauth credentials.
Python
bsd-3-clause
klen/Flask-Foundation,klen/fquest,klen/tweetchi
ac50044c16e2302e7543923d562cca5ba715e311
web/impact/impact/v1/events/base_history_event.py
web/impact/impact/v1/events/base_history_event.py
from abc import ( ABCMeta, abstractmethod, ) from impact.v1.helpers import ( STRING_FIELD, ) class BaseHistoryEvent(object): __metaclass__ = ABCMeta CLASS_FIELDS = { "event_type": STRING_FIELD, "datetime": STRING_FIELD, "latest_datetime": STRING_FIELD, "description": STRING_FIELD, } def __init__(self): self.earliest = None self.latest = None @classmethod def all_fields(cls): result = {} for base_class in cls.__bases__: if hasattr(base_class, "all_fields"): result.update(base_class.all_fields()) if hasattr(cls, "CLASS_FIELDS"): result.update(cls.CLASS_FIELDS) return result @classmethod def event_type(cls): return cls.EVENT_TYPE @abstractmethod def calc_datetimes(self): pass # pragma: no cover def datetime(self): self._check_date_cache() return self.earliest def latest_datetime(self): self._check_date_cache() return self.latest def _check_date_cache(self): if not self.earliest and hasattr(self, "calc_datetimes"): self.calc_datetimes() def description(self): return None # pragma: no cover def serialize(self): result = {} for key in self.all_fields().keys(): value = getattr(self, key)() if value is not None: result[key] = value return result
from abc import ( ABCMeta, abstractmethod, ) from impact.v1.helpers import ( STRING_FIELD, ) class BaseHistoryEvent(object): __metaclass__ = ABCMeta CLASS_FIELDS = { "event_type": STRING_FIELD, "datetime": STRING_FIELD, "latest_datetime": STRING_FIELD, "description": STRING_FIELD, } def __init__(self): self.earliest = None self.latest = None @classmethod def all_fields(cls): result = {} for base_class in cls.__bases__: if hasattr(base_class, "all_fields"): result.update(base_class.all_fields()) if hasattr(cls, "CLASS_FIELDS"): result.update(cls.CLASS_FIELDS) return result @classmethod def event_type(cls): return cls.EVENT_TYPE @abstractmethod def calc_datetimes(self): pass # pragma: no cover def datetime(self): self._check_date_cache() return self.earliest def latest_datetime(self): self._check_date_cache() return self.latest def _check_date_cache(self): if not self.earliest and hasattr(self, "calc_datetimes"): self.calc_datetimes() def description(self): return None # pragma: no cover def serialize(self): result = {} for key in self.all_fields().keys(): value = getattr(self, key).__call__() if value is not None: result[key] = value return result
Switch from () to __call__()
[AC-4857] Switch from () to __call__()
Python
mit
masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api
6722e16aef43f9cfe03e7e76fc578582139721f6
vint/linting/env.py
vint/linting/env.py
import os import os.path import re import logging from pathlib import Path VIM_SCRIPT_FILE_NAME_PATTERNS = r'(?:[\._]g?vimrc|.*\.vim$)' def build_environment(cmdargs): return { 'cmdargs': cmdargs, 'home_path': _get_home_path(cmdargs), 'cwd': _get_cwd(cmdargs), 'file_paths': _get_file_paths(cmdargs) } def _get_cwd(cmdargs): return Path(os.getcwd()) def _get_home_path(cmdargs): return Path(os.path.expanduser('~')) def _get_file_paths(cmdargs): if 'files' not in cmdargs: return [] found_files = _collect_files([Path(path) for path in cmdargs['files']]) return found_files def _collect_files(paths): result = set() for path in paths: if path.is_dir(): dir_path = path result |= _collect_files(tuple(dir_path.iterdir())) elif _is_vim_script(path): file_path = path result.add(file_path) else: logging.debug('ignore not Vim script file: `{file_path}`'.format( file_path=str(path))) return result def _is_vim_script(path): file_name = path.name return bool(re.search(VIM_SCRIPT_FILE_NAME_PATTERNS, file_name))
import os import os.path from pathlib import Path from vint.linting.file_filter import find_vim_script def build_environment(cmdargs): return { 'cmdargs': cmdargs, 'home_path': _get_home_path(cmdargs), 'cwd': _get_cwd(cmdargs), 'file_paths': _get_file_paths(cmdargs) } def _get_cwd(cmdargs): return Path(os.getcwd()) def _get_home_path(cmdargs): return Path(os.path.expanduser('~')) def _get_file_paths(cmdargs): if 'files' not in cmdargs: return [] found_file_paths = find_vim_script(map(Path, cmdargs['files'])) return set(found_file_paths)
Split file collecting algorithm to FileFilter
Split file collecting algorithm to FileFilter
Python
mit
Kuniwak/vint,RianFuro/vint,RianFuro/vint,Kuniwak/vint
ba8e567592c96dacb697e067004dc71799e4e93f
ctypeslib/test/stdio.py
ctypeslib/test/stdio.py
import os from ctypeslib.dynamic_module import include from ctypes import * if os.name == "nt": _libc = CDLL("msvcrt") else: _libc = CDLL(None) include("""\ #include <stdio.h> #ifdef _MSC_VER # include <fcntl.h> #else # include <sys/fcntl.h> #endif """, persist=False)
import os from ctypeslib.dynamic_module import include from ctypes import * if os.name == "nt": _libc = CDLL("msvcrt") else: _libc = CDLL(None) _gen_basename = include("""\ #include <stdio.h> #ifdef _MSC_VER # include <fcntl.h> #else # include <sys/fcntl.h> #endif /* Silly comment */ """, persist=False)
Store the basename of the generated files, to allow the unittests to clean up in the tearDown method.
Store the basename of the generated files, to allow the unittests to clean up in the tearDown method.
Python
mit
sugarmanz/ctypeslib
1ff4dab34d4aa6935d4d1b54aa354882790b9b44
astroquery/astrometry_net/__init__.py
astroquery/astrometry_net/__init__.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ <Put Your Tool Name Here> ------------------------- :author: <your name> (<your email>) """ # Make the URL of the server, timeout and other items configurable # See <http://docs.astropy.org/en/latest/config/index.html#developer-usage> # for docs and examples on how to do this # Below is a common use case from astropy import config as _config class Conf(_config.ConfigNamespace): """ Configuration parameters for `astroquery.astrometry_net` """ api_key = _config.ConfigItem( '', "The Astrometry.net API key." ) conf = Conf() # Now import your public class # Should probably have the same name as your module from .core import AstrometryNet, AstrometryNetClass __all__ = ['AstrometryNet', 'AstrometryNetClass']
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ <Put Your Tool Name Here> ------------------------- :author: <your name> (<your email>) """ # Make the URL of the server, timeout and other items configurable # See <http://docs.astropy.org/en/latest/config/index.html#developer-usage> # for docs and examples on how to do this # Below is a common use case from astropy import config as _config class Conf(_config.ConfigNamespace): """ Configuration parameters for `astroquery.astrometry_net` """ api_key = _config.ConfigItem( '', "The Astrometry.net API key." ) server = _config.ConfigItem('http://nova.astrometry.net', 'Name of server') timeout = _config.ConfigItem(60, 'Default timeout for connecting to server') conf = Conf() # Now import your public class # Should probably have the same name as your module from .core import AstrometryNet, AstrometryNetClass __all__ = ['AstrometryNet', 'AstrometryNetClass']
Add config items for server, timeout
Add config items for server, timeout
Python
bsd-3-clause
imbasimba/astroquery,ceb8/astroquery,ceb8/astroquery,imbasimba/astroquery
89e3d4ae0a7be5baef6354324b2e7f8623564c94
examples/olfaction/data/gen_olf_input.py
examples/olfaction/data/gen_olf_input.py
#!/usr/bin/env python """ Generate sample olfactory model stimulus. """ import numpy as np import h5py osn_num = 1375 dt = 1e-4 # time step Ot = 2000 # number of data point during reset period Rt = 1000 # number of data point during odor delivery period Nt = 4*Ot + 3*Rt # number of data points in time t = np.arange(0, dt*Nt, dt) I = 0.5195 # amplitude of odorant concentration u_on = I*np.ones(Ot, dtype=np.float64) u_off = np.zeros(Ot, dtype=np.float64) u_reset = np.zeros(Rt, dtype=np.float64) u = np.concatenate((u_off, u_reset, u_on, u_reset, u_off, u_reset, u_on)) u_all = np.transpose(np.kron(np.ones((osn_num, 1)), u)) with h5py.File('olfactory_input.h5', 'w') as f: f.create_dataset('real', (Nt, osn_num), dtype=np.float64, data=u_all)
#!/usr/bin/env python """ Generate sample olfactory model stimulus. """ import numpy as np import h5py osn_num = 1375 dt = 1e-4 # time step Ot = 2000 # number of data point during reset period Rt = 1000 # number of data point during odor delivery period Nt = 4*Ot + 3*Rt # number of data points in time t = np.arange(0, dt*Nt, dt) I = 0.5195 # amplitude of odorant concentration u_on = I*np.ones(Ot, dtype=np.float64) u_off = np.zeros(Ot, dtype=np.float64) u_reset = np.zeros(Rt, dtype=np.float64) u = np.concatenate((u_off, u_reset, u_on, u_reset, u_off, u_reset, u_on)) u_all = np.transpose(np.kron(np.ones((osn_num, 1)), u)) with h5py.File('olfactory_input.h5', 'w') as f: f.create_dataset('array', (Nt, osn_num), dtype=np.float64, data=u_all)
Use 'array' rather than 'real' for data array name in olfactory stimulus generation script.
Use 'array' rather than 'real' for data array name in olfactory stimulus generation script.
Python
bsd-3-clause
cerrno/neurokernel
87753b0bff057b61879e2dbcc4dceba7aec95451
settings/const.py
settings/const.py
import urllib2 #Database settings database_connect = "dbname='ridprod'" kv1_database_connect = "dbname='kv1tmp'" iff_database_connect = "dbname='ifftmp'" pool_generation_enabled = True #NDOVLoket settings ndovloket_url = "data.ndovloket.nl" ndovloket_user = "voorwaarden" ndovloket_password = "geaccepteerd" auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(realm=ndovloket_url, uri=ndovloket_url, user=ndovloket_user, passwd=ndovloket_password) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener)
import urllib2 #Database settings database_connect = "dbname='ridprod'" kv1_database_connect = "dbname='kv1tmp'" iff_database_connect = "dbname='ifftmp'" pool_generation_enabled = False #NDOVLoket settings ndovloket_url = "data.ndovloket.nl" ndovloket_user = "voorwaarden" ndovloket_password = "geaccepteerd" auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(realm=ndovloket_url, uri=ndovloket_url, user=ndovloket_user, passwd=ndovloket_password) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener)
Disable pool generation by default
Disable pool generation by default
Python
bsd-2-clause
bliksemlabs/bliksemintegration,bliksemlabs/bliksemintegration
9aa17b90b8f3413f0621cc25a686774dd809dc84
frigg/projects/serializers.py
frigg/projects/serializers.py
from rest_framework import serializers from frigg.builds.serializers import BuildInlineSerializer from .models import Project class ProjectSerializer(serializers.ModelSerializer): builds = BuildInlineSerializer(read_only=True, many=True) class Meta: model = Project fields = ( 'id', 'owner', 'name', 'private', 'approved', 'should_clone_with_ssh', 'builds' )
from rest_framework import serializers from frigg.builds.serializers import BuildInlineSerializer from .models import Project class EnvironmentVariableSerializer(serializers.ModelSerializer): def to_representation(self, instance): representation = super().to_representation(instance) if instance.is_secret: representation.value = '[secret]' return representation class Meta: model = Project fields = ( 'id', 'key', 'is_secret', 'value', ) class ProjectSerializer(serializers.ModelSerializer): builds = BuildInlineSerializer(read_only=True, many=True) class Meta: model = Project fields = ( 'id', 'owner', 'name', 'private', 'approved', 'should_clone_with_ssh', 'builds' )
Add drf serializer for environment variables
feat: Add drf serializer for environment variables
Python
mit
frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq
85537b6bee3efdd1862726a7e68bd79f693ecd4f
tornado_menumaker/helper/Page.py
tornado_menumaker/helper/Page.py
#!/usr/bin/python # -*- encoding: utf-8 -*- """ """ import inspect from tornado.web import Application from .Route import Route from .Index import IndexRoute __author__ = 'Martin Martimeo <[email protected]>' __date__ = '16.06.13 - 23:46' class Page(Route): """ A Page """ def __init__(self, url: str=None, **kwargs): super().__init__(url=url, **kwargs) self._index = None def __call__(self, *args, **kwargs): if isinstance(args[0], Application): if self._index is not None: return self._index(*args, **kwargs) self.handler = self.cls(*args, **kwargs) return self.handler elif isinstance(args[0], type): self.cls = args[0] for n, route in inspect.getmembers(self.cls, Route.isroute): route.url = self._url + route.url route.cls = self.cls for n, method in inspect.getmembers(self.cls, IndexRoute.isindex): self._index = method return self raise Exception()
#!/usr/bin/python # -*- encoding: utf-8 -*- """ """ import inspect from tornado.web import Application from .Route import Route from .Index import IndexRoute __author__ = 'Martin Martimeo <[email protected]>' __date__ = '16.06.13 - 23:46' class Page(Route): """ A Page """ def __init__(self, url: str=None, **kwargs): super().__init__(url=url, **kwargs) self._index = None def __call__(self, *args, **kwargs): if isinstance(args[0], Application): if self._index is not None: return self._index(*args, **kwargs) self.handler = self.cls(*args, **kwargs) return self.handler elif isinstance(args[0], type): self.cls = args[0] for n, route in inspect.getmembers(self.cls, Route.isroute): route.url = self._url + route.url route.cls = self.cls for n, method in inspect.getmembers(self.cls, IndexRoute.isindex): self._index = method return self.cls raise Exception()
Make still class available when decorating class with @page
Make still class available when decorating class with @page
Python
agpl-3.0
tornado-utils/tornado-menumaker
4bcf35efcfc751a1c337fdcf50d23d9d06549717
demo/apps/catalogue/models.py
demo/apps/catalogue/models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore.models import Page class Category(Page): """ user oscars category as a wagtail Page. this works becuase they both use treebeard """ name = models.CharField( verbose_name=_('name'), max_length=255, help_text=_("Category name") ) from oscar.apps.catalogue.models import * # noqa
from django.db import models from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore.models import Page class Category(Page): """ The Oscars Category as a Wagtail Page This works because they both use Treebeard """ name = models.CharField( verbose_name=_('name'), max_length=255, help_text=_("Category name") ) from oscar.apps.catalogue.models import * # noqa
Fix typo in doc string
Fix typo in doc string
Python
mit
pgovers/oscar-wagtail-demo,pgovers/oscar-wagtail-demo
0a69133e44810dd0469555f62ec49eba120e6ecc
apps/storybase/utils.py
apps/storybase/utils.py
"""Shared utility functions""" from django.template.defaultfilters import slugify as django_slugify def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, converts spaces to hyphens, and truncates to 50 characters. """ slug = django_slugify(value) slug = slug[:50] return slug.rstrip('-')
"""Shared utility functions""" from django.conf import settings from django.template.defaultfilters import slugify as django_slugify from django.utils.translation import ugettext as _ def get_language_name(language_code): """Convert a language code into its full (localized) name""" languages = dict(settings.LANGUAGES) return _(languages[language_code]) def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, converts spaces to hyphens, and truncates to 50 characters. """ slug = django_slugify(value) slug = slug[:50] return slug.rstrip('-')
Add utility function to convert a language code to a its full name
Add utility function to convert a language code to a its full name
Python
mit
denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase
62b1c49c67c72c36d4177c657df49a4700586c06
djangoTemplate/urls.py
djangoTemplate/urls.py
"""djangoTemplate URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ """ from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url('', include('base.urls')), url('', include('social.apps.django_app.urls', namespace='social')), url(r'^admin/', admin.site.urls), url(r'^tosp_auth/', include('tosp_auth.urls')) ]
"""djangoTemplate URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ """ from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url('', include('base.urls')), url('', include('social_django.urls', namespace='social')), url(r'^admin/', admin.site.urls), url(r'^tosp_auth/', include('tosp_auth.urls')) ]
Change the url patters from python_social_auth to social_django
Change the url patters from python_social_auth to social_django
Python
mit
tosp/djangoTemplate,tosp/djangoTemplate
62f4c6b7d24176284054b13c4e1e9b6d631c7b42
basicTest.py
basicTest.py
import slither, pygame, time snakey = slither.Sprite() snakey.setCostumeByName("costume0") SoExcited = slither.Sprite() SoExcited.addCostume("SoExcited.png", "avatar") SoExcited.setCostumeByNumber(0) SoExcited.goTo(300, 300) SoExcited.setScaleTo(0.33) slither.slitherStage.setColor(40, 222, 40) screen = slither.setup() # Begin slither continueLoop = True while continueLoop: slither.blit(screen) # Display snakey.changeXBy(1) SoExcited.changeDirectionBy(1) # Handle quitting for event in pygame.event.get(): if event.type == pygame.QUIT: continueLoop = False time.sleep(0.01)
import slither, pygame, time snakey = slither.Sprite() snakey.setCostumeByName("costume0") SoExcited = slither.Sprite() SoExcited.addCostume("SoExcited.png", "avatar") SoExcited.setCostumeByNumber(0) SoExcited.goTo(300, 300) SoExcited.setScaleTo(0.33) slither.slitherStage.setColor(40, 222, 40) screen = slither.setup() # Begin slither def run_a_frame(): snakey.changeXBy(1) SoExcited.changeDirectionBy(1) slither.runMainLoop(run_a_frame)
Update basic test Now uses the new format by @BookOwl.
Update basic test Now uses the new format by @BookOwl.
Python
mit
PySlither/Slither,PySlither/Slither
385f190d782c7d2edbba8b425db2418e6891ea86
framework/mongo/__init__.py
framework/mongo/__init__.py
# -*- coding: utf-8 -*- from flask import request from modularodm.storedobject import StoredObject as GenericStoredObject from modularodm.ext.concurrency import with_proxies, proxied_members from bson import ObjectId from .handlers import client, database, set_up_storage from api.base.api_globals import api_globals class DummyRequest(object): pass dummy_request = DummyRequest() def get_cache_key(): """ Fetch a request key from either a Django or Flask request. Fall back on a process-global dummy object if we are not in either type of request """ # TODO: This is ugly use of exceptions; is there a better way to track whether in a given type of request? try: return request._get_current_object() except RuntimeError: # Not in a flask request context if hasattr(api_globals, 'request') and api_globals.request is not None: return api_globals.request else: # Not in a Django request return dummy_request @with_proxies(proxied_members, get_cache_key) class StoredObject(GenericStoredObject): pass __all__ = [ 'StoredObject', 'ObjectId', 'client', 'database', 'set_up_storage', ]
# -*- coding: utf-8 -*- from flask import request from modularodm.storedobject import StoredObject as GenericStoredObject from modularodm.ext.concurrency import with_proxies, proxied_members from bson import ObjectId from .handlers import client, database, set_up_storage from api.base.api_globals import api_globals class DummyRequest(object): pass dummy_request = DummyRequest() def get_cache_key(): """ Fetch a request key from either a Django or Flask request. Fall back on a process-global dummy object if we are not in either type of request """ # TODO: This is ugly use of exceptions; is there a better way to track whether in a given type of request? try: return request._get_current_object() except RuntimeError: # Not in a flask request context if getattr(api_globals, 'request', None) is not None: return api_globals.request else: # Not in a Django request return dummy_request @with_proxies(proxied_members, get_cache_key) class StoredObject(GenericStoredObject): pass __all__ = [ 'StoredObject', 'ObjectId', 'client', 'database', 'set_up_storage', ]
Consolidate hasattr + getter to single statement with default value.
Consolidate hasattr + getter to single statement with default value.
Python
apache-2.0
kch8qx/osf.io,aaxelb/osf.io,chrisseto/osf.io,baylee-d/osf.io,billyhunt/osf.io,acshi/osf.io,SSJohns/osf.io,kwierman/osf.io,emetsger/osf.io,icereval/osf.io,DanielSBrown/osf.io,mattclark/osf.io,njantrania/osf.io,jmcarp/osf.io,HalcyonChimera/osf.io,emetsger/osf.io,Nesiehr/osf.io,bdyetton/prettychart,doublebits/osf.io,lyndsysimon/osf.io,icereval/osf.io,cwisecarver/osf.io,caseyrollins/osf.io,jolene-esposito/osf.io,GageGaskins/osf.io,haoyuchen1992/osf.io,cosenal/osf.io,HarryRybacki/osf.io,samanehsan/osf.io,felliott/osf.io,adlius/osf.io,brianjgeiger/osf.io,mluo613/osf.io,mluke93/osf.io,cwisecarver/osf.io,acshi/osf.io,acshi/osf.io,ckc6cz/osf.io,jolene-esposito/osf.io,kch8qx/osf.io,hmoco/osf.io,TomBaxter/osf.io,DanielSBrown/osf.io,cslzchen/osf.io,mluo613/osf.io,MerlinZhang/osf.io,jmcarp/osf.io,mfraezz/osf.io,Ghalko/osf.io,binoculars/osf.io,jnayak1/osf.io,hmoco/osf.io,amyshi188/osf.io,baylee-d/osf.io,mattclark/osf.io,acshi/osf.io,billyhunt/osf.io,ZobairAlijan/osf.io,sbt9uc/osf.io,HarryRybacki/osf.io,laurenrevere/osf.io,RomanZWang/osf.io,crcresearch/osf.io,dplorimer/osf,Ghalko/osf.io,Ghalko/osf.io,Ghalko/osf.io,sloria/osf.io,lyndsysimon/osf.io,samanehsan/osf.io,wearpants/osf.io,kch8qx/osf.io,ZobairAlijan/osf.io,brianjgeiger/osf.io,bdyetton/prettychart,jmcarp/osf.io,DanielSBrown/osf.io,lyndsysimon/osf.io,mluo613/osf.io,caseyrygt/osf.io,zamattiac/osf.io,brandonPurvis/osf.io,asanfilippo7/osf.io,haoyuchen1992/osf.io,TomHeatwole/osf.io,cosenal/osf.io,sbt9uc/osf.io,Johnetordoff/osf.io,brianjgeiger/osf.io,kwierman/osf.io,reinaH/osf.io,cldershem/osf.io,wearpants/osf.io,HarryRybacki/osf.io,jolene-esposito/osf.io,samchrisinger/osf.io,Nesiehr/osf.io,cldershem/osf.io,adlius/osf.io,RomanZWang/osf.io,billyhunt/osf.io,ticklemepierce/osf.io,njantrania/osf.io,hmoco/osf.io,chrisseto/osf.io,CenterForOpenScience/osf.io,laurenrevere/osf.io,jnayak1/osf.io,emetsger/osf.io,saradbowman/osf.io,petermalcolm/osf.io,alexschiller/osf.io,brandonPurvis/osf.io,asanfilippo7/osf.io,caneruguz/osf.io,asanfilippo7/osf.io,RomanZWang/osf.io,wearpants/osf.io,GageGaskins/osf.io,arpitar/osf.io,chennan47/osf.io,alexschiller/osf.io,Johnetordoff/osf.io,CenterForOpenScience/osf.io,hmoco/osf.io,ticklemepierce/osf.io,billyhunt/osf.io,mluo613/osf.io,baylee-d/osf.io,billyhunt/osf.io,laurenrevere/osf.io,sbt9uc/osf.io,samanehsan/osf.io,danielneis/osf.io,chennan47/osf.io,caseyrygt/osf.io,chennan47/osf.io,haoyuchen1992/osf.io,abought/osf.io,TomHeatwole/osf.io,felliott/osf.io,GageGaskins/osf.io,RomanZWang/osf.io,caseyrygt/osf.io,ZobairAlijan/osf.io,doublebits/osf.io,KAsante95/osf.io,mattclark/osf.io,cosenal/osf.io,Nesiehr/osf.io,ckc6cz/osf.io,doublebits/osf.io,monikagrabowska/osf.io,erinspace/osf.io,alexschiller/osf.io,aaxelb/osf.io,ckc6cz/osf.io,ticklemepierce/osf.io,leb2dg/osf.io,binoculars/osf.io,erinspace/osf.io,mluke93/osf.io,mluke93/osf.io,aaxelb/osf.io,dplorimer/osf,lyndsysimon/osf.io,rdhyee/osf.io,bdyetton/prettychart,zachjanicki/osf.io,caneruguz/osf.io,MerlinZhang/osf.io,jolene-esposito/osf.io,rdhyee/osf.io,SSJohns/osf.io,pattisdr/osf.io,caseyrollins/osf.io,sloria/osf.io,cwisecarver/osf.io,rdhyee/osf.io,MerlinZhang/osf.io,monikagrabowska/osf.io,abought/osf.io,dplorimer/osf,adlius/osf.io,erinspace/osf.io,asanfilippo7/osf.io,arpitar/osf.io,dplorimer/osf,SSJohns/osf.io,jnayak1/osf.io,felliott/osf.io,bdyetton/prettychart,adlius/osf.io,ticklemepierce/osf.io,samchrisinger/osf.io,CenterForOpenScience/osf.io,icereval/osf.io,sbt9uc/osf.io,cwisecarver/osf.io,KAsante95/osf.io,jnayak1/osf.io,pattisdr/osf.io,samchrisinger/osf.io,felliott/osf.io,emetsger/osf.io,aaxelb/osf.io,caneruguz/osf.io,samchrisinger/osf.io,amyshi188/osf.io,cosenal/osf.io,binoculars/osf.io,saradbowman/osf.io,caseyrygt/osf.io,HalcyonChimera/osf.io,leb2dg/osf.io,KAsante95/osf.io,danielneis/osf.io,kwierman/osf.io,chrisseto/osf.io,zachjanicki/osf.io,abought/osf.io,petermalcolm/osf.io,cslzchen/osf.io,zamattiac/osf.io,njantrania/osf.io,kwierman/osf.io,TomBaxter/osf.io,zamattiac/osf.io,monikagrabowska/osf.io,danielneis/osf.io,brandonPurvis/osf.io,TomBaxter/osf.io,brandonPurvis/osf.io,doublebits/osf.io,crcresearch/osf.io,mfraezz/osf.io,HalcyonChimera/osf.io,petermalcolm/osf.io,RomanZWang/osf.io,mluo613/osf.io,kch8qx/osf.io,arpitar/osf.io,cslzchen/osf.io,mfraezz/osf.io,monikagrabowska/osf.io,MerlinZhang/osf.io,petermalcolm/osf.io,reinaH/osf.io,Johnetordoff/osf.io,leb2dg/osf.io,zachjanicki/osf.io,jmcarp/osf.io,KAsante95/osf.io,cldershem/osf.io,reinaH/osf.io,DanielSBrown/osf.io,alexschiller/osf.io,kch8qx/osf.io,TomHeatwole/osf.io,caseyrollins/osf.io,GageGaskins/osf.io,zachjanicki/osf.io,cslzchen/osf.io,ckc6cz/osf.io,abought/osf.io,CenterForOpenScience/osf.io,reinaH/osf.io,arpitar/osf.io,mfraezz/osf.io,brianjgeiger/osf.io,wearpants/osf.io,chrisseto/osf.io,alexschiller/osf.io,ZobairAlijan/osf.io,monikagrabowska/osf.io,HalcyonChimera/osf.io,amyshi188/osf.io,brandonPurvis/osf.io,GageGaskins/osf.io,Nesiehr/osf.io,leb2dg/osf.io,Johnetordoff/osf.io,SSJohns/osf.io,KAsante95/osf.io,crcresearch/osf.io,cldershem/osf.io,HarryRybacki/osf.io,pattisdr/osf.io,mluke93/osf.io,amyshi188/osf.io,rdhyee/osf.io,doublebits/osf.io,sloria/osf.io,njantrania/osf.io,haoyuchen1992/osf.io,caneruguz/osf.io,acshi/osf.io,zamattiac/osf.io,TomHeatwole/osf.io,samanehsan/osf.io,danielneis/osf.io
890190f40b9061f7bfa15bbd7e56abc0f1b7d44a
redmapper/__init__.py
redmapper/__init__.py
from __future__ import division, absolute_import, print_function from ._version import __version__, __version_info__ version = __version__ from .configuration import Configuration from .runcat import RunCatalog from .solver_nfw import Solver from .catalog import DataObject, Entry, Catalog from .redsequence import RedSequenceColorPar from .chisq_dist import compute_chisq from .background import Background, ZredBackground from .cluster import Cluster, ClusterCatalog from .galaxy import Galaxy, GalaxyCatalog from .mask import Mask, HPMask, get_mask from .zlambda import Zlambda, ZlambdaCorrectionPar from .cluster_runner import ClusterRunner from .zred_color import ZredColor from .centering import Centering, CenteringWcenZred, CenteringBCG from .depthmap import DepthMap from .color_background import ColorBackground, ColorBackgroundGenerator
from __future__ import division, absolute_import, print_function from ._version import __version__, __version_info__ version = __version__ from .configuration import Configuration from .runcat import RunCatalog from .solver_nfw import Solver from .catalog import DataObject, Entry, Catalog from .redsequence import RedSequenceColorPar from .chisq_dist import compute_chisq from .background import Background, ZredBackground from .cluster import Cluster, ClusterCatalog from .galaxy import Galaxy, GalaxyCatalog from .mask import Mask, HPMask, get_mask from .zlambda import Zlambda, ZlambdaCorrectionPar from .cluster_runner import ClusterRunner from .zred_color import ZredColor from .centering import Centering, CenteringWcenZred, CenteringBCG from .depthmap import DepthMap from .color_background import ColorBackground, ColorBackgroundGenerator from .fitters import MedZFitter, RedSequenceFitter, RedSequenceOffDiagonalFitter, CorrectionFitter, EcgmmFitter
Make fitters available at main import level.
Make fitters available at main import level.
Python
apache-2.0
erykoff/redmapper,erykoff/redmapper
aa8234d1e6b4916e6945468a2bc5772df2d53e28
bot/admin.py
bot/admin.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from . import models @admin.register(models.Notification) class NotificationAdmin(admin.ModelAdmin): list_display = ('launch', 'last_net_stamp', 'last_twitter_post', 'last_notification_sent', 'last_notification_recipient_count', 'days_to_launch') readonly_fields = ('days_to_launch',) ordering = ('launch__net',) search_fields = ('launch__name',) @admin.register(models.DailyDigestRecord) class DailyDigestRecordAdmin(admin.ModelAdmin): list_display = ('id', 'timestamp', 'messages', 'count', 'data')
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from . import models @admin.register(models.Notification) class NotificationAdmin(admin.ModelAdmin): list_display = ('launch', 'last_net_stamp', 'last_twitter_post', 'last_notification_sent', 'last_notification_recipient_count', 'days_to_launch') readonly_fields = ('days_to_launch',) ordering = ('launch__net',) search_fields = ('launch__name',) @admin.register(models.DailyDigestRecord) class DailyDigestRecordAdmin(admin.ModelAdmin): list_display = ('id', 'timestamp', 'messages', 'count', 'data') @admin.register(models.DiscordChannel) class DiscordBotAdmin(admin.ModelAdmin): list_display = ('name', 'channel_id', 'server_id')
Add Discord Admin for debugging.
Add Discord Admin for debugging.
Python
apache-2.0
ItsCalebJones/SpaceLaunchNow-Server,ItsCalebJones/SpaceLaunchNow-Server,ItsCalebJones/SpaceLaunchNow-Server
e9fbd541b3fcb84c6d2de9ba1de53886730a67fa
common.py
common.py
import os def get_project_path(): root_dir = os.path.abspath(os.path.dirname(__file__)) return root_dir
import os def get_project_path(): root_dir = os.path.abspath(os.path.dirname(__file__)) return root_dir def get_yourproject_path(): root_dir = os.path.abspath(os.path.dirname(__file__)) return root_dir
Add new changes to th branch
Add new changes to th branch
Python
mit
nvthanh1/Skypybot
42a54411634ef395ca3c2dfbfeefd7cea2d55101
auth0plus/exceptions.py
auth0plus/exceptions.py
try: from auth0.v2.exceptions import Auth0Error except ImportError: # pragma: no cover class Auth0Error(Exception): def __init__(self, status_code, error_code, message): self.status_code = status_code self.error_code = error_code self.message = message def __str__(self): return '%s: %s' % (self.status_code, self.message) class MultipleObjectsReturned(Exception): pass class ObjectDoesNotExist(Exception): pass class DoesNotExist(ObjectDoesNotExist): pass class UnimplementedException(Exception): pass
try: from auth0.v3.exceptions import Auth0Error except ImportError: # pragma: no cover class Auth0Error(Exception): def __init__(self, status_code, error_code, message): self.status_code = status_code self.error_code = error_code self.message = message def __str__(self): return '%s: %s' % (self.status_code, self.message) class MultipleObjectsReturned(Exception): pass class ObjectDoesNotExist(Exception): pass class DoesNotExist(ObjectDoesNotExist): pass class UnimplementedException(Exception): pass
Update to v3 of the auth0 client for the exception handling
Update to v3 of the auth0 client for the exception handling
Python
isc
bretth/auth0plus
53ad3866b8dfbd012748e4ad7d7ed7025d491bd0
src/alexa-main.py
src/alexa-main.py
import handlers.events as events APPLICATION_ID = "amzn1.ask.skill.dd677950-cade-4805-b1f1-ce2e3a3569f0" def lambda_handler(event, context): if event['session']['new']: events.on_session_started({'requestId': event['request']['requestId']}, event['session']) request_type = event['request']['type'] if request_type == "LaunchRequest": return events.on_launch(event['request'], event['session']) elif request_type == "IntentRequest": return events.on_intent(event['request'], event['session']) elif request_type == "SessionEndedRequest": return events.on_session_ended(event['request'], event['session'])
import handlers.events as events APPLICATION_ID = "amzn1.ask.skill.dd677950-cade-4805-b1f1-ce2e3a3569f0" def lambda_handler(event, context): # Make sure only this Alexa skill can use this function if event['session']['application']['applicationId'] != APPLICATION_ID: raise ValueError("Invalid Application ID") if event['session']['new']: events.on_session_started({'requestId': event['request']['requestId']}, event['session']) request_type = event['request']['type'] if request_type == "LaunchRequest": return events.on_launch(event['request'], event['session']) elif request_type == "IntentRequest": return events.on_intent(event['request'], event['session']) elif request_type == "SessionEndedRequest": return events.on_session_ended(event['request'], event['session'])
REVERT remove application id validation
REVERT remove application id validation
Python
mit
mauriceyap/ccm-assistant
5cd674ec764be72bb3e94c0b56fdf733a4a1c885
Discord/utilities/errors.py
Discord/utilities/errors.py
from discord.ext.commands.errors import CommandError class NotServerOwner(CommandError): '''Not Server Owner''' pass class VoiceNotConnected(CommandError): '''Voice Not Connected''' pass class PermittedVoiceNotConnected(VoiceNotConnected): '''Permitted, but Voice Not Connected''' pass class NotPermittedVoiceNotConnected(VoiceNotConnected): '''Voice Not Connected, and Not Permitted''' pass class MissingPermissions(CommandError): '''Missing Permissions''' pass class MissingCapability(CommandError): '''Missing Capability''' def __init__(self, permissions): self.permissions = permissions class NotPermitted(CommandError): '''Not Permitted''' pass class AudioError(CommandError): '''Audio Error''' pass class AudioNotPlaying(AudioError): '''Audio Not Playing''' pass class AudioAlreadyDone(AudioError): '''Audio Already Done playing''' pass
from discord.ext.commands.errors import CommandError class NotServerOwner(CommandError): '''Not Server Owner''' pass class VoiceNotConnected(CommandError): '''Voice Not Connected''' pass class PermittedVoiceNotConnected(VoiceNotConnected): '''Permitted, but Voice Not Connected''' pass class NotPermittedVoiceNotConnected(VoiceNotConnected): '''Voice Not Connected, and Not Permitted''' pass class MissingPermissions(CommandError): '''Missing Permissions''' pass class MissingCapability(CommandError): '''Missing Capability''' def __init__(self, permissions): self.permissions = permissions class NotPermitted(CommandError): '''Not Permitted''' pass class AudioError(CommandError): '''Audio Error''' pass class AudioNotPlaying(AudioError): '''Audio Not Playing''' pass
Remove Audio Already Done error
[Discord] Remove Audio Already Done error
Python
mit
Harmon758/Harmonbot,Harmon758/Harmonbot
737d069c57c3cb2d6305f8e5d1f7d88402ef1327
go/apps/jsbox/definition.py
go/apps/jsbox/definition.py
import json from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class ViewLogsAction(ConversationAction): action_name = 'view_logs' action_display_name = 'View Sandbox Logs' redirect_to = 'jsbox_logs' class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'jsbox' conversation_display_name = 'Javascript App' actions = (ViewLogsAction,) def configured_endpoints(self, config): # TODO: make jsbox apps define these explicitly and # update the outbound resource to check and # complain if a jsbox app sends on an endpoint # it hasn't defined. app_config = config.get("jsbox_app_config", {}) raw_js_config = app_config.get("config", {}).get("value", {}) try: js_config = json.loads(raw_js_config) pool, tag = js_config.get("sms_tag") except Exception: return [] return ["%s:%s" % (pool, tag)]
import json from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class ViewLogsAction(ConversationAction): action_name = 'view_logs' action_display_name = 'View Sandbox Logs' redirect_to = 'jsbox_logs' class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'jsbox' conversation_display_name = 'Javascript App' actions = (ViewLogsAction,) def configured_endpoints(self, config): # TODO: make jsbox apps define these explicitly and # update the outbound resource to check and # complain if a jsbox app sends on an endpoint # it hasn't defined. app_config = config.get("jsbox_app_config", {}) raw_js_config = app_config.get("config", {}).get("value", {}) try: js_config = json.loads(raw_js_config) except Exception: return [] endpoints = set() # vumi-jssandbox-toolkit v2 endpoints try: endpoints.update(js_config["endpoints"].keys()) except Exception: pass # vumi-jssandbox-toolkit v1 endpoints try: pool, tag = js_config["sms_tag"] endpoints.add("%s:%s" % (pool, tag)) except Exception: pass return sorted(endpoints)
Add support for v2 endpoints in config.
Add support for v2 endpoints in config.
Python
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
c97e5cf11fc21e2ef4ee04779a424e4d6a2b96ae
tools/perf/metrics/__init__.py
tools/perf/metrics/__init__.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. class Metric(object): """Base class for all the metrics that are used by telemetry measurements. The Metric class represents a way of measuring something. Metrics are helper classes used by PageMeasurements. Each PageMeasurement may use multiple metrics; each metric should be focussed on collecting data about one thing. """ def Start(self, page, tab): """Start collecting data for this metric.""" raise NotImplementedError() def Stop(self, page, tab): """Stop collecting data for this metric (if applicable).""" raise NotImplementedError() def AddResults(self, tab, results): """Add the data collected into the results object for a measurement. Metrics may implement AddResults to provide a common way to add results to the PageMeasurementResults in PageMeasurement.AddMeasurement -- results should be added with results.Add(trace_name, unit, value). """ raise NotImplementedError()
# 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. class Metric(object): """Base class for all the metrics that are used by telemetry measurements. The Metric class represents a way of measuring something. Metrics are helper classes used by PageMeasurements. Each PageMeasurement may use multiple metrics; each metric should be focussed on collecting data about one thing. """ def CustomizeBrowserOptions(self, options): """Add browser options that are required by this metric. Some metrics do not have any special browser options that need to be added, and they do not need to override this method; by default, no browser options are added. To add options here, call options.AppendExtraBrowserArg(arg). """ pass def Start(self, page, tab): """Start collecting data for this metric.""" raise NotImplementedError() def Stop(self, page, tab): """Stop collecting data for this metric (if applicable).""" raise NotImplementedError() def AddResults(self, tab, results): """Add the data collected into the results object for a measurement. Metrics may implement AddResults to provide a common way to add results to the PageMeasurementResults in PageMeasurement.AddMeasurement -- results should be added with results.Add(trace_name, unit, value). """ raise NotImplementedError()
Add CustomizeBrowserOptions method to Metric base class
Add CustomizeBrowserOptions method to Metric base class BUG=271177 Review URL: https://chromiumcodereview.appspot.com/22938004 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@217198 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
mogoweb/chromium-crosswalk,Just-D/chromium-1,M4sse/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,Just-D/chromium-1,ChromiumWebApps/chromium,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,M4sse/chromium.src,Fireblend/chromium-crosswalk,Jonekee/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,ltilve/chromium,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,dushu1203/chromium.src,markYoungH/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,M4sse/chromium.src,jaruba/chromium.src,littlstar/chromium.src,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,jaruba/chromium.src,ondra-novak/chromium.src,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,dednal/chromium.src,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,anirudhSK/chromium,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,jaruba/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,axinging/chromium-crosswalk,ondra-novak/chromium.src,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,anirudhSK/chromium,M4sse/chromium.src,Fireblend/chromium-crosswalk,anirudhSK/chromium,Jonekee/chromium.src,markYoungH/chromium.src,littlstar/chromium.src,axinging/chromium-crosswalk,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,hgl888/chromium-crosswalk,dushu1203/chromium.src,fujunwei/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,patrickm/chromium.src,Just-D/chromium-1,dushu1203/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,dednal/chromium.src,jaruba/chromium.src,ltilve/chromium,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,littlstar/chromium.src,Chilledheart/chromium,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,patrickm/chromium.src,jaruba/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,ltilve/chromium,Just-D/chromium-1,Jonekee/chromium.src,anirudhSK/chromium,markYoungH/chromium.src,markYoungH/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,Chilledheart/chromium,mogoweb/chromium-crosswalk,Jonekee/chromium.src,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,ltilve/chromium,patrickm/chromium.src,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk,Jonekee/chromium.src,ltilve/chromium,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,ltilve/chromium,jaruba/chromium.src,patrickm/chromium.src,M4sse/chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,anirudhSK/chromium,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,ltilve/chromium,dednal/chromium.src,anirudhSK/chromium,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,anirudhSK/chromium,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,dednal/chromium.src,jaruba/chromium.src,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,dednal/chromium.src,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,Jonekee/chromium.src,jaruba/chromium.src,bright-sparks/chromium-spacewalk,dednal/chromium.src,dushu1203/chromium.src,ltilve/chromium,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,chuan9/chromium-crosswalk,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,Just-D/chromium-1,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,ondra-novak/chromium.src,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,littlstar/chromium.src,dednal/chromium.src,dednal/chromium.src,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,ltilve/chromium,patrickm/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src
f9c7a911411429972929bb4372b370192bd4cf8a
altair/examples/interactive_layered_crossfilter.py
altair/examples/interactive_layered_crossfilter.py
""" Interactive Crossfilter ======================= This example shows a multi-panel view of the same data, where you can interactively select a portion of the data in any of the panels to highlight that portion in any of the other panels. """ # category: interactive charts import altair as alt from vega_datasets import data source = alt.UrlData( data.flights_2k.url, format={'parse': {'date': 'date'}} ) brush = alt.selection(type='interval', encodings=['x']) # Define the base chart, with the common parts of the # background and highlights base = alt.Chart().mark_bar().encode( x=alt.X(alt.repeat('column'), type='quantitative', bin=alt.Bin(maxbins=20)), y='count()' ).properties( width=160, height=130 ) # blue background with selection background = base.add_selection(brush) # yellow highlights on the transformed data highlight = base.encode( color=alt.value('goldenrod') ).transform_filter(brush) # layer the two charts & repeat alt.layer( background, highlight, data=source ).transform_calculate( "time", "hours(datum.date)" ).repeat(column=["distance", "delay", "time"])
""" Interactive Crossfilter ======================= This example shows a multi-panel view of the same data, where you can interactively select a portion of the data in any of the panels to highlight that portion in any of the other panels. """ # category: interactive charts import altair as alt from vega_datasets import data source = alt.UrlData( data.flights_2k.url, format={'parse': {'date': 'date'}} ) brush = alt.selection(type='interval', encodings=['x']) # Define the base chart, with the common parts of the # background and highlights base = alt.Chart().mark_bar().encode( x=alt.X(alt.repeat('column'), type='quantitative', bin=alt.Bin(maxbins=20)), y='count()' ).properties( width=160, height=130 ) # gray background with selection background = base.encode( color=alt.value('#ddd') ).add_selection(brush) # blue highlights on the transformed data highlight = base.transform_filter(brush) # layer the two charts & repeat alt.layer( background, highlight, data=source ).transform_calculate( "time", "hours(datum.date)" ).repeat(column=["distance", "delay", "time"])
Update crossfilter to gray/blue scheme
Update crossfilter to gray/blue scheme Same as in https://vega.github.io/editor/#/examples/vega-lite/interactive_layered_crossfilter
Python
bsd-3-clause
altair-viz/altair,jakevdp/altair
6064db3000f2aeec66a775345d22b8a2b421497f
astropy/utils/tests/test_gzip.py
astropy/utils/tests/test_gzip.py
import io import os from ...tests.helper import pytest from .. import gzip def test_gzip(tmpdir): fd = gzip.GzipFile(str(tmpdir.join("test.gz")), 'wb') fd = io.TextIOWrapper(fd, encoding='utf8')
import io import os from ...tests.helper import pytest from .. import gzip pytestmark = pytest.mark.skipif("sys.version_info < (3,0)") def test_gzip(tmpdir): fd = gzip.GzipFile(str(tmpdir.join("test.gz")), 'wb') fd = io.TextIOWrapper(fd, encoding='utf8')
Fix gzip test for Python 2.6
Fix gzip test for Python 2.6
Python
bsd-3-clause
tbabej/astropy,bsipocz/astropy,lpsinger/astropy,MSeifert04/astropy,StuartLittlefair/astropy,larrybradley/astropy,DougBurke/astropy,stargaser/astropy,pllim/astropy,stargaser/astropy,MSeifert04/astropy,tbabej/astropy,lpsinger/astropy,joergdietrich/astropy,astropy/astropy,joergdietrich/astropy,dhomeier/astropy,kelle/astropy,kelle/astropy,saimn/astropy,MSeifert04/astropy,bsipocz/astropy,funbaker/astropy,kelle/astropy,pllim/astropy,dhomeier/astropy,StuartLittlefair/astropy,pllim/astropy,dhomeier/astropy,MSeifert04/astropy,larrybradley/astropy,mhvk/astropy,funbaker/astropy,StuartLittlefair/astropy,stargaser/astropy,StuartLittlefair/astropy,aleksandr-bakanov/astropy,astropy/astropy,AustereCuriosity/astropy,tbabej/astropy,DougBurke/astropy,AustereCuriosity/astropy,funbaker/astropy,pllim/astropy,lpsinger/astropy,larrybradley/astropy,funbaker/astropy,dhomeier/astropy,mhvk/astropy,joergdietrich/astropy,saimn/astropy,kelle/astropy,lpsinger/astropy,stargaser/astropy,mhvk/astropy,bsipocz/astropy,StuartLittlefair/astropy,dhomeier/astropy,saimn/astropy,mhvk/astropy,joergdietrich/astropy,astropy/astropy,AustereCuriosity/astropy,AustereCuriosity/astropy,astropy/astropy,aleksandr-bakanov/astropy,joergdietrich/astropy,mhvk/astropy,aleksandr-bakanov/astropy,saimn/astropy,larrybradley/astropy,larrybradley/astropy,tbabej/astropy,pllim/astropy,bsipocz/astropy,aleksandr-bakanov/astropy,DougBurke/astropy,astropy/astropy,kelle/astropy,lpsinger/astropy,AustereCuriosity/astropy,tbabej/astropy,saimn/astropy,DougBurke/astropy
6797c9b705b0cfd5c770f68695402baf044510ff
utils/training_utils/params.py
utils/training_utils/params.py
# Data set split TRAIN_FRACTION = 0.75 VALIDATE_FRACTION = 0.1 TEST_FRACTION = 0.15 TOTAL_NUM_EXAMPLES = 147052 # Total number of tracks assert(TRAIN_FRACTION + VALIDATE_FRACTION + TEST_FRACTION == 1.0) # Validation and check pointing EVALUATION_FREQ = 1000 # Number of mini-batch SGD steps after which an evaluation is performed. CHECKPOINT_FREQ = 1000 # Number of mini-batch SGD steps after which a checkpoint is taken. # File paths EXPT_DIRECTORY_PATH = "./Experiments" # Path of the Experiments directory
# Data set split TRAIN_FRACTION = 0.75 VALIDATE_FRACTION = 0.1 TEST_FRACTION = 0.15 TOTAL_NUM_EXAMPLES = 147052 # Total number of tracks assert(TRAIN_FRACTION + VALIDATE_FRACTION + TEST_FRACTION == 1.0) # Validation and check pointing EVALUATION_FREQ = 900 # Number of mini-batch SGD steps after which an evaluation is performed. CHECKPOINT_FREQ = 900 # Number of mini-batch SGD steps after which a checkpoint is taken. # File paths EXPT_DIRECTORY_PATH = "./Experiments" # Path of the Experiments directory
Change default value of checkpoint frequency
Change default value of checkpoint frequency The default values of evaluation and checkpoint frequency are the same, and they are approximately equal to the number of steps in each epoch.
Python
mit
harpribot/representation-music,harpribot/representation-music
f195c01ad6a98b3454880106e95fe40bbeb14da0
tests/test_essentia_dissonance.py
tests/test_essentia_dissonance.py
#! /usr/bin/env python from unit_timeside import unittest, TestRunner from timeside.plugins.decoder.file import FileDecoder from timeside.core import get_processor from timeside.core.tools.test_samples import samples class TestEssentiaDissonance(unittest.TestCase): def setUp(self): self.analyzer = get_processor('essentia_dissonance')() def testOnC4Scale(self): "runs on C4 scale" self.source = samples["C4_scale.wav"] def tearDown(self): decoder = FileDecoder(self.source) (decoder | self.analyzer).run() self.assertAlmostEqual(self.analyzer.results['essentia_dissonance'].data_object.value.mean(), 0.18, places=2) if __name__ == '__main__': unittest.main(testRunner=TestRunner())
#! /usr/bin/env python from unit_timeside import unittest, TestRunner from timeside.plugins.decoder.file import FileDecoder from timeside.core import get_processor from timeside.core.tools.test_samples import samples class TestEssentiaDissonance(unittest.TestCase): def setUp(self): self.analyzer = get_processor('essentia_dissonance')() def testOnC4Scale(self): "runs on C4 scale" self.source = samples["C4_scale.wav"] def tearDown(self): decoder = FileDecoder(self.source) (decoder | self.analyzer).run() self.assertAlmostEqual(self.analyzer.results['essentia_dissonance'].data_object.value.mean(), 0.16, places=2) if __name__ == '__main__': unittest.main(testRunner=TestRunner())
Fix unit test for essentia dissonance
Fix unit test for essentia dissonance
Python
agpl-3.0
Parisson/TimeSide,Parisson/TimeSide,Parisson/TimeSide,Parisson/TimeSide,Parisson/TimeSide
853c727c472efc09df90cb016bd05f81d4cf5e8e
beetle_preview/__init__.py
beetle_preview/__init__.py
from http import server from socketserver import TCPServer import os class Server: def __init__(self, own_config, config, builder): self.directory = config.folders['output'] self.port = own_config.get('port', 5000) self.builder = builder def serve(self): os.chdir(self.directory) request_handler = server.SimpleHTTPRequestHandler httpd = TCPServer(('', self.port), request_handler) try: httpd.serve_forever() except KeyboardInterrupt: httpd.shutdown() def register(plugin_config, config, commander, builder, content_renderer): server = Server(plugin_config, config, builder) commander.add('preview', server.serve, 'Serve the rendered site')
from http import server from socketserver import TCPServer import os class Server: def __init__(self, own_config, config, builder): self.directory = config.folders['output'] self.port = own_config.get('port', 5000) self.builder = builder def serve(self): os.chdir(self.directory) request_handler = server.SimpleHTTPRequestHandler httpd = TCPServer(('', self.port), request_handler) try: print('Preview available at http://0.0.0.0:{}/'.format(self.port)) httpd.serve_forever() except KeyboardInterrupt: httpd.shutdown() def register(plugin_config, config, commander, builder, content_renderer): server = Server(plugin_config, config, builder) commander.add('preview', server.serve, 'Serve the rendered site')
Print a line telling where the site is available at
Print a line telling where the site is available at
Python
mit
cknv/beetle-preview
b474c7368f3a8152296acf9cad7459510b71ada5
fs/opener/sshfs.py
fs/opener/sshfs.py
from ._base import Opener from ._registry import registry @registry.install class SSHOpener(Opener): protocols = ['ssh'] @staticmethod def open_fs(fs_url, parse_result, writeable, create, cwd): from ..sshfs import SSHFS ssh_host, _, dir_path = parse_result.resource.partition('/') ssh_host, _, ssh_port = ssh_host.partition(':') ssh_port = int(ssh_port) if ssh_port.isdigit() else 22 ssh_fs = SSHFS( ssh_host, port=ssh_port, user=parse_result.username, passwd=parse_result.password, ) return ssh_fs.opendir(dir_path) if dir_path else ssh_fs
from ._base import Opener from ._registry import registry from ..subfs import ClosingSubFS @registry.install class SSHOpener(Opener): protocols = ['ssh'] @staticmethod def open_fs(fs_url, parse_result, writeable, create, cwd): from ..sshfs import SSHFS ssh_host, _, dir_path = parse_result.resource.partition('/') ssh_host, _, ssh_port = ssh_host.partition(':') ssh_port = int(ssh_port) if ssh_port.isdigit() else 22 ssh_fs = SSHFS( ssh_host, port=ssh_port, user=parse_result.username, passwd=parse_result.password, ) if dir_path: return ssh_fs.opendir(dir_path, factory=ClosingSubFS) else: return ssh_fs
Fix SSHOpener to use the new ClosingSubFS
Fix SSHOpener to use the new ClosingSubFS
Python
lgpl-2.1
althonos/fs.sshfs
22f305a7cb1daab3dc61b0d22b796916417de9d2
examples/mnist-deepautoencoder.py
examples/mnist-deepautoencoder.py
#!/usr/bin/env python import matplotlib.pyplot as plt import theanets from utils import load_mnist, plot_layers, plot_images train, valid, _ = load_mnist() e = theanets.Experiment( theanets.Autoencoder, layers=(784, 256, 64, 16, 64, 256, 784), train_batches=100, tied_weights=True, ) e.run(train, valid) plot_layers(e.network.weights, tied_weights=True) plt.tight_layout() plt.show() valid = valid[:16*16] plot_images(valid, 121, 'Sample data') plot_images(e.network.predict(valid), 122, 'Reconstructed data') plt.tight_layout() plt.show()
#!/usr/bin/env python import matplotlib.pyplot as plt import theanets from utils import load_mnist, plot_layers, plot_images train, valid, _ = load_mnist() e = theanets.Experiment( theanets.Autoencoder, layers=(784, 256, 64, 36, 64, 256, 784), train_batches=100, tied_weights=True, ) e.run(train, valid) plot_layers(e.network.weights, tied_weights=True) plt.tight_layout() plt.show() valid = valid[:16*16] plot_images(valid, 121, 'Sample data') plot_images(e.network.predict(valid), 122, 'Reconstructed data') plt.tight_layout() plt.show()
Increase size of bottleneck layer.
Increase size of bottleneck layer.
Python
mit
lmjohns3/theanets,chrinide/theanets,devdoer/theanets
f70bbbdadc044a76f7b90b2cac0191353a6a5048
depfinder.py
depfinder.py
import ast def get_imported_libs(code): tree = ast.parse(code) # ast.Import represents lines like 'import foo' and 'import foo, bar' # the extra for name in t.names is needed, because names is a list that # would be ['foo'] for the first and ['foo', 'bar'] for the second imports = [name.name.split('.')[0] for t in tree.body if type(t) == ast.Import for name in t.names] # ast.ImportFrom represents lines like 'from foo import bar' import_froms = [t.module.split('.')[0] for t in tree.body if type(t) == ast.ImportFrom if t.module] return imports + import_froms
import ast import os from collections import deque import sys from stdlib_list import stdlib_list conf = { 'ignore_relative_imports': True, 'ignore_builtin_modules': True, 'pyver': None, } def get_imported_libs(code): tree = ast.parse(code) imports = deque() for t in tree.body: # ast.Import represents lines like 'import foo' and 'import foo, bar' # the extra for name in t.names is needed, because names is a list that # would be ['foo'] for the first and ['foo', 'bar'] for the second if type(t) == ast.Import: imports.extend([name.name.split('.')[0] for name in t.names]) # ast.ImportFrom represents lines like 'from foo import bar' # t.level == 0 is to get rid of 'from .foo import bar' and higher levels # of relative importing if type(t) == ast.ImportFrom: if t.level > 0: if conf['ignore_relative_imports'] or not t.module: continue else: imports.append(t.module.split('.')[0]) return list(imports) def iterate_over_library(path_to_source_code): libs = set() for parent, folders, files in os.walk(path_to_source_code): for file in files: if file.endswith('.py'): print('.', end='') full_file_path = os.path.join(parent, file) with open(full_file_path, 'r') as f: code = f.read() libs.update(set(get_imported_libs(code))) if conf['ignore_builtin_modules']: if not conf['pyver']: pyver = '%s.%s' % (sys.version_info.major, sys.version_info.minor) std_libs = stdlib_list("3.4") # print(std_libs) libs = [lib for lib in libs if lib not in std_libs] return libs
Rework the import finding logic
MNT: Rework the import finding logic
Python
bsd-3-clause
ericdill/depfinder
2a8c4790bd432fc4dc0fdda64c0cea4f76fac9ff
feincms/context_processors.py
feincms/context_processors.py
from feincms.module.page.models import Page def add_page_if_missing(request): # If this attribute exists, the a page object has been registered already # by some other part of the code. We let it decide, which page object it # wants to pass into the template if hasattr(request, '_feincms_page'): return {} return { 'feincms_page': Page.objects.best_match_for_request(request), }
from feincms.module.page.models import Page def add_page_if_missing(request): # If this attribute exists, the a page object has been registered already # by some other part of the code. We let it decide, which page object it # wants to pass into the template if hasattr(request, '_feincms_page'): return {} try: return { 'feincms_page': Page.objects.best_match_for_request(request), } except Page.DoesNotExist: return {}
Fix add_page_if_missing context processor when no pages exist yet
Fix add_page_if_missing context processor when no pages exist yet
Python
bsd-3-clause
matthiask/feincms2-content,hgrimelid/feincms,nickburlett/feincms,michaelkuty/feincms,michaelkuty/feincms,hgrimelid/feincms,feincms/feincms,pjdelport/feincms,joshuajonah/feincms,pjdelport/feincms,michaelkuty/feincms,joshuajonah/feincms,matthiask/feincms2-content,matthiask/django-content-editor,matthiask/django-content-editor,pjdelport/feincms,matthiask/django-content-editor,mjl/feincms,nickburlett/feincms,nickburlett/feincms,michaelkuty/feincms,matthiask/feincms2-content,mjl/feincms,joshuajonah/feincms,hgrimelid/feincms,nickburlett/feincms,joshuajonah/feincms,feincms/feincms,mjl/feincms,feincms/feincms,matthiask/django-content-editor
efa36e1013e44fa75f6a77a74bd8bf21f3120976
django_facebook/models.py
django_facebook/models.py
from django.db import models from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect class FacebookProfileModel(models.Model): ''' Abstract class to add to your profile model. NOTE: If you don't use this this abstract class, make sure you copy/paste the fields in. ''' about_me = models.TextField(blank=True, null=True) facebook_id = models.IntegerField(blank=True, null=True) facebook_name = models.CharField(max_length=255, blank=True, null=True) facebook_profile_url = models.TextField(blank=True, null=True) website_url = models.TextField(blank=True, null=True) blog_url = models.TextField(blank=True, null=True) image = models.ImageField(blank=True, null=True, upload_to='profile_images') date_of_birth = models.DateField(blank=True, null=True) raw_data = models.TextField(blank=True, null=True) def __unicode__(self): return self.user.__unicode__() class Meta: abstract = True def post_facebook_registration(self): ''' Behaviour after registering with facebook ''' url = reverse('facebook_connect') response = HttpResponseRedirect(url) response.set_cookie('fresh_registration', self.user.id) return response
from django.db import models from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect class FacebookProfileModel(models.Model): ''' Abstract class to add to your profile model. NOTE: If you don't use this this abstract class, make sure you copy/paste the fields in. ''' about_me = models.TextField(blank=True, null=True) facebook_id = models.IntegerField(blank=True, null=True) facebook_name = models.CharField(max_length=255, blank=True, null=True) facebook_profile_url = models.TextField(blank=True, null=True) website_url = models.TextField(blank=True, null=True) blog_url = models.TextField(blank=True, null=True) image = models.ImageField(blank=True, null=True, upload_to='profile_images', max_length=255) date_of_birth = models.DateField(blank=True, null=True) raw_data = models.TextField(blank=True, null=True) def __unicode__(self): return self.user.__unicode__() class Meta: abstract = True def post_facebook_registration(self): ''' Behaviour after registering with facebook ''' url = reverse('facebook_connect') response = HttpResponseRedirect(url) response.set_cookie('fresh_registration', self.user.id) return response
Allow for a longer image path
Allow for a longer image path My profile image for example does not fit in the default VARCHAR(100)
Python
bsd-3-clause
fivejjs/Django-facebook,troygrosfield/Django-facebook,danosaure/Django-facebook,rafaelgontijo/Django-facebook-fork,abendleiter/Django-facebook,pjdelport/Django-facebook,fivejjs/Django-facebook,abendleiter/Django-facebook,abendleiter/Django-facebook,andriisoldatenko/Django-facebook,ganescoo/Django-facebook,VishvajitP/Django-facebook,javipalanca/Django-facebook,fyndsi/Django-facebook,christer155/Django-facebook,cyrixhero/Django-facebook,Fiedzia/Django-facebook,tuxos/Django-facebook,troygrosfield/Django-facebook,QLGu/Django-facebook,PeterWangPo/Django-facebook,PeterWangPo/Django-facebook,troygrosfield/Django-facebook,pjdelport/Django-facebook,andriisoldatenko/Django-facebook,tuxos/Django-facebook,danosaure/Django-facebook,abhijo89/Django-facebook,cyrixhero/Django-facebook,andriisoldatenko/Django-facebook,cyrixhero/Django-facebook,abhijo89/Django-facebook,VishvajitP/Django-facebook,sitsbeyou/Django-facebook,ganescoo/Django-facebook,sitsbeyou/Django-facebook,takeshineshiro/Django-facebook,christer155/Django-facebook,javipalanca/Django-facebook,takeshineshiro/Django-facebook,fyndsi/Django-facebook,fyndsi/Django-facebook,QLGu/Django-facebook,jcpyun/Django-facebook,takeshineshiro/Django-facebook,selwin/Django-facebook,christer155/Django-facebook,javipalanca/Django-facebook,rafaelgontijo/Django-facebook-fork,PeterWangPo/Django-facebook,selwin/Django-facebook,jcpyun/Django-facebook,Shekharrajak/Django-facebook,Shekharrajak/Django-facebook,ganescoo/Django-facebook,VishvajitP/Django-facebook,rafaelgontijo/Django-facebook-fork,jcpyun/Django-facebook,danosaure/Django-facebook,abhijo89/Django-facebook,QLGu/Django-facebook,Fiedzia/Django-facebook,Shekharrajak/Django-facebook,tuxos/Django-facebook,andriisoldatenko/Django-facebook,Fiedzia/Django-facebook,selwin/Django-facebook,fivejjs/Django-facebook,pjdelport/Django-facebook,sitsbeyou/Django-facebook
78a03f0b0cbc948a6c9fb215e9051d099c528a82
src/app.py
src/app.py
from flask import Flask from flask import render_template, url_for import parse_data app = Flask(__name__) @app.route("/dashboard") def dashboard(): data = parse_data.load_and_format_data() title = 'Grand Bargain Monitoring' return render_template('dashboard.html', data=data, heading=title, page_title=title) if __name__ == "__main__": app.run()
from flask import Flask from flask import render_template, url_for import parse_data app = Flask(__name__) @app.route("/dashboard") def dashboard(): data = parse_data.load_and_format_data() title = 'Grand Bargain Transparency Dashboard' return render_template('dashboard.html', data=data, heading=title, page_title=title) if __name__ == "__main__": app.run()
Change page title and heading
Change page title and heading
Python
mit
devinit/grand-bargain-monitoring,devinit/grand-bargain-monitoring,devinit/grand-bargain-monitoring
6b7e32c98fa8a11dcd7bbbadaa2a057e4ff0ce90
f5_os_test/__init__.py
f5_os_test/__init__.py
# Copyright 2016 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # __version__ = '0.2.0'
# Copyright 2016 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import random import string __version__ = '0.2.0' def random_name(prefix, N): """Creates a name with random characters. Returns a new string created from an input prefix appended with a set of random characters. The number of random characters appended to the prefix string is defined by the N parameter. For example, random_name('test_', 6) might return "test_FR3N5Y" :param string prefix: String to append randoms characters. :param int N: Number of random characters to append. """ return prefix + ''.join( random.SystemRandom().choice( string.ascii_uppercase + string.digits) for _ in range(N))
Add function to create name strings with random characters
Add function to create name strings with random characters Issues: Fixes #48 Problem: Need a function that will generate names with random chars. Analysis: Added new function, random_name(). Tests: test_solution.py
Python
apache-2.0
F5Networks/f5-openstack-test,pjbreaux/f5-openstack-test
1a98b29293ccfab6534a48402414e89726d8e5bb
Python/pomodoro.py
Python/pomodoro.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import subprocess as spr import time def main(): start = datetime.datetime.now() spr.call(['notify-send', 'Started new pomodoro']) time.sleep(30 * 60) end = datetime.datetime.now() duration = (end - start).total_seconds() // 60 for i in range(5): time.sleep(3) spr.call( ['notify-send', 'POMO: {0:.0f} minute passed.\tFrom {1}'.format( duration, start.strftime("%H:%M:%S")) ] ) if __name__ == "__main__": main()
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import subprocess as spr import time def main(): start = datetime.datetime.now() start_str = start.strftime("%H:%M:%S") spr.call(['notify-send', '--app-name', 'POMODORO', '--icon', 'dialog-information', 'New pomodoro', 'From: {}'.format(start_str)]) time.sleep(30 * 60) end = datetime.datetime.now() duration = (end - start).total_seconds() // 60 for i in range(5): time.sleep(3) spr.call( ['notify-send', 'POMO: {0:.0f} minute passed.\tFrom {1}'.format( duration, start_str ) ] ) if __name__ == "__main__": main()
Set icon, summary for notification
Set icon, summary for notification
Python
bsd-2-clause
familug/FAMILUG,familug/FAMILUG,familug/FAMILUG,familug/FAMILUG,familug/FAMILUG,familug/FAMILUG,familug/FAMILUG,familug/FAMILUG
d9a6071674857ceae566d29c7c77a31a5ed5214d
byceps/blueprints/api/decorators.py
byceps/blueprints/api/decorators.py
""" byceps.blueprints.api.decorators ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from functools import wraps from typing import Optional from flask import abort, request from ...services.authentication.api import service as api_service def api_token_required(func): """Ensure the request is authenticated via API token.""" @wraps(func) def wrapper(*args, **kwargs): if not _has_valid_api_token(): abort(401, www_authenticate='Bearer') return func(*args, **kwargs) return wrapper def _has_valid_api_token() -> bool: request_token = _extract_token_from_request() if request_token is None: return False api_token = api_service.find_api_token_by_token(request_token) return api_token is not None and not api_token.suspended def _extract_token_from_request() -> Optional[str]: header_value = request.headers.get('Authorization') if header_value is None: return None return header_value.replace('Bearer ', '', 1)
""" byceps.blueprints.api.decorators ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from functools import wraps from typing import Optional from flask import abort, request from werkzeug.datastructures import WWWAuthenticate from ...services.authentication.api import service as api_service def api_token_required(func): """Ensure the request is authenticated via API token.""" @wraps(func) def wrapper(*args, **kwargs): if not _has_valid_api_token(): www_authenticate = WWWAuthenticate('Bearer') abort(401, www_authenticate=www_authenticate) return func(*args, **kwargs) return wrapper def _has_valid_api_token() -> bool: request_token = _extract_token_from_request() if request_token is None: return False api_token = api_service.find_api_token_by_token(request_token) return api_token is not None and not api_token.suspended def _extract_token_from_request() -> Optional[str]: header_value = request.headers.get('Authorization') if header_value is None: return None return header_value.replace('Bearer ', '', 1)
Return proper WWW-Authenticate header if API authentication fails
Return proper WWW-Authenticate header if API authentication fails
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
b5653ac28ac8358127943bd1f40c22dfd8a274f3
examples/list_people.py
examples/list_people.py
#! /usr/bin/python # See README.txt for information and build instructions. import addressbook_pb2 import sys # Iterates though all people in the AddressBook and prints info about them. def ListPeople(address_book): for person in address_book.person: print "Person ID:", person.id print " Name:", person.name if person.HasField('email'): print " E-mail address:", person.email for phone_number in person.phone: if phone_number.type == addressbook_pb2.Person.MOBILE: print " Mobile phone #: ", elif phone_number.type == addressbook_pb2.Person.HOME: print " Home phone #: ", elif phone_number.type == addressbook_pb2.Person.WORK: print " Work phone #: ", print phone_number.number # Main procedure: Reads the entire address book from a file and prints all # the information inside. if len(sys.argv) != 2: print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE" sys.exit(-1) address_book = addressbook_pb2.AddressBook() # Read the existing address book. f = open(sys.argv[1], "rb") address_book.ParseFromString(f.read()) f.close() ListPeople(address_book)
#! /usr/bin/python # See README.txt for information and build instructions. import addressbook_pb2 import sys # Iterates though all people in the AddressBook and prints info about them. def ListPeople(address_book): for person in address_book.person: print "Person ID:", person.id print " Name:", person.name if person.HasField('email'): print " E-mail address:", person.email for phone_number in person.phone: if phone_number.type == addressbook_pb2.Person.MOBILE: print " Mobile phone #:", elif phone_number.type == addressbook_pb2.Person.HOME: print " Home phone #:", elif phone_number.type == addressbook_pb2.Person.WORK: print " Work phone #:", print phone_number.number # Main procedure: Reads the entire address book from a file and prints all # the information inside. if len(sys.argv) != 2: print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE" sys.exit(-1) address_book = addressbook_pb2.AddressBook() # Read the existing address book. f = open(sys.argv[1], "rb") address_book.ParseFromString(f.read()) f.close() ListPeople(address_book)
Make Python example output identical to C++ and Java by removing redundant spaces.
Make Python example output identical to C++ and Java by removing redundant spaces.
Python
bsd-3-clause
malthe/google-protobuf,malthe/google-protobuf,malthe/google-protobuf,malthe/google-protobuf,malthe/google-protobuf
8de8da05bb9461aaa48d3058f5b1e2caab6191f1
openmath/xml.py
openmath/xml.py
from . import openmath as om openmath_ns = "http://www.openmath.org/OpenMath" omtags = { "OMOBJ": om.OMObject, "OMR": om.OMReference, "OMI": om.OMInteger, "OMF": om.OMFloat, "OMSTR": om.OMString, "OMB": om.OMBytes, "OMS": om.OMSymbol, "OMV": om.OMVariable, "OMFOREIGN": om.OMForeign, "OMA": om.OMApplication, "OMATTR": om.OMAttribution, "OMATP": om.OMAttributionPairs, "OMBIND": om.OMBinding, "OMBVAR": om.OMBindVariables, "OME": om.OMError } inv_omtags = {(v,k) for k,v in omtags.items()} def tag_to_object(tag, ns=True): if ns and not tag.startswith('{%s}' % openmath_ns): raise ValueError('Invalid namespace') return omtags[tag.split('}')[-1]] def object_to_tag(obj, ns=True): tpl = '{%(ns)s}%(tag)s' if ns else '%(tag)s' return tpl % { "ns": openmath_ns, "tag": inv_omtags(obj) }
from . import openmath as om openmath_ns = "http://www.openmath.org/OpenMath" omtags = { "OMOBJ": om.OMObject, "OMR": om.OMReference, "OMI": om.OMInteger, "OMF": om.OMFloat, "OMSTR": om.OMString, "OMB": om.OMBytes, "OMS": om.OMSymbol, "OMV": om.OMVariable, "OMFOREIGN": om.OMForeign, "OMA": om.OMApplication, "OMATTR": om.OMAttribution, "OMATP": om.OMAttributionPairs, "OMBIND": om.OMBinding, "OMBVAR": om.OMBindVariables, "OME": om.OMError } inv_omtags = dict((v,k) for k,v in omtags.items()) def tag_to_object(tag, ns=True): if ns and not tag.startswith('{%s}' % openmath_ns): raise ValueError('Invalid namespace') return omtags[tag.split('}')[-1]] def object_to_tag(obj, ns=True): tpl = '{%(ns)s}%(tag)s' if ns else '%(tag)s' return tpl % { "ns": openmath_ns, "tag": inv_omtags(obj) }
Use dict() syntax that works in Python 2.6 onward
Use dict() syntax that works in Python 2.6 onward
Python
mit
OpenMath/py-openmath
ab4ae040895c50da6cb0827f6461d1733c7fe30a
tests/test_plugin_states.py
tests/test_plugin_states.py
from contextlib import contextmanager from os import path from unittest import TestCase from canaryd_packages import six from dictdiffer import diff from jsontest import JsonTest from mock import patch from canaryd.plugin import get_plugin_by_name @six.add_metaclass(JsonTest) class TestPluginStates(TestCase): jsontest_files = path.join('tests/plugins') @contextmanager def patch_commands(self, commands): def handle_command(command, *args, **kwargs): command = command[0] if command not in commands: raise ValueError( 'Broken tests: {0} not in commands'.format(command), ) return '\n'.join(commands[command]) check_output_patch = patch( 'canaryd.subprocess.check_output', handle_command, ) check_output_patch.start() yield check_output_patch.stop() def jsontest_function(self, test_name, test_data): plugin = get_plugin_by_name(test_data['plugin']) with self.patch_commands(test_data['commands']): state = plugin.get_state({}) try: self.assertEqual(state, test_data['state']) except AssertionError: print(list(diff(test_data['state'], state))) raise
from contextlib import contextmanager from os import path from unittest import TestCase from dictdiffer import diff from jsontest import JsonTest from mock import patch from canaryd_packages import six from canaryd.plugin import get_plugin_by_name class TestPluginRealStates(TestCase): def run_plugin(self, plugin_name): plugin = get_plugin_by_name(plugin_name) plugin.get_state({}) def test_meta_plugin(self): self.run_plugin('meta') def test_services_plugin(self): self.run_plugin('services') def test_containers_plugin(self): self.run_plugin('containers') @six.add_metaclass(JsonTest) class TestPluginStates(TestCase): jsontest_files = path.join('tests/plugins') @contextmanager def patch_commands(self, commands): def handle_command(command, *args, **kwargs): command = command[0] if command not in commands: raise ValueError('Broken tests: {0} not in commands: {1}'.format( command, commands.keys(), )) return '\n'.join(commands[command]) check_output_patch = patch( 'canaryd.subprocess.check_output', handle_command, ) check_output_patch.start() yield check_output_patch.stop() def jsontest_function(self, test_name, test_data): plugin = get_plugin_by_name(test_data['plugin']) with self.patch_commands(test_data['commands']): state = plugin.get_state({}) try: self.assertEqual(state, test_data['state']) except AssertionError: print(list(diff(test_data['state'], state))) raise
Add real plugin state tests for plugins that always work (meta, containers, services).
Add real plugin state tests for plugins that always work (meta, containers, services).
Python
mit
Oxygem/canaryd,Oxygem/canaryd
94a91f128b046a818acb873579c8aadd41aa5c3a
test/streamparse/cli/test_sparse.py
test/streamparse/cli/test_sparse.py
from __future__ import absolute_import, unicode_literals import argparse import unittest from streamparse.cli import sparse from nose.tools import ok_ class SparseTestCase(unittest.TestCase): def test_load_subparsers(self): parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() sparse.load_suparsers(subparsers) # grab subcommands from subparsers subcommands = parser._optionals._actions[1].choices.keys() # we know quickstart will be a subcommand test others as needed ok_('quickstart' in subcommands) if __name__ == '__main__': unittest.main()
from __future__ import absolute_import, unicode_literals import argparse import unittest from streamparse.cli import sparse from nose.tools import ok_ class SparseTestCase(unittest.TestCase): def test_load_subparsers(self): parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() sparse.load_subparsers(subparsers) # grab subcommands from subparsers subcommands = parser._optionals._actions[1].choices.keys() # we know quickstart will be a subcommand test others as needed ok_('quickstart' in subcommands) if __name__ == '__main__': unittest.main()
Fix remaining load_suparsers typo instance
Fix remaining load_suparsers typo instance
Python
apache-2.0
msmakhlouf/streamparse,codywilbourn/streamparse,petchat/streamparse,petchat/streamparse,Parsely/streamparse,msmakhlouf/streamparse,petchat/streamparse,petchat/streamparse,msmakhlouf/streamparse,msmakhlouf/streamparse,codywilbourn/streamparse,eric7j/streamparse,petchat/streamparse,crohling/streamparse,hodgesds/streamparse,msmakhlouf/streamparse,hodgesds/streamparse,phanib4u/streamparse,Parsely/streamparse,eric7j/streamparse,crohling/streamparse,phanib4u/streamparse
26dcd1ce43864de77c1cd26065c09cc2b4c4788e
tests/fuzzer/test_random_content.py
tests/fuzzer/test_random_content.py
# Copyright (c) 2016 Renata Hodovan, Akos Kiss. # # Licensed under the BSD 3-Clause License # <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>. # This file may not be copied, modified, or distributed except # according to those terms. import pytest import fuzzinator @pytest.mark.parametrize('fuzzer_kwargs, exp_min_len, exp_max_len', [ ({}, 1, 1), ({'max_length': '100'}, 1, 100), ({'min_length': '10', 'max_length': '100'}, 10, 100), ]) def test_random_content(fuzzer_kwargs, exp_min_len, exp_max_len): for index in range(100): out = fuzzinator.fuzzer.RandomContent(index=index, **fuzzer_kwargs) out_len = len(out) assert out_len >= exp_min_len and out_len <= exp_max_len
# Copyright (c) 2016-2021 Renata Hodovan, Akos Kiss. # # Licensed under the BSD 3-Clause License # <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>. # This file may not be copied, modified, or distributed except # according to those terms. import pytest import fuzzinator @pytest.mark.parametrize('fuzzer_kwargs, exp_min_len, exp_max_len', [ ({}, 1, 1), ({'max_length': '100'}, 1, 100), ({'min_length': '10', 'max_length': '100'}, 10, 100), ]) def test_random_content(fuzzer_kwargs, exp_min_len, exp_max_len): for index in range(100): out = fuzzinator.fuzzer.RandomContent(index=index, **fuzzer_kwargs) out_len = len(out) assert exp_min_len <= out_len <= exp_max_len
Make use of chained comparisons
Make use of chained comparisons
Python
bsd-3-clause
akosthekiss/fuzzinator,akosthekiss/fuzzinator,akosthekiss/fuzzinator,renatahodovan/fuzzinator,renatahodovan/fuzzinator,renatahodovan/fuzzinator,akosthekiss/fuzzinator,renatahodovan/fuzzinator
c79cedf826a3b6ee89e6186954185ef3217dd901
tomviz/python/InvertData.py
tomviz/python/InvertData.py
import tomviz.operators NUMBER_OF_CHUNKS = 10 class InvertOperator(tomviz.operators.CancelableOperator): def transform_scalars(self, dataset): from tomviz import utils import numpy as np self.progress.maximum = NUMBER_OF_CHUNKS scalars = utils.get_scalars(dataset) if scalars is None: raise RuntimeError("No scalars found!") result = np.float32(scalars) max = np.amax(scalars) step = 0 for chunk in np.array_split(result, NUMBER_OF_CHUNKS): if self.canceled: return chunk[:] = max - chunk step += 1 self.progress.value = step utils.set_scalars(dataset, result)
import tomviz.operators NUMBER_OF_CHUNKS = 10 class InvertOperator(tomviz.operators.CancelableOperator): def transform_scalars(self, dataset): from tomviz import utils import numpy as np self.progress.maximum = NUMBER_OF_CHUNKS scalars = utils.get_scalars(dataset) if scalars is None: raise RuntimeError("No scalars found!") result = np.float32(scalars) min = np.amin(scalars) max = np.amax(scalars) step = 0 for chunk in np.array_split(result, NUMBER_OF_CHUNKS): if self.canceled: return chunk[:] = max - chunk + min step += 1 self.progress.value = step utils.set_scalars(dataset, result)
Add the minimum scalar value to the result of the InvertOperator
Add the minimum scalar value to the result of the InvertOperator Without it, all results would be shifted so the minimum was 0.
Python
bsd-3-clause
OpenChemistry/tomviz,mathturtle/tomviz,OpenChemistry/tomviz,mathturtle/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz,mathturtle/tomviz
47053a42b9053755aad052159dac845b34195297
config/test/__init__.py
config/test/__init__.py
from SCons.Script import * def run_tests(env): import shlex import subprocess import sys cmd = shlex.split(env.get('TEST_COMMAND')) print('Executing:', cmd) sys.exit(subprocess.call(cmd)) def generate(env): import os import distutils.spawn python = distutils.spawn.find_executable('python3') if not python: python = distutils.spawn.find_executable('python') if not python: python = distutils.spawn.find_executable('python2') if not python: python = 'python' if env['PLATFORM'] == 'win32': python = python.replace('\\', '\\\\') cmd = python + ' tests/testHarness -C tests --diff-failed --view-failed ' \ '--view-unfiltered --save-failed --build' if 'DOCKBOT_MASTER_PORT' in os.environ: cmd += ' --no-color' env.CBAddVariables(('TEST_COMMAND', '`test` target command line', cmd)) if 'test' in COMMAND_LINE_TARGETS: env.CBAddConfigureCB(run_tests) def exists(): return 1
from SCons.Script import * import inspect def run_tests(env): import shlex import subprocess import sys cmd = shlex.split(env.get('TEST_COMMAND')) print('Executing:', cmd) sys.exit(subprocess.call(cmd)) def generate(env): import os import distutils.spawn python = distutils.spawn.find_executable('python3') if not python: python = distutils.spawn.find_executable('python') if not python: python = distutils.spawn.find_executable('python2') if not python: python = 'python' if env['PLATFORM'] == 'win32': python = python.replace('\\', '\\\\') path = inspect.getfile(inspect.currentframe()) home = os.path.dirname(os.path.abspath(path)) + '/../..' cmd = python + ' ' + home + '/tests/testHarness -C tests --diff-failed ' \ '--view-failed --view-unfiltered --save-failed --build' if 'DOCKBOT_MASTER_PORT' in os.environ: cmd += ' --no-color' env.CBAddVariables(('TEST_COMMAND', '`test` target command line', cmd)) if 'test' in COMMAND_LINE_TARGETS: env.CBAddConfigureCB(run_tests) def exists(): return 1
Use common testHarness in derived projects
Use common testHarness in derived projects
Python
lgpl-2.1
CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang
37831f549eddc014ab89cc7dba3616a133c774a2
api/BucketListAPI.py
api/BucketListAPI.py
from flask import Flask, jsonify from modals.modals import User, Bucket, Item from api.__init__ import app, db @app.errorhandler(404) def page_not_found(e): response = jsonify({'error': 'The request can not be completed'}) response.status_code = 404 return response if __name__ == '__main__': app.run()
from flask import Flask, jsonify from modals.modals import User, Bucket, Item from api.__init__ import create_app, db app = create_app('DevelopmentEnv') @app.errorhandler(404) def page_not_found(e): response = jsonify({'error': 'The request can not be completed'}) response.status_code = 404 return response if __name__ == '__main__': app.run()
Add create_app method to __init__.py
Add create_app method to __init__.py
Python
mit
patlub/BucketListAPI,patlub/BucketListAPI
ffa8f79fe15621081acbb220a2a4dfd3d4d6d500
galton/utils/logger.py
galton/utils/logger.py
# -*- coding: utf-8 -*- import os import os.path as op import yaml import logging.config from .text_files import read from ..config import LOG_LEVEL MODULE_NAME = __name__.split('.')[0] def setup_logging(log_config_file=op.join(op.dirname(__file__), 'logger.yml'), log_default_level=LOG_LEVEL, env_key=MODULE_NAME + '_LOG_CFG'): """Setup logging configuration.""" path = log_config_file value = os.getenv(env_key, None) if value: path = value if op.exists(path): log_cfg = yaml.load(read(path).format(MODULE_NAME)) logging.config.dictConfig(log_cfg) #print('Started logging using config file {0}.'.format(path)) else: logging.basicConfig(level=log_default_level) #print('Started default logging. Could not find config file ' # 'in {0}.'.format(path)) log = logging.getLogger(__name__) log.debug('Start logging.')
# -*- coding: utf-8 -*- import os import os.path as op import yaml import logging.config from .text_files import read from ..config import LOG_LEVEL MODULE_NAME = __name__.split('.')[0] def setup_logging(log_config_file=op.join(op.dirname(__file__), 'logger.yml'), log_default_level=LOG_LEVEL, env_key=MODULE_NAME.upper() + '_LOG_CFG'): """Setup logging configuration.""" path = log_config_file value = os.getenv(env_key, None) if value: path = value if op.exists(path): log_cfg = yaml.load(read(path).format(MODULE_NAME)) logging.config.dictConfig(log_cfg) #print('Started logging using config file {0}.'.format(path)) else: logging.basicConfig(level=log_default_level) #print('Started default logging. Could not find config file ' # 'in {0}.'.format(path)) log = logging.getLogger(__name__) log.debug('Start logging.')
Correct env_key input argument default value
Correct env_key input argument default value
Python
bsd-3-clause
Neurita/galton
554572f327e4b9c920f65b416bfc6a3a5b549846
numba/tests/npyufunc/test_parallel_env_variable.py
numba/tests/npyufunc/test_parallel_env_variable.py
from numba.np.ufunc.parallel import get_thread_count from os import environ as env from numba.core import config import unittest class TestParallelEnvVariable(unittest.TestCase): """ Tests environment variables related to the underlying "parallel" functions for npyufuncs. """ _numba_parallel_test_ = False def test_num_threads_variable(self): """ Tests the NUMBA_NUM_THREADS env variable behaves as expected. """ key = 'NUMBA_NUM_THREADS' current = str(getattr(env, key, config.NUMBA_DEFAULT_NUM_THREADS)) threads = "3154" env[key] = threads try: config.reload_config() except RuntimeError as e: # This test should fail if threads have already been launched self.assertIn("Cannot set NUMBA_NUM_THREADS", e.args[0]) else: self.assertEqual(threads, str(get_thread_count())) self.assertEqual(threads, str(config.NUMBA_NUM_THREADS)) finally: # reset the env variable/set to default. Should not fail even if # threads are launched because the value is the same. env[key] = current config.reload_config() if __name__ == '__main__': unittest.main()
from numba.np.ufunc.parallel import get_thread_count from os import environ as env from numba.core import config import unittest class TestParallelEnvVariable(unittest.TestCase): """ Tests environment variables related to the underlying "parallel" functions for npyufuncs. """ _numba_parallel_test_ = False def test_num_threads_variable(self): """ Tests the NUMBA_NUM_THREADS env variable behaves as expected. """ key = 'NUMBA_NUM_THREADS' current = str(getattr(env, key, config.NUMBA_NUM_THREADS)) threads = "3154" env[key] = threads try: config.reload_config() except RuntimeError as e: # This test should fail if threads have already been launched self.assertIn("Cannot set NUMBA_NUM_THREADS", e.args[0]) else: self.assertEqual(threads, str(get_thread_count())) self.assertEqual(threads, str(config.NUMBA_NUM_THREADS)) finally: # reset the env variable/set to default. Should not fail even if # threads are launched because the value is the same. env[key] = current config.reload_config() if __name__ == '__main__': unittest.main()
Reset the num threads to the env variable, not the default
Reset the num threads to the env variable, not the default
Python
bsd-2-clause
numba/numba,stonebig/numba,cpcloud/numba,gmarkall/numba,sklam/numba,stuartarchibald/numba,seibert/numba,seibert/numba,cpcloud/numba,numba/numba,sklam/numba,IntelLabs/numba,stuartarchibald/numba,IntelLabs/numba,IntelLabs/numba,gmarkall/numba,cpcloud/numba,seibert/numba,stuartarchibald/numba,numba/numba,sklam/numba,seibert/numba,gmarkall/numba,seibert/numba,stuartarchibald/numba,cpcloud/numba,numba/numba,gmarkall/numba,cpcloud/numba,IntelLabs/numba,numba/numba,stonebig/numba,stonebig/numba,stuartarchibald/numba,stonebig/numba,IntelLabs/numba,sklam/numba,stonebig/numba,gmarkall/numba,sklam/numba
4b5dd61607c9692bb330f89545d5f76d7a1ed221
puzzle/feeds.py
puzzle/feeds.py
""" Generate an RSS feed of published crosswords from staff users. Uses the built-in feed framework. There's no attempt to send the actual crossword, it's just a message indicating that a new one is available. """ from django.contrib.syndication.views import Feed from django.urls import reverse from django.utils import timezone from puzzle.models import Puzzle class PuzzleFeed(Feed): """RSS feed of new puzzles from the staff.""" #pylint: disable=no-self-use,missing-docstring title = 'Three Pins' link = 'http://www.threepins.org' description = 'A cryptic crossword outlet.' def items(self): return Puzzle.objects.filter(user__is_staff=True, pub_date__lte=timezone.now()).order_by('-pub_date')[:5] def item_title(self, item): return 'Crossword #' + str(item.number) def item_description(self, item): return 'Crossword #' + str(item.number) + ' is now available.' def item_link(self, item): return reverse('puzzle', args=[item.number]) def item_pubdate(self, item): return item.pub_date
""" Generate an RSS feed of published crosswords from staff users. Uses the built-in feed framework. There's no attempt to send the actual crossword, it's just a message indicating that a new one is available. """ from django.contrib.syndication.views import Feed from django.urls import reverse from django.utils import timezone from puzzle.models import Puzzle class PuzzleFeed(Feed): """RSS feed of new puzzles from the staff.""" #pylint: disable=no-self-use,missing-docstring title = 'Three Pins' link = 'http://www.threepins.org' description = 'A cryptic crossword outlet.' def items(self): return Puzzle.objects.filter(user__is_staff=True, pub_date__lte=timezone.now()).order_by('-pub_date')[:5] def item_title(self, item): return 'Crossword #' + str(item.number) def item_description(self, item): return 'Crossword #' + str(item.number) + ' is now available.' def item_link(self, item): return reverse('puzzle', kwargs={'author': item.user.username, 'number': item.number}) def item_pubdate(self, item): return item.pub_date
Fix linkage in the RSS feed
Fix linkage in the RSS feed
Python
mit
jomoore/threepins,jomoore/threepins,jomoore/threepins
a0ceb84519d1bf735979b3afdfdb8b17621d308b
froide/problem/admin.py
froide/problem/admin.py
from django.contrib import admin from django.utils.html import format_html from django.urls import reverse from django.utils.translation import gettext_lazy as _ from froide.helper.admin_utils import make_nullfilter from .models import ProblemReport class ProblemReportAdmin(admin.ModelAdmin): date_hierarchy = 'timestamp' raw_id_fields = ('message', 'user', 'moderator') list_filter = ( 'auto_submitted', 'resolved', 'kind', make_nullfilter('claimed', _('Claimed')), make_nullfilter('escalated', _('Escalated')), ) list_display = ( 'kind', 'timestamp', 'admin_link_message', 'auto_submitted', 'resolved', ) def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.select_related('message') return qs def admin_link_message(self, obj): return format_html('<a href="{}">{}</a>', reverse('admin:foirequest_foimessage_change', args=(obj.message_id,)), str(obj.message)) def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) if 'resolved' in form.changed_data and obj.resolved: sent = obj.resolve(request.user) if sent: self.message_user( request, _('User will be notified of resolution') ) admin.site.register(ProblemReport, ProblemReportAdmin)
from django.contrib import admin from django.utils.html import format_html from django.urls import reverse from django.utils.translation import gettext_lazy as _ from froide.helper.admin_utils import make_nullfilter from .models import ProblemReport class ProblemReportAdmin(admin.ModelAdmin): date_hierarchy = 'timestamp' raw_id_fields = ('message', 'user', 'moderator') list_filter = ( 'auto_submitted', 'resolved', 'kind', make_nullfilter('claimed', _('Claimed')), make_nullfilter('escalated', _('Escalated')), ) list_display = ( 'kind', 'timestamp', 'admin_link_message', 'auto_submitted', 'resolved', ) def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.select_related('message') return qs def admin_link_message(self, obj): return format_html('<a href="{}">{}</a>', reverse('admin:foirequest_foimessage_change', args=(obj.message_id,)), str(obj.message)) def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) if 'resolved' in form.changed_data and obj.resolved: sent = obj.resolve(request.user, resolution=obj.resolution) if sent: self.message_user( request, _('User will be notified of resolution') ) admin.site.register(ProblemReport, ProblemReportAdmin)
Fix overwriting resolution with empty text
Fix overwriting resolution with empty text
Python
mit
stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide
1171ade137c54c778a284ef32fdbdcd9e5c1d828
runcommands/runners/result.py
runcommands/runners/result.py
from ..util import cached_property class Result: def __init__(self, return_code, stdout_data, stderr_data, encoding): self.return_code = return_code self.stdout_data = stdout_data self.stderr_data = stderr_data self.encoding = encoding self.succeeded = self.return_code == 0 self.failed = not self.succeeded @cached_property def stdout(self): if self.stdout_data: stdout = b''.join(self.stdout_data) stdout = stdout.decode(self.encoding) else: stdout = '' return stdout @cached_property def stderr(self): if self.stderr_data: stderr = b''.join(self.stderr_data) stderr = stderr.decode(self.encoding) else: stderr = '' return stderr @cached_property def stdout_lines(self): return self.stdout.splitlines() if self.stdout else [] @cached_property def stderr_lines(self): return self.stderr.splitlines() if self.stderr else [] def __bool__(self): return self.succeeded
from ..util import cached_property class Result: def __init__(self, return_code, stdout_data, stderr_data, encoding): self.return_code = return_code self.stdout_data = stdout_data self.stderr_data = stderr_data self.encoding = encoding self.succeeded = self.return_code == 0 self.failed = not self.succeeded @cached_property def stdout(self): if self.stdout_data: stdout = b''.join(self.stdout_data) stdout = stdout.decode(self.encoding) else: stdout = '' return stdout @cached_property def stderr(self): if self.stderr_data: stderr = b''.join(self.stderr_data) stderr = stderr.decode(self.encoding) else: stderr = '' return stderr @cached_property def stdout_lines(self): return self.stdout.splitlines() if self.stdout else [] @cached_property def stderr_lines(self): return self.stderr.splitlines() if self.stderr else [] def __bool__(self): return self.succeeded def __str__(self): return self.stdout def __repr__(self): return repr(self.stdout)
Add __repr__() and __str__() to Result
Add __repr__() and __str__() to Result
Python
mit
wylee/runcommands,wylee/runcommands
ed45c8201977aecde226b2e9b060820a8fd677c3
test/functional/rpc_deprecated.py
test/functional/rpc_deprecated.py
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_raises_rpc_error class DeprecatedRpcTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = True self.extra_args = [[], ["-deprecatedrpc=createmultisig"]] def run_test(self): self.log.info("Make sure that -deprecatedrpc=createmultisig allows it to take addresses") assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, [self.nodes[0].getnewaddress()]) self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()]) if __name__ == '__main__': DeprecatedRpcTest().main()
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework class DeprecatedRpcTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = True self.extra_args = [[], []] def run_test(self): # This test should be used to verify correct behaviour of deprecated # RPC methods with and without the -deprecatedrpc flags. For example: # # self.log.info("Make sure that -deprecatedrpc=createmultisig allows it to take addresses") # assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, [self.nodes[0].getnewaddress()]) # self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()]) # # There are currently no deprecated RPC methods in master, so this # test is currently empty. pass if __name__ == '__main__': DeprecatedRpcTest().main()
Remove test for deprecated createmultsig option
[tests] Remove test for deprecated createmultsig option
Python
mit
guncoin/guncoin,AkioNak/bitcoin,tjps/bitcoin,myriadteam/myriadcoin,tjps/bitcoin,tecnovert/particl-core,vmp32k/litecoin,jamesob/bitcoin,achow101/bitcoin,jtimon/bitcoin,particl/particl-core,DigitalPandacoin/pandacoin,MarcoFalke/bitcoin,kazcw/bitcoin,cdecker/bitcoin,andreaskern/bitcoin,paveljanik/bitcoin,Kogser/bitcoin,andreaskern/bitcoin,Flowdalic/bitcoin,ericshawlinux/bitcoin,guncoin/guncoin,ElementsProject/elements,jambolo/bitcoin,MeshCollider/bitcoin,DigitalPandacoin/pandacoin,dscotese/bitcoin,yenliangl/bitcoin,BTCGPU/BTCGPU,EthanHeilman/bitcoin,qtumproject/qtum,Kogser/bitcoin,guncoin/guncoin,Xekyo/bitcoin,sstone/bitcoin,nikkitan/bitcoin,domob1812/namecore,pataquets/namecoin-core,fujicoin/fujicoin,thrasher-/litecoin,domob1812/namecore,yenliangl/bitcoin,n1bor/bitcoin,CryptArc/bitcoin,jtimon/bitcoin,midnightmagic/bitcoin,jtimon/bitcoin,kallewoof/bitcoin,r8921039/bitcoin,sstone/bitcoin,DigitalPandacoin/pandacoin,GlobalBoost/GlobalBoost,afk11/bitcoin,joshrabinowitz/bitcoin,ahmedbodi/vertcoin,h4x3rotab/BTCGPU,OmniLayer/omnicore,Kogser/bitcoin,midnightmagic/bitcoin,Christewart/bitcoin,Sjors/bitcoin,lateminer/bitcoin,bitcoin/bitcoin,fujicoin/fujicoin,midnightmagic/bitcoin,prusnak/bitcoin,anditto/bitcoin,Xekyo/bitcoin,jnewbery/bitcoin,litecoin-project/litecoin,RHavar/bitcoin,digibyte/digibyte,cdecker/bitcoin,fanquake/bitcoin,jtimon/bitcoin,TheBlueMatt/bitcoin,untrustbank/litecoin,ElementsProject/elements,domob1812/bitcoin,fanquake/bitcoin,AkioNak/bitcoin,domob1812/bitcoin,JeremyRubin/bitcoin,GlobalBoost/GlobalBoost,fujicoin/fujicoin,mm-s/bitcoin,bitcoinsSG/bitcoin,namecoin/namecore,mitchellcash/bitcoin,rnicoll/bitcoin,nikkitan/bitcoin,EthanHeilman/bitcoin,vertcoin/vertcoin,gjhiggins/vcoincore,lateminer/bitcoin,tjps/bitcoin,GroestlCoin/bitcoin,litecoin-project/litecoin,bitcoinknots/bitcoin,jonasschnelli/bitcoin,untrustbank/litecoin,kallewoof/bitcoin,mitchellcash/bitcoin,afk11/bitcoin,jtimon/bitcoin,thrasher-/litecoin,jonasschnelli/bitcoin,Flowdalic/bitcoin,JeremyRubin/bitcoin,h4x3rotab/BTCGPU,prusnak/bitcoin,cdecker/bitcoin,achow101/bitcoin,CryptArc/bitcoin,paveljanik/bitcoin,jnewbery/bitcoin,namecoin/namecoin-core,jlopp/statoshi,jmcorgan/bitcoin,apoelstra/bitcoin,bitcoinknots/bitcoin,MarcoFalke/bitcoin,tecnovert/particl-core,bitcoinsSG/bitcoin,rawodb/bitcoin,bitcoin/bitcoin,peercoin/peercoin,jlopp/statoshi,kallewoof/bitcoin,domob1812/huntercore,ahmedbodi/vertcoin,r8921039/bitcoin,jlopp/statoshi,Bushstar/UFO-Project,DigitalPandacoin/pandacoin,domob1812/huntercore,thrasher-/litecoin,bespike/litecoin,jmcorgan/bitcoin,myriadcoin/myriadcoin,MarcoFalke/bitcoin,Christewart/bitcoin,jnewbery/bitcoin,vmp32k/litecoin,jonasschnelli/bitcoin,kazcw/bitcoin,guncoin/guncoin,paveljanik/bitcoin,midnightmagic/bitcoin,droark/bitcoin,globaltoken/globaltoken,bitcoinsSG/bitcoin,practicalswift/bitcoin,Christewart/bitcoin,jambolo/bitcoin,n1bor/bitcoin,guncoin/guncoin,paveljanik/bitcoin,bitcoin/bitcoin,sstone/bitcoin,GroestlCoin/GroestlCoin,fanquake/bitcoin,mruddy/bitcoin,stamhe/bitcoin,jtimon/bitcoin,RHavar/bitcoin,domob1812/huntercore,h4x3rotab/BTCGPU,kazcw/bitcoin,vmp32k/litecoin,rnicoll/dogecoin,joshrabinowitz/bitcoin,AkioNak/bitcoin,lbryio/lbrycrd,achow101/bitcoin,practicalswift/bitcoin,instagibbs/bitcoin,GroestlCoin/bitcoin,tecnovert/particl-core,sebrandon1/bitcoin,rnicoll/dogecoin,domob1812/bitcoin,nikkitan/bitcoin,CryptArc/bitcoin,OmniLayer/omnicore,bespike/litecoin,mm-s/bitcoin,wellenreiter01/Feathercoin,TheBlueMatt/bitcoin,ahmedbodi/vertcoin,monacoinproject/monacoin,Sjors/bitcoin,OmniLayer/omnicore,FeatherCoin/Feathercoin,Kogser/bitcoin,JeremyRubin/bitcoin,jambolo/bitcoin,domob1812/namecore,domob1812/namecore,monacoinproject/monacoin,donaloconnor/bitcoin,h4x3rotab/BTCGPU,namecoin/namecoin-core,wellenreiter01/Feathercoin,n1bor/bitcoin,lbryio/lbrycrd,pstratem/bitcoin,fujicoin/fujicoin,peercoin/peercoin,BTCGPU/BTCGPU,myriadteam/myriadcoin,n1bor/bitcoin,sipsorcery/bitcoin,afk11/bitcoin,TheBlueMatt/bitcoin,myriadcoin/myriadcoin,lateminer/bitcoin,ericshawlinux/bitcoin,bespike/litecoin,gjhiggins/vcoincore,domob1812/bitcoin,qtumproject/qtum,tecnovert/particl-core,namecoin/namecoin-core,vertcoin/vertcoin,bespike/litecoin,lateminer/bitcoin,qtumproject/qtum,myriadteam/myriadcoin,afk11/bitcoin,GroestlCoin/bitcoin,peercoin/peercoin,randy-waterhouse/bitcoin,GlobalBoost/GlobalBoost,pstratem/bitcoin,donaloconnor/bitcoin,paveljanik/bitcoin,mm-s/bitcoin,stamhe/bitcoin,FeatherCoin/Feathercoin,pstratem/bitcoin,ajtowns/bitcoin,EthanHeilman/bitcoin,tjps/bitcoin,digibyte/digibyte,GlobalBoost/GlobalBoost,RHavar/bitcoin,jamesob/bitcoin,midnightmagic/bitcoin,joshrabinowitz/bitcoin,rawodb/bitcoin,mitchellcash/bitcoin,CryptArc/bitcoin,JeremyRubin/bitcoin,OmniLayer/omnicore,lbryio/lbrycrd,yenliangl/bitcoin,jmcorgan/bitcoin,untrustbank/litecoin,dscotese/bitcoin,bitcoinsSG/bitcoin,fujicoin/fujicoin,namecoin/namecore,litecoin-project/litecoin,myriadcoin/myriadcoin,alecalve/bitcoin,untrustbank/litecoin,prusnak/bitcoin,TheBlueMatt/bitcoin,mruddy/bitcoin,myriadteam/myriadcoin,alecalve/bitcoin,dscotese/bitcoin,practicalswift/bitcoin,ryanofsky/bitcoin,FeatherCoin/Feathercoin,lbryio/lbrycrd,OmniLayer/omnicore,GlobalBoost/GlobalBoost,vertcoin/vertcoin,Flowdalic/bitcoin,kallewoof/bitcoin,digibyte/digibyte,MarcoFalke/bitcoin,andreaskern/bitcoin,domob1812/huntercore,tjps/bitcoin,n1bor/bitcoin,sstone/bitcoin,fanquake/bitcoin,bitcoinknots/bitcoin,afk11/bitcoin,digibyte/digibyte,Kogser/bitcoin,pstratem/bitcoin,sebrandon1/bitcoin,domob1812/bitcoin,gjhiggins/vcoincore,thrasher-/litecoin,Bushstar/UFO-Project,ahmedbodi/vertcoin,MarcoFalke/bitcoin,ahmedbodi/vertcoin,ajtowns/bitcoin,rnicoll/bitcoin,Bushstar/UFO-Project,litecoin-project/litecoin,yenliangl/bitcoin,lbryio/lbrycrd,achow101/bitcoin,ajtowns/bitcoin,MeshCollider/bitcoin,Flowdalic/bitcoin,MeshCollider/bitcoin,pataquets/namecoin-core,mitchellcash/bitcoin,nikkitan/bitcoin,qtumproject/qtum,particl/particl-core,tjps/bitcoin,vertcoin/vertcoin,Christewart/bitcoin,untrustbank/litecoin,CryptArc/bitcoin,monacoinproject/monacoin,AkioNak/bitcoin,jlopp/statoshi,Sjors/bitcoin,namecoin/namecore,kazcw/bitcoin,droark/bitcoin,bitcoin/bitcoin,Kogser/bitcoin,vmp32k/litecoin,Kogser/bitcoin,thrasher-/litecoin,EthanHeilman/bitcoin,droark/bitcoin,sipsorcery/bitcoin,cdecker/bitcoin,randy-waterhouse/bitcoin,jnewbery/bitcoin,andreaskern/bitcoin,jamesob/bitcoin,andreaskern/bitcoin,ajtowns/bitcoin,randy-waterhouse/bitcoin,rnicoll/bitcoin,GroestlCoin/GroestlCoin,lateminer/bitcoin,jambolo/bitcoin,h4x3rotab/BTCGPU,myriadcoin/myriadcoin,jmcorgan/bitcoin,TheBlueMatt/bitcoin,sipsorcery/bitcoin,particl/particl-core,bespike/litecoin,ryanofsky/bitcoin,achow101/bitcoin,Christewart/bitcoin,EthanHeilman/bitcoin,Kogser/bitcoin,namecoin/namecore,mitchellcash/bitcoin,monacoinproject/monacoin,peercoin/peercoin,globaltoken/globaltoken,particl/particl-core,donaloconnor/bitcoin,namecoin/namecore,GroestlCoin/GroestlCoin,instagibbs/bitcoin,fujicoin/fujicoin,namecoin/namecoin-core,apoelstra/bitcoin,pataquets/namecoin-core,GroestlCoin/bitcoin,namecoin/namecore,donaloconnor/bitcoin,practicalswift/bitcoin,jambolo/bitcoin,sipsorcery/bitcoin,instagibbs/bitcoin,gjhiggins/vcoincore,Christewart/bitcoin,nikkitan/bitcoin,vertcoin/vertcoin,r8921039/bitcoin,globaltoken/globaltoken,apoelstra/bitcoin,myriadcoin/myriadcoin,EthanHeilman/bitcoin,myriadteam/myriadcoin,particl/particl-core,vmp32k/litecoin,stamhe/bitcoin,GroestlCoin/bitcoin,cdecker/bitcoin,jnewbery/bitcoin,ericshawlinux/bitcoin,r8921039/bitcoin,practicalswift/bitcoin,MeshCollider/bitcoin,qtumproject/qtum,ElementsProject/elements,bitcoin/bitcoin,jmcorgan/bitcoin,jamesob/bitcoin,mruddy/bitcoin,DigitalPandacoin/pandacoin,joshrabinowitz/bitcoin,rawodb/bitcoin,OmniLayer/omnicore,vmp32k/litecoin,particl/particl-core,monacoinproject/monacoin,DigitalPandacoin/pandacoin,gjhiggins/vcoincore,randy-waterhouse/bitcoin,RHavar/bitcoin,rawodb/bitcoin,wellenreiter01/Feathercoin,peercoin/peercoin,wellenreiter01/Feathercoin,globaltoken/globaltoken,Xekyo/bitcoin,ryanofsky/bitcoin,andreaskern/bitcoin,peercoin/peercoin,fanquake/bitcoin,rnicoll/dogecoin,bespike/litecoin,namecoin/namecoin-core,r8921039/bitcoin,myriadcoin/myriadcoin,droark/bitcoin,donaloconnor/bitcoin,kazcw/bitcoin,instagibbs/bitcoin,paveljanik/bitcoin,globaltoken/globaltoken,midnightmagic/bitcoin,mitchellcash/bitcoin,Kogser/bitcoin,bitcoin/bitcoin,ahmedbodi/vertcoin,sstone/bitcoin,achow101/bitcoin,randy-waterhouse/bitcoin,TheBlueMatt/bitcoin,rawodb/bitcoin,rnicoll/bitcoin,anditto/bitcoin,Sjors/bitcoin,apoelstra/bitcoin,jonasschnelli/bitcoin,pataquets/namecoin-core,pataquets/namecoin-core,mruddy/bitcoin,untrustbank/litecoin,droark/bitcoin,nikkitan/bitcoin,h4x3rotab/BTCGPU,namecoin/namecoin-core,tecnovert/particl-core,globaltoken/globaltoken,dscotese/bitcoin,ElementsProject/elements,RHavar/bitcoin,lbryio/lbrycrd,Xekyo/bitcoin,Bushstar/UFO-Project,GlobalBoost/GlobalBoost,Bushstar/UFO-Project,practicalswift/bitcoin,kallewoof/bitcoin,prusnak/bitcoin,AkioNak/bitcoin,sebrandon1/bitcoin,gjhiggins/vcoincore,jamesob/bitcoin,jlopp/statoshi,Kogser/bitcoin,rnicoll/dogecoin,GroestlCoin/GroestlCoin,jamesob/bitcoin,rawodb/bitcoin,Kogser/bitcoin,Xekyo/bitcoin,domob1812/namecore,mruddy/bitcoin,joshrabinowitz/bitcoin,domob1812/bitcoin,CryptArc/bitcoin,BTCGPU/BTCGPU,prusnak/bitcoin,ericshawlinux/bitcoin,GroestlCoin/GroestlCoin,anditto/bitcoin,JeremyRubin/bitcoin,BTCGPU/BTCGPU,afk11/bitcoin,pstratem/bitcoin,Flowdalic/bitcoin,wellenreiter01/Feathercoin,yenliangl/bitcoin,alecalve/bitcoin,lateminer/bitcoin,tecnovert/particl-core,dscotese/bitcoin,stamhe/bitcoin,Flowdalic/bitcoin,fanquake/bitcoin,jmcorgan/bitcoin,apoelstra/bitcoin,MarcoFalke/bitcoin,jlopp/statoshi,thrasher-/litecoin,r8921039/bitcoin,pataquets/namecoin-core,wellenreiter01/Feathercoin,monacoinproject/monacoin,qtumproject/qtum,instagibbs/bitcoin,mm-s/bitcoin,sstone/bitcoin,pstratem/bitcoin,GroestlCoin/GroestlCoin,mruddy/bitcoin,stamhe/bitcoin,n1bor/bitcoin,rnicoll/bitcoin,kazcw/bitcoin,domob1812/namecore,bitcoinknots/bitcoin,JeremyRubin/bitcoin,rnicoll/bitcoin,guncoin/guncoin,litecoin-project/litecoin,FeatherCoin/Feathercoin,Bushstar/UFO-Project,rnicoll/dogecoin,prusnak/bitcoin,Kogser/bitcoin,donaloconnor/bitcoin,domob1812/huntercore,sipsorcery/bitcoin,mm-s/bitcoin,BTCGPU/BTCGPU,digibyte/digibyte,joshrabinowitz/bitcoin,bitcoinknots/bitcoin,FeatherCoin/Feathercoin,myriadteam/myriadcoin,sebrandon1/bitcoin,ElementsProject/elements,sebrandon1/bitcoin,yenliangl/bitcoin,vertcoin/vertcoin,instagibbs/bitcoin,jambolo/bitcoin,GroestlCoin/bitcoin,RHavar/bitcoin,ryanofsky/bitcoin,jonasschnelli/bitcoin,Sjors/bitcoin,alecalve/bitcoin,dscotese/bitcoin,anditto/bitcoin,GlobalBoost/GlobalBoost,AkioNak/bitcoin,ryanofsky/bitcoin,sebrandon1/bitcoin,sipsorcery/bitcoin,alecalve/bitcoin,BTCGPU/BTCGPU,ajtowns/bitcoin,FeatherCoin/Feathercoin,anditto/bitcoin,ericshawlinux/bitcoin,ericshawlinux/bitcoin,litecoin-project/litecoin,Xekyo/bitcoin,digibyte/digibyte,bitcoinsSG/bitcoin,mm-s/bitcoin,ryanofsky/bitcoin,apoelstra/bitcoin,cdecker/bitcoin,anditto/bitcoin,kallewoof/bitcoin,bitcoinsSG/bitcoin,ElementsProject/elements,domob1812/huntercore,droark/bitcoin,MeshCollider/bitcoin,alecalve/bitcoin,qtumproject/qtum,stamhe/bitcoin,ajtowns/bitcoin,lbryio/lbrycrd,randy-waterhouse/bitcoin,MeshCollider/bitcoin
09c3b752154478b15a45d11f08d46a5003f174ec
giveaminute/keywords.py
giveaminute/keywords.py
""" :copyright: (c) 2011 Local Projects, all rights reserved :license: Affero GNU GPL v3, see LICENSE for more details. """ from framework.controller import log # find keywords in a string def getKeywords(db, s): """Get all matches for passed in string in keyword tables :param db: database handle :param s: string to look for :returns list of matching keywords """ words = [] if isinstance(s, str): s = [s] if not isinstance(s, list): log.error("getKeywords requested for a non-string, non-list value: %s. Cannot process!" % s) else: words = list(db.query("select keyword from keyword where keyword in $lookfor", vars=dict(lookfor=s))) return words
""" :copyright: (c) 2011 Local Projects, all rights reserved :license: Affero GNU GPL v3, see LICENSE for more details. """ # find keywords in a string def getKeywords(db, s): sql = "select keyword from keyword" data = list(db.query(sql)) words = [] for d in data: if (d.keyword in s): words.append(d.keyword) return words
Revert keyword optimization for current release
Revert keyword optimization for current release
Python
agpl-3.0
codeforeurope/Change-By-Us,watchcat/cbu-rotterdam,codeforeurope/Change-By-Us,codeforeurope/Change-By-Us,codeforeurope/Change-By-Us,watchcat/cbu-rotterdam,localprojects/Change-By-Us,watchcat/cbu-rotterdam,watchcat/cbu-rotterdam,watchcat/cbu-rotterdam,localprojects/Change-By-Us,localprojects/Change-By-Us,localprojects/Change-By-Us
d7001ccab0879e17308bf2dc945b5fd3b726be27
statblock/dice.py
statblock/dice.py
from random import random class Die: """ Abstracts the random dice throw. Roll will produce the result. The die can be further parametrized by a multiplicator and/or a modifier, like 2 * Die(8) +4. """ def __init__(self, number, multiplicator=1, modifier=0): self.number = number self.multiplicator = multiplicator self.modifier = modifier def roll(self): return self.multiplicator * random.choice(range(1, self.number + 1)) + self.modifier def __rmul__(self, other): return Die(self.number, multiplicator=other, modifier=self.modifier) def __add__(self, other): return Die(self.number, multiplicator=self.multiplicator, modifier=other) def __call__(self): return self.roll() def __eq__(self, other): return (other.number == self.number and other.multiplicator == self.multiplicator and other.modifier == self.modifier) @classmethod def parse(cls, text): return cls.__new__() def __repr__(self): return "%sd%s+%s" % (self.multiplicator, self.number, self.modifier) d4 = Die(4) d6 = Die(6) d8 = Die(8) d10 = Die(10) d12 = Die(12) d20 = Die(20) d100 = Die(100)
from random import random class Die: """ Abstracts the random dice throw. Roll will produce the result. The die can be further parametrized by a multiplicator and/or a modifier, like 2 * Die(8) +4. """ def __init__(self, number, multiplicator=1, modifier=0): self.number = number self.multiplicator = multiplicator self.modifier = modifier def roll(self): return self.multiplicator * random.choice(range(1, self.number + 1)) + self.modifier def __rmul__(self, other): return Die(self.number, multiplicator=other, modifier=self.modifier) def __add__(self, other): return Die(self.number, multiplicator=self.multiplicator, modifier=other) def __call__(self): return self.roll() def __eq__(self, other): return (other.number == self.number and other.multiplicator == self.multiplicator and other.modifier == self.modifier) @classmethod def parse(cls, text): return cls.__new__() def __repr__(self): base = "%sd%s" % (self.multiplicator, self.number) if self.modifier > 0: return base + ("+%s" % self.modifier) return base d4 = Die(4) d6 = Die(6) d8 = Die(8) d10 = Die(10) d12 = Die(12) d20 = Die(20) d100 = Die(100)
Write the critical multiplier or the range when the damage gets converted into a String
Write the critical multiplier or the range when the damage gets converted into a String
Python
mit
bkittelmann/statblock
95f7c6cba7c4077053899e3ca01c8ffd3172873c
grouprise/core/views.py
grouprise/core/views.py
import json import django from rules.contrib.views import PermissionRequiredMixin class PermissionMixin(PermissionRequiredMixin): @property def raise_exception(self): return self.request.user.is_authenticated class AppConfig: def __init__(self): self._settings = {} self._defaults = {} def add_setting(self, name, value): self._settings[name] = value return self def add_default(self, name, value): self._defaults[name] = value return self def serialize(self): conf = {} conf.update(self._defaults) conf.update(self._settings) return json.dumps(conf) app_config = AppConfig() class Markdown(django.views.generic.TemplateView): template_name = 'core/markdown.html'
import json import django from django_filters.views import FilterMixin from rules.contrib.views import PermissionRequiredMixin class PermissionMixin(PermissionRequiredMixin): @property def raise_exception(self): return self.request.user.is_authenticated class TemplateFilterMixin(FilterMixin): def get_context_data(self, **kwargs): filterset_class = self.get_filterset_class() self.filterset = self.get_filterset(filterset_class) if not self.filterset.is_bound or self.filterset.is_valid() or not self.get_strict(): self.object_list = self.filterset.qs else: self.object_list = self.filterset.queryset.none() return super().get_context_data(filter=self.filterset, object_list=self.object_list) class AppConfig: def __init__(self): self._settings = {} self._defaults = {} def add_setting(self, name, value): self._settings[name] = value return self def add_default(self, name, value): self._defaults[name] = value return self def serialize(self): conf = {} conf.update(self._defaults) conf.update(self._settings) return json.dumps(conf) app_config = AppConfig() class Markdown(django.views.generic.TemplateView): template_name = 'core/markdown.html'
Add view mixin for working with filters in templates
Add view mixin for working with filters in templates
Python
agpl-3.0
stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten
a789e8bf574973259c0461b99fb9a486abed6e23
systemvm/patches/debian/config/opt/cloud/bin/cs_ip.py
systemvm/patches/debian/config/opt/cloud/bin/cs_ip.py
from pprint import pprint from netaddr import * def merge(dbag, ip): added = False for dev in dbag: if dev == "id": continue for address in dbag[dev]: if address['public_ip'] == ip['public_ip']: dbag[dev].remove(address) if ip['add']: ipo = IPNetwork(ip['public_ip'] + '/' + ip['netmask']) ip['device'] = 'eth' + str(ip['nic_dev_id']) ip['cidr'] = str(ipo.ip) + '/' + str(ipo.prefixlen) ip['network'] = str(ipo.network) + '/' + str(ipo.prefixlen) if 'nw_type' not in ip.keys(): ip['nw_type'] = 'public' dbag.setdefault('eth' + str(ip['nic_dev_id']), []).append( ip ) return dbag
from pprint import pprint from netaddr import * def merge(dbag, ip): added = False for dev in dbag: if dev == "id": continue for address in dbag[dev]: if address['public_ip'] == ip['public_ip']: dbag[dev].remove(address) if ip['add']: ipo = IPNetwork(ip['public_ip'] + '/' + ip['netmask']) ip['device'] = 'eth' + str(ip['nic_dev_id']) ip['cidr'] = str(ipo.ip) + '/' + str(ipo.prefixlen) ip['network'] = str(ipo.network) + '/' + str(ipo.prefixlen) if 'nw_type' not in ip.keys(): ip['nw_type'] = 'public' if ip['nw_type'] == 'control': dbag['eth' + str(ip['nic_dev_id'])] = [ ip ] else: dbag.setdefault('eth' + str(ip['nic_dev_id']), []).append( ip ) return dbag
Fix a bug that would add updated control ip address instead of replace
Fix a bug that would add updated control ip address instead of replace
Python
apache-2.0
jcshen007/cloudstack,resmo/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,resmo/cloudstack,wido/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack
67ebe8da58384529c49673e2314d4fc228aebe9e
python/testData/inspections/PyPackageRequirementsInspection/ImportsNotInRequirementsTxt/test1.py
python/testData/inspections/PyPackageRequirementsInspection/ImportsNotInRequirementsTxt/test1.py
import pip import <weak_warning descr="Package 'opster' is not listed in project requirements">opster</weak_warning> from <weak_warning descr="Package 'clevercss' is not listed in project requirements">clevercss</weak_warning> import convert import <weak_warning descr="Package 'django' is not listed in project requirements">django</weak_warning>.conf import httplib import <weak_warning descr="Package 'test3' is not listed in project requirements">test3</weak_warning> print('Hello, World!')
import pip import <weak_warning descr="Package containing module 'opster' is not listed in project requirements">opster</weak_warning> from <weak_warning descr="Package containing module 'clevercss' is not listed in project requirements">clevercss</weak_warning> import convert import <weak_warning descr="Package containing module 'django' is not listed in project requirements">django</weak_warning>.conf import httplib import <weak_warning descr="Package containing module 'test3' is not listed in project requirements">test3</weak_warning> print('Hello, World!')
Fix test data for PyPackageRequirementsInspectionTest.testImportsNotInRequirementsTxt.
Fix test data for PyPackageRequirementsInspectionTest.testImportsNotInRequirementsTxt.
Python
apache-2.0
apixandru/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,da1z/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,da1z/intellij-community,suncycheng/intellij-community,allotria/intellij-community,allotria/intellij-community,asedunov/intellij-community,ibinti/intellij-community,apixandru/intellij-community,apixandru/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,asedunov/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,vvv1559/intellij-community,allotria/intellij-community,ibinti/intellij-community,ibinti/intellij-community,allotria/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,allotria/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,asedunov/intellij-community,apixandru/intellij-community,xfournet/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,apixandru/intellij-community,da1z/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,asedunov/intellij-community,da1z/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,da1z/intellij-community,asedunov/intellij-community,da1z/intellij-community,asedunov/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,apixandru/intellij-community,allotria/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,allotria/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,allotria/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,apixandru/intellij-community,allotria/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,apixandru/intellij-community,apixandru/intellij-community,asedunov/intellij-community,suncycheng/intellij-community
ed91a6832d459dffa18d1b2d7b827b6aa6da2627
src/sentry/api/endpoints/team_project_index.py
src/sentry/api/endpoints/team_project_index.py
from __future__ import absolute_import from rest_framework import serializers, status from rest_framework.response import Response from sentry.api.bases.team import TeamEndpoint from sentry.api.permissions import assert_perm from sentry.api.serializers import serialize from sentry.constants import MEMBER_ADMIN from sentry.models import Project from sentry.permissions import can_create_projects class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ('name', 'slug') class TeamProjectIndexEndpoint(TeamEndpoint): def get(self, request, team): assert_perm(team, request.user, request.auth) results = list(Project.objects.get_for_user(team=team, user=request.user)) return Response(serialize(results, request.user)) def post(self, request, team): assert_perm(team, request.user, request.auth, access=MEMBER_ADMIN) if not can_create_projects(user=request.user, team=team): return Response(status=403) serializer = ProjectSerializer(data=request.DATA) if serializer.is_valid(): project = serializer.object project.team = team project.organization = team.organization project.save() return Response(serialize(project, request.user), status=201) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
from __future__ import absolute_import from rest_framework import serializers, status from rest_framework.response import Response from sentry.api.base import DocSection from sentry.api.bases.team import TeamEndpoint from sentry.api.permissions import assert_perm from sentry.api.serializers import serialize from sentry.constants import MEMBER_ADMIN from sentry.models import Project from sentry.permissions import can_create_projects class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ('name', 'slug') class TeamProjectIndexEndpoint(TeamEndpoint): doc_section = DocSection.TEAMS def get(self, request, team): """ List a team's projects Return a list of projects bound to a team. {method} {path} """ assert_perm(team, request.user, request.auth) results = list(Project.objects.get_for_user(team=team, user=request.user)) return Response(serialize(results, request.user)) def post(self, request, team): """ Create a new project Create a new project bound to a team. {method} {path} {{ "name": "My project" }} """ assert_perm(team, request.user, request.auth, access=MEMBER_ADMIN) if not can_create_projects(user=request.user, team=team): return Response(status=403) serializer = ProjectSerializer(data=request.DATA) if serializer.is_valid(): project = serializer.object project.team = team project.organization = team.organization project.save() return Response(serialize(project, request.user), status=201) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Add team project list to docs
Add team project list to docs
Python
bsd-3-clause
BuildingLink/sentry,JamesMura/sentry,mvaled/sentry,beeftornado/sentry,JamesMura/sentry,ngonzalvez/sentry,Kryz/sentry,fuziontech/sentry,nicholasserra/sentry,TedaLIEz/sentry,JackDanger/sentry,songyi199111/sentry,BayanGroup/sentry,songyi199111/sentry,1tush/sentry,kevinlondon/sentry,gg7/sentry,jokey2k/sentry,Natim/sentry,vperron/sentry,daevaorn/sentry,wong2/sentry,JTCunning/sentry,Natim/sentry,nicholasserra/sentry,daevaorn/sentry,fuziontech/sentry,gg7/sentry,boneyao/sentry,kevinastone/sentry,gencer/sentry,mvaled/sentry,pauloschilling/sentry,kevinastone/sentry,BuildingLink/sentry,TedaLIEz/sentry,fotinakis/sentry,gg7/sentry,drcapulet/sentry,drcapulet/sentry,JTCunning/sentry,BayanGroup/sentry,argonemyth/sentry,fuziontech/sentry,looker/sentry,gencer/sentry,jokey2k/sentry,wujuguang/sentry,boneyao/sentry,JamesMura/sentry,vperron/sentry,felixbuenemann/sentry,ewdurbin/sentry,daevaorn/sentry,ifduyue/sentry,1tush/sentry,zenefits/sentry,korealerts1/sentry,zenefits/sentry,alexm92/sentry,JackDanger/sentry,mitsuhiko/sentry,wujuguang/sentry,llonchj/sentry,ngonzalvez/sentry,JamesMura/sentry,mvaled/sentry,fotinakis/sentry,hongliang5623/sentry,pauloschilling/sentry,looker/sentry,Kryz/sentry,gencer/sentry,jean/sentry,boneyao/sentry,Kryz/sentry,looker/sentry,wong2/sentry,BuildingLink/sentry,korealerts1/sentry,ewdurbin/sentry,JTCunning/sentry,ifduyue/sentry,ewdurbin/sentry,beeftornado/sentry,JackDanger/sentry,gencer/sentry,hongliang5623/sentry,jokey2k/sentry,ifduyue/sentry,1tush/sentry,BuildingLink/sentry,imankulov/sentry,fotinakis/sentry,daevaorn/sentry,felixbuenemann/sentry,songyi199111/sentry,imankulov/sentry,beeftornado/sentry,jean/sentry,vperron/sentry,Natim/sentry,zenefits/sentry,felixbuenemann/sentry,imankulov/sentry,looker/sentry,alexm92/sentry,mvaled/sentry,gencer/sentry,ifduyue/sentry,kevinlondon/sentry,kevinlondon/sentry,pauloschilling/sentry,JamesMura/sentry,BayanGroup/sentry,ngonzalvez/sentry,jean/sentry,zenefits/sentry,drcapulet/sentry,korealerts1/sentry,mvaled/sentry,wong2/sentry,ifduyue/sentry,fotinakis/sentry,argonemyth/sentry,alexm92/sentry,jean/sentry,hongliang5623/sentry,argonemyth/sentry,llonchj/sentry,looker/sentry,llonchj/sentry,jean/sentry,kevinastone/sentry,nicholasserra/sentry,BuildingLink/sentry,zenefits/sentry,mvaled/sentry,mitsuhiko/sentry,TedaLIEz/sentry,wujuguang/sentry
b04f3bd19b508140b0b4feee46d590b61da46bed
swift/__init__.py
swift/__init__.py
import gettext class Version(object): def __init__(self, canonical_version, final): self.canonical_version = canonical_version self.final = final @property def pretty_version(self): if self.final: return self.canonical_version else: return '%s-dev' % (self.canonical_version,) _version = Version('1.4.0', False) __version__ = _version.pretty_version __canonical_version__ = _version.canonical_version gettext.install('swift')
import gettext class Version(object): def __init__(self, canonical_version, final): self.canonical_version = canonical_version self.final = final @property def pretty_version(self): if self.final: return self.canonical_version else: return '%s-dev' % (self.canonical_version,) _version = Version('1.4.1', False) __version__ = _version.pretty_version __canonical_version__ = _version.canonical_version gettext.install('swift')
Switch Swift trunk to 1.4.1, now that the 1.4.0 release branch is branched out.
Switch Swift trunk to 1.4.1, now that the 1.4.0 release branch is branched out.
Python
apache-2.0
mja054/swift_plugin,iostackproject/IO-Bandwidth-Differentiation,williamthegrey/swift,openstack/swift,notmyname/swift,matthewoliver/swift,orion/swift-config,thiagodasilva/swift,zackmdavis/swift,smerritt/swift,bkolli/swift,Em-Pan/swift,Khushbu27/Tutorial,openstack/swift,larsbutler/swift,aerwin3/swift,redhat-openstack/swift,hbhdytf/mac,scality/ScalitySproxydSwift,rackerlabs/swift,eatbyte/Swift,citrix-openstack-build/swift,psachin/swift,revoer/keystone-8.0.0,dpgoetz/swift,smerritt/swift,bkolli/swift,matthewoliver/swift,clayg/swift,Seagate/swift,IPVL/swift-kilo,psachin/swift,nadeemsyed/swift,smerritt/swift,sarvesh-ranjan/swift,sarvesh-ranjan/swift,NeCTAR-RC/swift,bradleypj823/swift,bouncestorage/swift,matthewoliver/swift,citrix-openstack/build-swift,ceph/swift,orion/swift-config,openstack/swift,revoer/keystone-8.0.0,hurricanerix/swift,levythu/swift,dpgoetz/swift,hurricanerix/swift,clayg/swift,Khushbu27/Tutorial,hbhdytf/mac2,mjwtom/swift,notmyname/swift,AfonsoFGarcia/swift,Akanoa/swift,shibaniahegde/OpenStak_swift,xiaoguoai/ec-dev-swift,williamthegrey/swift,anishnarang/gswift,Mirantis/swift-encrypt,prashanthpai/swift,mja054/swift_plugin,Akanoa/swift,NewpTone/StackLab-swift,AfonsoFGarcia/swift,dencaval/swift,zackmdavis/swift,NewpTone/StackLab-swift,levythu/swift,NeCTAR-RC/swift,shibaniahegde/OpenStak_swift,notmyname/swift,gold3bear/swift,gold3bear/swift,mjwtom/swift,zaitcev/swift-lfs,SUSE/swift,matthewoliver/swift,redbo/swift,JioCloud/swift,VictorLowther/swift,Seagate/swift,maginatics/swift,prashanthpai/swift,notmyname/swift,psachin/swift,redbo/swift,mja054/swift_plugin,nadeemsyed/swift,tipabu/swift,wenhuizhang/swift,Intel-bigdata/swift,SUSE/swift,hbhdytf/mac2,dencaval/swift,tipabu/swift,aerwin3/swift,openstack/swift,Em-Pan/swift,takeshineshiro/swift,houseurmusic/my-swift,rackerlabs/swift,swiftstack/swift,clayg/swift,anishnarang/gswift,hbhdytf/mac2,Intel-bigdata/swift,hbhdytf/mac2,eatbyte/Swift,houseurmusic/my-swift,psachin/swift,VictorLowther/swift,hurricanerix/swift,Triv90/SwiftUml,zaitcev/swift-lfs,mjzmjz/swift,maginatics/swift,clayg/swift,hurricanerix/swift,ceph/swift,citrix-openstack-build/swift,nadeemsyed/swift,scality/ScalitySproxydSwift,nadeemsyed/swift,iostackproject/IO-Bandwidth-Differentiation,swiftstack/swift,smerritt/swift,tsli/test,tipabu/swift,wenhuizhang/swift,bradleypj823/swift,Triv90/SwiftUml,takeshineshiro/swift,redhat-openstack/swift,IPVL/swift-kilo,bouncestorage/swift,thiagodasilva/swift,tsli/test,xiaoguoai/ec-dev-swift,swiftstack/swift,Mirantis/swift-encrypt,daasbank/swift,tipabu/swift,daasbank/swift,hbhdytf/mac,larsbutler/swift,citrix-openstack/build-swift,mjzmjz/swift,JioCloud/swift