commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
ab8fc00a7dc6618d23e06f06e125da5ee69b2dba
event_registration_hr_contract/__openerp__.py
event_registration_hr_contract/__openerp__.py
# -*- coding: utf-8 -*- # (c) 2016 Alfredo de la Fuente - AvanzOSC # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { "name": "Event Registration Hr Contract", 'version': '8.0.1.1.0', 'license': "AGPL-3", 'author': "AvanzOSC", 'website': "http://www.avanzosc.es", 'contributors': [ "Ana Juaristi <anajuaristi@avanzosc.es>", "Alfredo de la Fuente <alfredodelafuente@avanzosc.es", ], "category": "Event Management", "depends": [ 'event_track_presence_hr_holidays', 'hr_contract_stages' ], "data": [ 'wizard/wiz_calculate_employee_calendar_view.xml', 'wizard/wiz_event_append_assistant_view.xml', 'views/event_event_view.xml', 'views/hr_contract_view.xml', 'views/event_track_presence_view.xml', 'views/res_partner_calendar_view.xml', 'views/res_partner_calendar_day_view.xml' ], "installable": True, }
# -*- coding: utf-8 -*- # (c) 2016 Alfredo de la Fuente - AvanzOSC # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { "name": "Event Registration Hr Contract", 'version': '8.0.1.1.0', 'license': "AGPL-3", 'author': "AvanzOSC", 'website': "http://www.avanzosc.es", 'contributors': [ "Ana Juaristi <anajuaristi@avanzosc.es>", "Alfredo de la Fuente <alfredodelafuente@avanzosc.es", ], "category": "Event Management", "depends": [ 'event_track_presence_hr_holidays', ], "data": [ 'wizard/wiz_calculate_employee_calendar_view.xml', 'wizard/wiz_event_append_assistant_view.xml', 'views/event_event_view.xml', 'views/hr_contract_view.xml', 'views/event_track_presence_view.xml', 'views/res_partner_calendar_view.xml', 'views/res_partner_calendar_day_view.xml' ], "installable": True, }
Remove the dependence with the module hr_contract_stage.
[IMP] event_registration_hr_contract: Remove the dependence with the module hr_contract_stage.
Python
agpl-3.0
avanzosc/event-wip
--- +++ @@ -14,7 +14,6 @@ "category": "Event Management", "depends": [ 'event_track_presence_hr_holidays', - 'hr_contract_stages' ], "data": [ 'wizard/wiz_calculate_employee_calendar_view.xml',
44a7c59d798d9a20d4d54b9cce7e56b8f88595cc
ch14/caesar.py
ch14/caesar.py
# Caesar Cipher MAX_KEY_SIZE = 26 def getMode(): while True: print('Do you wish to encrypt or decrypt a message?') mode = input().lower() if mode in 'encrypt e decrypt d'.split(): return mode else: print('Enter either "encrypt" or "e" or "decrypt" or "d".') def getMessage(): print('Enter your message:') return input() def getKey(): key = 0 while True: print('Enter the key number (1-%s)' % (MAX_KEY_SIZE)) key = int(input()) if (key >= 1 and key <= MAX_KEY_SIZE): return key def getTranslatedMessage(mode, message, key): if mode[0] == 'd': key = -key translated = '' for symbol in message: if symbol.isalpha(): num = ord(symbol) num += key if symbol.isupper(): if num > ord('Z'): num -= 26 elif num < ord('A'): num += 26 elif symbol.islower(): if num > ord('z'): num -= 26 elif num < ord('a'): num += 26 translated += chr(num) else: translated += symbol return translated mode = getMode() message = getMessage() key = getKey() print('Your translated text is:') print(getTranslatedMessage(mode, message, key))
# Caesar Cipher MAX_KEY_SIZE = 26 def getMode(): while True: print('Do you wish to encrypt or decrypt a message?') mode = input().lower() if mode in 'encrypt e decrypt d'.split(): return mode else: print('Enter either "encrypt" or "e" or "decrypt" or "d".') def getMessage(): print('Enter your message:') return input() def getKey(): key = 0 while True: print('Enter the key number (1-%s)' % (MAX_KEY_SIZE)) try: key = int(input()) except ValueError: continue if (key >= 1 and key <= MAX_KEY_SIZE): return key def getTranslatedMessage(mode, message, key): if mode[0] == 'd': key = -key translated = '' for symbol in message: if symbol.isalpha(): num = ord(symbol) num += key if symbol.isupper(): if num > ord('Z'): num -= 26 elif num < ord('A'): num += 26 elif symbol.islower(): if num > ord('z'): num -= 26 elif num < ord('a'): num += 26 translated += chr(num) else: translated += symbol return translated mode = getMode() message = getMessage() key = getKey() print('Your translated text is:') print(getTranslatedMessage(mode, message, key))
Modify the code in the getKey() function so that it gracefully ignores non-integer input.
Modify the code in the getKey() function so that it gracefully ignores non-integer input.
Python
bsd-2-clause
aclogreco/InventGamesWP
--- +++ @@ -21,7 +21,10 @@ key = 0 while True: print('Enter the key number (1-%s)' % (MAX_KEY_SIZE)) - key = int(input()) + try: + key = int(input()) + except ValueError: + continue if (key >= 1 and key <= MAX_KEY_SIZE): return key
014b4905784f50fd13111ca8528fade9be4bd767
skimage/feature/__init__.py
skimage/feature/__init__.py
from ._hog import hog from ._greycomatrix import greycomatrix, greycoprops from .hog import hog from .texture import greycomatrix, greycoprops, local_binary_pattern from .peak import peak_local_max from ._harris import harris from .template import match_template
from ._hog import hog from .texture import greycomatrix, greycoprops, local_binary_pattern from .peak import peak_local_max from ._harris import harris from .template import match_template
Fix import bug due to rebase
Fix import bug due to rebase
Python
bsd-3-clause
blink1073/scikit-image,robintw/scikit-image,emon10005/scikit-image,newville/scikit-image,michaelaye/scikit-image,GaZ3ll3/scikit-image,chintak/scikit-image,chriscrosscutler/scikit-image,warmspringwinds/scikit-image,vighneshbirodkar/scikit-image,robintw/scikit-image,dpshelio/scikit-image,Hiyorimi/scikit-image,youprofit/scikit-image,youprofit/scikit-image,rjeli/scikit-image,michaelpacer/scikit-image,Britefury/scikit-image,SamHames/scikit-image,almarklein/scikit-image,SamHames/scikit-image,bennlich/scikit-image,Hiyorimi/scikit-image,WarrenWeckesser/scikits-image,almarklein/scikit-image,WarrenWeckesser/scikits-image,ClinicalGraphics/scikit-image,chriscrosscutler/scikit-image,Midafi/scikit-image,juliusbierk/scikit-image,oew1v07/scikit-image,juliusbierk/scikit-image,ajaybhat/scikit-image,newville/scikit-image,Britefury/scikit-image,vighneshbirodkar/scikit-image,paalge/scikit-image,ClinicalGraphics/scikit-image,dpshelio/scikit-image,emmanuelle/scikits.image,jwiggins/scikit-image,bsipocz/scikit-image,ajaybhat/scikit-image,pratapvardhan/scikit-image,ofgulban/scikit-image,Midafi/scikit-image,rjeli/scikit-image,bsipocz/scikit-image,blink1073/scikit-image,almarklein/scikit-image,almarklein/scikit-image,emmanuelle/scikits.image,ofgulban/scikit-image,keflavich/scikit-image,keflavich/scikit-image,paalge/scikit-image,chintak/scikit-image,bennlich/scikit-image,warmspringwinds/scikit-image,emon10005/scikit-image,michaelpacer/scikit-image,chintak/scikit-image,pratapvardhan/scikit-image,emmanuelle/scikits.image,jwiggins/scikit-image,GaZ3ll3/scikit-image,ofgulban/scikit-image,michaelaye/scikit-image,SamHames/scikit-image,rjeli/scikit-image,SamHames/scikit-image,emmanuelle/scikits.image,chintak/scikit-image,oew1v07/scikit-image,vighneshbirodkar/scikit-image,paalge/scikit-image
--- +++ @@ -1,6 +1,4 @@ from ._hog import hog -from ._greycomatrix import greycomatrix, greycoprops -from .hog import hog from .texture import greycomatrix, greycoprops, local_binary_pattern from .peak import peak_local_max from ._harris import harris
72865598fbe8658ade68f67da4e2a244a13713b9
analysis/plot-marker-trajectories.py
analysis/plot-marker-trajectories.py
import climate import lmj.plot import numpy as np import source import plots @climate.annotate( root='load experiment data from this directory', pattern='plot data from files matching this pattern', markers='plot traces of these markers', ) def main(root, pattern='*5/*block00/*circuit00.csv.gz', markers='r-fing-index l-fing-index r-heel r-knee'): with plots.space() as ax: for t in source.Experiment(root).trials_matching(pattern): t.realign() t.interpolate() for i, marker in enumerate(markers.split()): df = t.trajectory(marker) ax.plot(np.asarray(df.x), np.asarray(df.z), zs=np.asarray(df.y), color=lmj.plot.COLOR11[i], alpha=0.7) if __name__ == '__main__': climate.call(main)
import climate import lmj.plot import numpy as np import source import plots @climate.annotate( root='load experiment data from this directory', pattern=('plot data from files matching this pattern', 'option'), markers=('plot traces of these markers', 'option'), spline=('interpolate data with a spline of this order', 'option', None, int), accuracy=('fit spline with this accuracy', 'option', None, float), ) def main(root, pattern='*/*block00/*circuit00.csv.gz', markers='r-fing-index l-fing-index r-heel r-knee', spline=1, accuracy=1): with plots.space() as ax: for t in source.Experiment(root).trials_matching(pattern): t.normalize(order=spline, accuracy=accuracy) for i, marker in enumerate(markers.split()): df = t.trajectory(marker) ax.plot(np.asarray(df.x), np.asarray(df.z), zs=np.asarray(df.y), color=lmj.plot.COLOR11[i], alpha=0.7) if __name__ == '__main__': climate.call(main)
Add command-line flags for spline order and accuracy.
Add command-line flags for spline order and accuracy.
Python
mit
lmjohns3/cube-experiment,lmjohns3/cube-experiment,lmjohns3/cube-experiment
--- +++ @@ -8,14 +8,19 @@ @climate.annotate( root='load experiment data from this directory', - pattern='plot data from files matching this pattern', - markers='plot traces of these markers', + pattern=('plot data from files matching this pattern', 'option'), + markers=('plot traces of these markers', 'option'), + spline=('interpolate data with a spline of this order', 'option', None, int), + accuracy=('fit spline with this accuracy', 'option', None, float), ) -def main(root, pattern='*5/*block00/*circuit00.csv.gz', markers='r-fing-index l-fing-index r-heel r-knee'): +def main(root, + pattern='*/*block00/*circuit00.csv.gz', + markers='r-fing-index l-fing-index r-heel r-knee', + spline=1, + accuracy=1): with plots.space() as ax: for t in source.Experiment(root).trials_matching(pattern): - t.realign() - t.interpolate() + t.normalize(order=spline, accuracy=accuracy) for i, marker in enumerate(markers.split()): df = t.trajectory(marker) ax.plot(np.asarray(df.x),
d38599b88a4537d92b562010ca4b7e56580f2e35
graphene_django_extras/directives/__init__.py
graphene_django_extras/directives/__init__.py
# -*- coding: utf-8 -*- from graphql.type.directives import specified_directives as default_directives from .list import ShuffleGraphQLDirective, SampleGraphQLDirective from .numbers import FloorGraphQLDirective, CeilGraphQLDirective from .string import ( DefaultGraphQLDirective, Base64GraphQLDirective, NumberGraphQLDirective, CurrencyGraphQLDirective, LowercaseGraphQLDirective, UppercaseGraphQLDirective, CapitalizeGraphQLDirective, CamelCaseGraphQLDirective, SnakeCaseGraphQLDirective, KebabCaseGraphQLDirective, SwapCaseGraphQLDirective, StripGraphQLDirective, TitleCaseGraphQLDirective, CenterGraphQLDirective, ReplaceGraphQLDirective, ) try: import dateutil # noqa: 401 from .date import DateGraphQLDirective date_directives = (DateGraphQLDirective,) DATEUTIL_INSTALLED = True except ImportError: date_directives = () DATEUTIL_INSTALLED = False list_directives = (ShuffleGraphQLDirective, SampleGraphQLDirective) numbers_directives = (FloorGraphQLDirective, CeilGraphQLDirective) string_directives = ( DefaultGraphQLDirective, Base64GraphQLDirective, NumberGraphQLDirective, CurrencyGraphQLDirective, LowercaseGraphQLDirective, UppercaseGraphQLDirective, CapitalizeGraphQLDirective, CamelCaseGraphQLDirective, SnakeCaseGraphQLDirective, KebabCaseGraphQLDirective, SwapCaseGraphQLDirective, StripGraphQLDirective, TitleCaseGraphQLDirective, CenterGraphQLDirective, ReplaceGraphQLDirective, ) all_directives = ( date_directives + list_directives + numbers_directives + string_directives ) all_directives = [d() for d in all_directives] + default_directives
# -*- coding: utf-8 -*- from graphql.type.directives import specified_directives as default_directives from .date import * from .list import * from .numbers import * from .string import * all_directives = ( # date DateGraphQLDirective, # list ShuffleGraphQLDirective, SampleGraphQLDirective, # numbers FloorGraphQLDirective, CeilGraphQLDirective, # string DefaultGraphQLDirective, Base64GraphQLDirective, NumberGraphQLDirective, CurrencyGraphQLDirective, LowercaseGraphQLDirective, UppercaseGraphQLDirective, CapitalizeGraphQLDirective, CamelCaseGraphQLDirective, SnakeCaseGraphQLDirective, KebabCaseGraphQLDirective, SwapCaseGraphQLDirective, StripGraphQLDirective, TitleCaseGraphQLDirective, CenterGraphQLDirective, ReplaceGraphQLDirective, ) all_directives = [d() for d in all_directives] + default_directives
Reorder imports and use Black code style. Updated version to 0.4.4
Reorder imports and use Black code style. Updated version to 0.4.4
Python
mit
eamigo86/graphene-django-extras
--- +++ @@ -1,9 +1,21 @@ # -*- coding: utf-8 -*- from graphql.type.directives import specified_directives as default_directives -from .list import ShuffleGraphQLDirective, SampleGraphQLDirective -from .numbers import FloorGraphQLDirective, CeilGraphQLDirective -from .string import ( +from .date import * +from .list import * +from .numbers import * +from .string import * + +all_directives = ( + # date + DateGraphQLDirective, + # list + ShuffleGraphQLDirective, + SampleGraphQLDirective, + # numbers + FloorGraphQLDirective, + CeilGraphQLDirective, + # string DefaultGraphQLDirective, Base64GraphQLDirective, NumberGraphQLDirective, @@ -21,40 +33,5 @@ ReplaceGraphQLDirective, ) -try: - import dateutil # noqa: 401 - from .date import DateGraphQLDirective - - date_directives = (DateGraphQLDirective,) - DATEUTIL_INSTALLED = True -except ImportError: - date_directives = () - DATEUTIL_INSTALLED = False - - -list_directives = (ShuffleGraphQLDirective, SampleGraphQLDirective) -numbers_directives = (FloorGraphQLDirective, CeilGraphQLDirective) -string_directives = ( - DefaultGraphQLDirective, - Base64GraphQLDirective, - NumberGraphQLDirective, - CurrencyGraphQLDirective, - LowercaseGraphQLDirective, - UppercaseGraphQLDirective, - CapitalizeGraphQLDirective, - CamelCaseGraphQLDirective, - SnakeCaseGraphQLDirective, - KebabCaseGraphQLDirective, - SwapCaseGraphQLDirective, - StripGraphQLDirective, - TitleCaseGraphQLDirective, - CenterGraphQLDirective, - ReplaceGraphQLDirective, -) - -all_directives = ( - date_directives + list_directives + numbers_directives + string_directives -) - all_directives = [d() for d in all_directives] + default_directives
baf41667c9c86484319c58e56187792ed571b6db
certificates/generator.py
certificates/generator.py
from os import system from os import unlink from os.path import dirname from os.path import realpath def generate_certificate_for(event_id, certificate_name, name_of_certificate_holder): resources_path = dirname(realpath(__file__)) + '/resources/' static_files_path = dirname(dirname(realpath(__file__))) + '/staticfiles/certificates/' generic_template_path = resources_path + 'template.tex' personalized_template_path = resources_path + str(event_id) + '.tex' resulting_certificate_path = static_files_path + certificate_name with open(generic_template_path) as template: personalized_certificate_content = template.read().replace( '<CERTIFICATE_HOLDER_NAME>', name_of_certificate_holder) with open(personalized_template_path, 'w') as personalized_template: personalized_template.write(personalized_certificate_content) commands = [ 'cd ' + resources_path, 'pdflatex -interaction=nonstopmode -output-directory ' + resources_path + ' ' + personalized_template_path, 'mkdir -p ' + static_files_path, 'mv -f ' + personalized_template_path.replace('.tex', '.pdf') + ' ' + resulting_certificate_path, 'rm -rf ' + resources_path + str(event_id) + '.*', ] if system(' && '.join(commands)) != 0: return False return resulting_certificate_path
from os import system from os import unlink from os.path import dirname from os.path import realpath def generate_certificate_for(event_id, certificate_name, name_of_certificate_holder): resources_path = dirname(realpath(__file__)) + '/resources/' static_files_path = dirname(dirname(realpath(__file__))) + '/staticfiles/certificates/' generic_template_path = resources_path + 'template.tex' personalized_template_path = resources_path + str(event_id) + '.tex' resulting_certificate_path = static_files_path + certificate_name with open(generic_template_path) as template: personalized_certificate_content = template.read().replace( '<CERTIFICATE_HOLDER_NAME>', name_of_certificate_holder) with open(personalized_template_path, 'w') as personalized_template: personalized_template.write(personalized_certificate_content.encode('utf-8')) commands = [ 'cd ' + resources_path, 'pdflatex -interaction=nonstopmode -output-directory ' + resources_path + ' ' + personalized_template_path, 'mkdir -p ' + static_files_path, 'mv -f ' + personalized_template_path.replace('.tex', '.pdf') + ' ' + resulting_certificate_path, 'rm -rf ' + resources_path + str(event_id) + '.*', ] if system(' && '.join(commands)) != 0: return False return resulting_certificate_path
Fix writing UTF-8 texts to certificate templates
Fix writing UTF-8 texts to certificate templates The certificate PDF can’t reliably render all variants of UTF-8 text. We will need to disable non-ASCII input.
Python
mit
codeeu/coding-events,codeeu/coding-events,codeeu/coding-events,codeeu/coding-events,codeeu/coding-events
--- +++ @@ -16,7 +16,7 @@ '<CERTIFICATE_HOLDER_NAME>', name_of_certificate_holder) with open(personalized_template_path, 'w') as personalized_template: - personalized_template.write(personalized_certificate_content) + personalized_template.write(personalized_certificate_content.encode('utf-8')) commands = [ 'cd ' + resources_path,
5bad3f45bdca436515b416bbcfb45ca53b46ca2a
application/lomadee/data_importer.py
application/lomadee/data_importer.py
from django.conf import settings from urllib.parse import urljoin, urlencode class ComputerDataImporter(object): def __init__(self): pass def build_api_url(self, **kwargs): api_url = urljoin(settings.LOMADEE_API_URL, settings.LOMADEE_APP_TOKEN) # Specific path to 'Computer' category url = urljoin(api_url, 'offer/_category/6424') kwargs['sourceId'] = settings.LOMADEE_SOURCE_ID return '{}?{}'.format(url, urlencode(kwargs))
from django.conf import settings from urllib.parse import urljoin, urlencode import requests class ComputerDataImporter(object): def __init__(self): pass def build_api_url(self, **kwargs): api_url = urljoin(settings.LOMADEE_API_URL, settings.LOMADEE_APP_TOKEN) # Specific path to 'Computer' category url = urljoin('{}/'.format(api_url), 'offer/_category/6424') kwargs['sourceId'] = settings.LOMADEE_SOURCE_ID kwargs['size'] = 100 return '{}?{}'.format(url, urlencode(kwargs)) def get_data(self, url=None): if not url: url = self.build_api_url() data = requests.get(url).json() if data['requestInfo']['status'] != 'OK': return False final_data = [] final_data.extend(data['offers']) pagination = data['pagination'] # Get only 3 pages. To get all pages use: # if pagination['page'] < pagination['totalPage'] if pagination['page'] < 3: next_page_data = self.get_data( self.build_api_url(page=pagination['page'] + 1) ) final_data.extend(next_page_data) return final_data
Add get_data method to data importer
Add get_data method to data importer Signed-off-by: Matheus Fernandes <9de26933bf4170c6685be29c190c23bc8c34d55f@gmail.com>
Python
mit
msfernandes/facebook-chatbot
--- +++ @@ -1,5 +1,6 @@ from django.conf import settings from urllib.parse import urljoin, urlencode +import requests class ComputerDataImporter(object): @@ -11,7 +12,29 @@ api_url = urljoin(settings.LOMADEE_API_URL, settings.LOMADEE_APP_TOKEN) # Specific path to 'Computer' category - url = urljoin(api_url, 'offer/_category/6424') + url = urljoin('{}/'.format(api_url), 'offer/_category/6424') kwargs['sourceId'] = settings.LOMADEE_SOURCE_ID + kwargs['size'] = 100 return '{}?{}'.format(url, urlencode(kwargs)) + + def get_data(self, url=None): + if not url: + url = self.build_api_url() + + data = requests.get(url).json() + if data['requestInfo']['status'] != 'OK': + return False + + final_data = [] + final_data.extend(data['offers']) + pagination = data['pagination'] + + # Get only 3 pages. To get all pages use: + # if pagination['page'] < pagination['totalPage'] + if pagination['page'] < 3: + next_page_data = self.get_data( + self.build_api_url(page=pagination['page'] + 1) + ) + final_data.extend(next_page_data) + return final_data
b08bff08d69960c9035cefa4e4021d48530c5158
anemoi/Tests/test_Analytical.py
anemoi/Tests/test_Analytical.py
import unittest import numpy as np from anemoi import AnalyticalHelmholtz class TestMiniZephyr(unittest.TestCase): def setUp(self): pass def test_forwardModelling(self): nx = 100 nz = 200 systemConfig = { 'dx': 1., # m 'dz': 1., # m 'c': 2500., # m/s 'nx': nx, # count 'nz': nz, # count 'freq': 2e2, # Hz } Green = AnalyticalHelmholtz(systemConfig) u = Green(nx/2, nz/2) if __name__ == '__main__': unittest.main()
import unittest import numpy as np from anemoi import AnalyticalHelmholtz class TestAnalyticalHelmholtz(unittest.TestCase): def setUp(self): pass def test_cleanExecution(self): nx = 100 nz = 200 systemConfig = { 'c': 2500., # m/s 'nx': nx, # count 'nz': nz, # count 'freq': 2e2, # Hz } Green = AnalyticalHelmholtz(systemConfig) u = Green(nx/2, nz/2) if __name__ == '__main__': unittest.main()
Rename one test, use default dx and dz, fix naming of test class.
Rename one test, use default dx and dz, fix naming of test class.
Python
mit
uwoseis/zephyr,uwoseis/anemoi
--- +++ @@ -2,19 +2,17 @@ import numpy as np from anemoi import AnalyticalHelmholtz -class TestMiniZephyr(unittest.TestCase): +class TestAnalyticalHelmholtz(unittest.TestCase): def setUp(self): pass - def test_forwardModelling(self): + def test_cleanExecution(self): nx = 100 nz = 200 systemConfig = { - 'dx': 1., # m - 'dz': 1., # m 'c': 2500., # m/s 'nx': nx, # count 'nz': nz, # count
e97b5d343ca80ff050fca6d37efffcfe739b42e0
cloud_maker/py_version.py
cloud_maker/py_version.py
# vim: fileencoding=utf-8 from __future__ import print_function, absolute_import, unicode_literals import sys class VersionError (ValueError): pass def check_ex (): major, minor, patch = sys.version_info[0:2] if major == 3: if minor < 3 or (minor == 3 and patch < 4): raise VersionError("Error: this is Python 3.{}.{}, not 3.3.4+".format(minor, patch)) elif major == 2: if minor < 7: raise VersionError("Error: this is Python 2.{}, not 2.7".format(minor)) else: raise VersionError("Error: this is Python {}, not 2.7 nor 3.x".format(major)) def check (): try: check_ex() except VersionError as e: print(e.args, file=sys.stderr) print("Python 2.7 or 3.3+ is required.", file=sys.stderr) sys.exit(2)
# vim: fileencoding=utf-8 from __future__ import print_function, absolute_import, unicode_literals import sys class VersionError (ValueError): pass def check_ex (): v = sys.version_info if v.major == 3: if v.minor < 3 or (v.minor == 3 and v.micro < 4): raise VersionError("Error: this is Python 3.{}.{}, not 3.3.4+".format(v.minor, v.micro)) elif v.major == 2: if v.minor < 7: raise VersionError("Error: this is Python 2.{}, not 2.7".format(v.minor)) else: raise VersionError("Error: this is Python {}, not 2.7 nor 3.x".format(v.major)) def check (): try: check_ex() except VersionError as e: print(e.args, file=sys.stderr) print("Python 2.7 or 3.3+ is required.", file=sys.stderr) sys.exit(2)
Fix usage of `version_info` on Python 2.
Fix usage of `version_info` on Python 2.
Python
mit
sapphirecat/cloud-maker,sapphirecat/cloud-maker
--- +++ @@ -6,15 +6,15 @@ pass def check_ex (): - major, minor, patch = sys.version_info[0:2] - if major == 3: - if minor < 3 or (minor == 3 and patch < 4): - raise VersionError("Error: this is Python 3.{}.{}, not 3.3.4+".format(minor, patch)) - elif major == 2: - if minor < 7: - raise VersionError("Error: this is Python 2.{}, not 2.7".format(minor)) + v = sys.version_info + if v.major == 3: + if v.minor < 3 or (v.minor == 3 and v.micro < 4): + raise VersionError("Error: this is Python 3.{}.{}, not 3.3.4+".format(v.minor, v.micro)) + elif v.major == 2: + if v.minor < 7: + raise VersionError("Error: this is Python 2.{}, not 2.7".format(v.minor)) else: - raise VersionError("Error: this is Python {}, not 2.7 nor 3.x".format(major)) + raise VersionError("Error: this is Python {}, not 2.7 nor 3.x".format(v.major)) def check (): try:
036a5f879ddf6f8c2f1ae3bfea6a58962783f949
moocng/portal/management/commands/mailtest.py
moocng/portal/management/commands/mailtest.py
# Copyright 2013 Rooter Analysis S.L. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from django.conf import settings from django.core.management.base import BaseCommand from django.core.mail import send_mail class Command(BaseCommand): """send mail test """ def handle(self, *args, **options): send_mail('Testing mail', 'Here is the message.', settings.DEFAULT_FROM_EMAIL, args)
# Copyright 2013 Rooter Analysis S.L. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from datetime import datetime from django.conf import settings from django.core.management.base import BaseCommand from django.core.mail import send_mail class Command(BaseCommand): """send mail test """ def message(self, message): self.stdout.write("%s\n" % message.encode("ascii", "replace")) def handle(self, *args, **options): now = datetime.now() body=""" Hi, this is the testing message send on %s """ % str(now) self.message(body) send_mail('Testing mail - %s' % str(now), body, settings.DEFAULT_FROM_EMAIL, args)
Change subject to every mail to was sent
Change subject to every mail to was sent
Python
apache-2.0
OpenMOOC/moocng,GeographicaGS/moocng,GeographicaGS/moocng,GeographicaGS/moocng,OpenMOOC/moocng,GeographicaGS/moocng
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +from datetime import datetime from django.conf import settings from django.core.management.base import BaseCommand @@ -22,6 +23,19 @@ """send mail test """ + + def message(self, message): + self.stdout.write("%s\n" % message.encode("ascii", "replace")) + def handle(self, *args, **options): - send_mail('Testing mail', 'Here is the message.', + now = datetime.now() + body=""" +Hi, this is the testing message + +send on %s +""" % str(now) + + self.message(body) + + send_mail('Testing mail - %s' % str(now), body, settings.DEFAULT_FROM_EMAIL, args)
08b4fae4352f68a524d51a7e14767e5b093c4a73
social_django/migrations/0005_auto_20160727_2333.py
social_django/migrations/0005_auto_20160727_2333.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-07-28 02:33 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): replaces = [ ('default', '0005_auto_20160727_2333'), ('social_auth', '0005_auto_20160727_2333') ] dependencies = [ ('social_django', '0004_auto_20160423_0400'), ] operations = [ migrations.AlterUniqueTogether( name='association', unique_together=set([('server_url', 'handle')]), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-07-28 02:33 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): replaces = [ ('social_auth', '0005_auto_20160727_2333') ] dependencies = [ ('social_django', '0004_auto_20160423_0400'), ] operations = [ migrations.AlterUniqueTogether( name='association', unique_together=set([('server_url', 'handle')]), ), ]
Remove replacement of non existing migration
Remove replacement of non existing migration Fixes #16
Python
bsd-3-clause
python-social-auth/social-app-django,python-social-auth/social-app-django,python-social-auth/social-app-django
--- +++ @@ -7,7 +7,6 @@ class Migration(migrations.Migration): replaces = [ - ('default', '0005_auto_20160727_2333'), ('social_auth', '0005_auto_20160727_2333') ]
8b9f064a7544360f9932ec03c92ea77b4382f2e3
git-keeper-robot/gkeeprobot/dectorators.py
git-keeper-robot/gkeeprobot/dectorators.py
# Copyright 2018 Nathan Sommer and Ben Coleman # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import time polling_count = 25 def polling(func): def polling_wrapper(*args, **kwargs): for count in range(polling_count): if func(*args, **kwargs): return True time.sleep(.1) return False return polling_wrapper
# Copyright 2018 Nathan Sommer and Ben Coleman # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import time polling_count = 250 def polling(func): def polling_wrapper(*args, **kwargs): for count in range(polling_count): if func(*args, **kwargs): return True time.sleep(.01) return False return polling_wrapper
Increase polling freqency to speed up tests.
Increase polling freqency to speed up tests.
Python
agpl-3.0
git-keeper/git-keeper,git-keeper/git-keeper
--- +++ @@ -15,7 +15,7 @@ import time -polling_count = 25 +polling_count = 250 def polling(func): @@ -23,6 +23,6 @@ for count in range(polling_count): if func(*args, **kwargs): return True - time.sleep(.1) + time.sleep(.01) return False return polling_wrapper
042c11e298dd76c16ef84b2ee1d96d75de6203d4
print_traceback.py
print_traceback.py
import sys import traceback class CustomException(Exception): def __init__(self, *args, **kwargs): super(CustomException, self).__init__(*args, **kwargs) def custom_function(): raise CustomException('Test to raise custom exception.') try: custom_function() except: _type, _value, _traceback = sys.exc_info() for _entry in traceback.format_tb(_traceback): print(_entry)
import sys import traceback class CustomException(Exception): def __init__(self, *args, **kwargs): super(CustomException, self).__init__(*args, **kwargs) def custom_deep_function(): raise CustomException('Test to raise custom exception.') def custom_function(): custom_deep_function() try: custom_function() except: _type, _value, _traceback = sys.exc_info() print(''.join(str(entry) for entry in traceback.format_tb(_traceback, limit=10)))
Print stack trace of exception.
Print stack trace of exception.
Python
mit
iandmyhand/python-utils
--- +++ @@ -5,12 +5,14 @@ def __init__(self, *args, **kwargs): super(CustomException, self).__init__(*args, **kwargs) +def custom_deep_function(): + raise CustomException('Test to raise custom exception.') + def custom_function(): - raise CustomException('Test to raise custom exception.') + custom_deep_function() try: custom_function() except: _type, _value, _traceback = sys.exc_info() - for _entry in traceback.format_tb(_traceback): - print(_entry) + print(''.join(str(entry) for entry in traceback.format_tb(_traceback, limit=10)))
75f7ff7754eee79da9cd0a430a4fa16af21cdd4d
adhocracy4/actions/signals.py
adhocracy4/actions/signals.py
from django.apps import apps from django.conf import settings from django.db.models.signals import post_save from .models import Action from .verbs import Verbs def _extract_target(instance): target = None if hasattr(instance, 'content_object'): target = instance.content_object elif hasattr(instance, 'project'): target = instance.project return target def add_action(sender, instance, created, **kwargs): actor = instance.creator if hasattr(instance, 'creator') else None target = None if created: target = _extract_target(instance) if target: verb = Verbs.ADD.value else: verb = Verbs.CREATE.value else: verb = Verbs.UPDATE.value action = Action( actor=actor, verb=verb, obj=instance, target=target, ) if hasattr(instance, 'project'): action.project = instance.project action.save() for app, model in settings.A4_ACTIONABLES: post_save.connect(add_action, apps.get_model(app, model))
from itertools import chain from django.apps import apps from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.db.models.signals import post_delete, post_save from .models import Action from .verbs import Verbs SYSTEM_ACTIONABLES = ( ('a4phases', 'Phase'), ('a4projects', 'Project') ) def _extract_target(instance): target = None if hasattr(instance, 'content_object'): target = instance.content_object elif hasattr(instance, 'project'): target = instance.project return target def _add_action(sender, instance, created, **kwargs): actor = instance.creator if hasattr(instance, 'creator') else None target = None if created: target = _extract_target(instance) if target: verb = Verbs.ADD.value else: verb = Verbs.CREATE.value else: verb = Verbs.UPDATE.value action = Action( actor=actor, verb=verb, obj=instance, target=target, ) if hasattr(instance, 'project'): action.project = instance.project action.save() for app, model in settings.A4_ACTIONABLES: post_save.connect(_add_action, apps.get_model(app, model)) def _delete_action(sender, instance, **kwargs): contenttype = ContentType.objects.get_for_model(sender) Action.objects\ .filter(obj_content_type=contenttype, obj_object_id=instance.id)\ .delete() for app, model in chain(SYSTEM_ACTIONABLES, settings.A4_ACTIONABLES): post_delete.connect(_delete_action, apps.get_model(app, model))
Delete Actions if the related object is deleted
Delete Actions if the related object is deleted As we are loosing all the information when the object of an action is deleted, the action itself may be deleted, too.
Python
agpl-3.0
liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4
--- +++ @@ -1,9 +1,17 @@ +from itertools import chain from django.apps import apps from django.conf import settings -from django.db.models.signals import post_save +from django.contrib.contenttypes.models import ContentType +from django.db.models.signals import post_delete, post_save from .models import Action from .verbs import Verbs + + +SYSTEM_ACTIONABLES = ( + ('a4phases', 'Phase'), + ('a4projects', 'Project') +) def _extract_target(instance): @@ -15,7 +23,7 @@ return target -def add_action(sender, instance, created, **kwargs): +def _add_action(sender, instance, created, **kwargs): actor = instance.creator if hasattr(instance, 'creator') else None target = None if created: @@ -42,4 +50,15 @@ for app, model in settings.A4_ACTIONABLES: - post_save.connect(add_action, apps.get_model(app, model)) + post_save.connect(_add_action, apps.get_model(app, model)) + + +def _delete_action(sender, instance, **kwargs): + contenttype = ContentType.objects.get_for_model(sender) + Action.objects\ + .filter(obj_content_type=contenttype, obj_object_id=instance.id)\ + .delete() + + +for app, model in chain(SYSTEM_ACTIONABLES, settings.A4_ACTIONABLES): + post_delete.connect(_delete_action, apps.get_model(app, model))
c5cd62969ebee36c99923ad7a5b9e7c527bff6cc
quantecon/__init__.py
quantecon/__init__.py
""" Import the main names to top level. """ try: import numba except: raise ImportError("Cannot import numba from current anaconda distribution. Please run `conda install numba` to install the latest version.") from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV from .ecdf import ECDF from .estspec import smooth, periodogram, ar_periodogram from .graph_tools import DiGraph from .gridtools import cartesian, mlinspace from .kalman import Kalman from .lae import LAE from .arma import ARMA from .lqcontrol import LQ from .lqnash import nnash from .lss import LinearStateSpace from .matrix_eqn import solve_discrete_lyapunov, solve_discrete_riccati from .quadsums import var_quadratic_sum, m_quadratic_sum #->Propose Delete From Top Level from .markov import MarkovChain, random_markov_chain, random_stochastic_matrix, gth_solve, tauchen #Promote to keep current examples working from .markov import mc_compute_stationary, mc_sample_path #Imports that Should be Deprecated with markov package #<- from .rank_nullspace import rank_est, nullspace from .robustlq import RBLQ from . import quad as quad from .util import searchsorted, fetch_nb_dependencies #Add Version Attribute from .version import version as __version__
""" Import the main names to top level. """ try: import numba except: raise ImportError("Cannot import numba from current anaconda distribution. Please run `conda install numba` to install the latest version.") #-Modules-# from . import quad from . import random #-Objects-# from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV from .ecdf import ECDF from .estspec import smooth, periodogram, ar_periodogram from .graph_tools import DiGraph from .gridtools import cartesian, mlinspace from .kalman import Kalman from .lae import LAE from .arma import ARMA from .lqcontrol import LQ from .lqnash import nnash from .lss import LinearStateSpace from .matrix_eqn import solve_discrete_lyapunov, solve_discrete_riccati from .quadsums import var_quadratic_sum, m_quadratic_sum #->Propose Delete From Top Level from .markov import MarkovChain, random_markov_chain, random_stochastic_matrix, gth_solve, tauchen #Promote to keep current examples working from .markov import mc_compute_stationary, mc_sample_path #Imports that Should be Deprecated with markov package #<- from .rank_nullspace import rank_est, nullspace from .robustlq import RBLQ from .util import searchsorted, fetch_nb_dependencies #-Add Version Attribute-# from .version import version as __version__
Update base api to include module and object imports, fix missing import of random subpackage
Update base api to include module and object imports, fix missing import of random subpackage
Python
bsd-3-clause
QuantEcon/QuantEcon.py,oyamad/QuantEcon.py,oyamad/QuantEcon.py,QuantEcon/QuantEcon.py
--- +++ @@ -7,6 +7,11 @@ except: raise ImportError("Cannot import numba from current anaconda distribution. Please run `conda install numba` to install the latest version.") +#-Modules-# +from . import quad +from . import random + +#-Objects-# from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV from .ecdf import ECDF @@ -27,8 +32,7 @@ #<- from .rank_nullspace import rank_est, nullspace from .robustlq import RBLQ -from . import quad as quad from .util import searchsorted, fetch_nb_dependencies -#Add Version Attribute +#-Add Version Attribute-# from .version import version as __version__
05ecac15aa9b975bd83378daa0560182041bef97
src/format_go_correspondance.py
src/format_go_correspondance.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import argparse import re def format_go_correspondance(args): go = {} with open(args.go_correspondance_input, "r") as go_correspondance_input: for line in go_correspondance_input.readlines(): split_line = line[:-1].split('\t') go_name = split_line[0] if split_line[1] == "": continue slim_go_names = split_line[1].split(';') for split_go_name in slim_go_names: go.setdefault(split_go_name,[]).append(go_name) with open(args.go_correspondance_output,"w") as go_correspondance_output: for go_name in go: go_correspondance_output.write(go_name + '\t') go_correspondance_output.write("\t".join(go[go_name]) + "\n") if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--go_correspondance_input', required=True) parser.add_argument('--go_correspondance_output', required=True) args = parser.parse_args() format_go_correspondance(args)
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import argparse import re def format_go_correspondance(args): go = {} with open(args.go_correspondance_input, "r") as go_correspondance_input: for line in go_correspondance_input.readlines(): if not line.startswith('GO'): continue print line split_line = line[:-1].split('\t') go_name = split_line[0] if split_line[1] == "": continue slim_go_names = split_line[1].split(';') for split_go_name in slim_go_names: go.setdefault(split_go_name,[]).append(go_name) with open(args.go_correspondance_output,"w") as go_correspondance_output: for go_name in go: go_correspondance_output.write(go_name + '\t') go_correspondance_output.write("\t".join(go[go_name]) + "\n") if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--go_correspondance_input', required=True) parser.add_argument('--go_correspondance_output', required=True) args = parser.parse_args() format_go_correspondance(args)
Add test for go correspondance file begin
Add test for go correspondance file begin
Python
apache-2.0
ASaiM/group_humann2_uniref_abundances_to_GO,ASaiM/group_humann2_uniref_abundances_to_GO
--- +++ @@ -10,6 +10,10 @@ go = {} with open(args.go_correspondance_input, "r") as go_correspondance_input: for line in go_correspondance_input.readlines(): + if not line.startswith('GO'): + continue + + print line split_line = line[:-1].split('\t') go_name = split_line[0]
52933f030b246615429ac74f7f156b7a33225d7f
opengrid/tests/test_plotting.py
opengrid/tests/test_plotting.py
# -*- coding: utf-8 -*- """ Created on Mon Dec 30 02:37:25 2013 @author: Jan """ import unittest class PlotStyleTest(unittest.TestCase): def test_default(self): from opengrid.library.plotting import plot_style plt = plot_style() class CarpetTest(unittest.TestCase): def test_default(self): import numpy as np import pandas as pd from opengrid.library import plotting index = pd.date_range('2015-1-1', '2015-12-31', freq='h') ser = pd.Series(np.random.normal(size=len(index)), index=index, name='abc') plotting.carpet(ser) if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- """ Created on Mon Dec 30 02:37:25 2013 @author: Jan """ import unittest import pandas as pd from opengrid.library import plotting class PlotStyleTest(unittest.TestCase): def test_default(self): plt = plotting.plot_style() class CarpetTest(unittest.TestCase): def test_default(self): import numpy as np index = pd.date_range('2015-1-1', '2015-12-31', freq='h') ser = pd.Series(np.random.normal(size=len(index)), index=index, name='abc') assert plotting.carpet(ser) is not None def test_empty(self): assert plotting.carpet(pd.Series(index=list('abc'))) is None if __name__ == '__main__': unittest.main()
Resolve RuntimeError: Invalid DISPLAY variable - tst
[BLD] Resolve RuntimeError: Invalid DISPLAY variable - tst
Python
apache-2.0
opengridcc/opengrid
--- +++ @@ -6,22 +6,24 @@ """ import unittest +import pandas as pd +from opengrid.library import plotting class PlotStyleTest(unittest.TestCase): def test_default(self): - from opengrid.library.plotting import plot_style - plt = plot_style() + plt = plotting.plot_style() class CarpetTest(unittest.TestCase): def test_default(self): import numpy as np - import pandas as pd - from opengrid.library import plotting index = pd.date_range('2015-1-1', '2015-12-31', freq='h') ser = pd.Series(np.random.normal(size=len(index)), index=index, name='abc') - plotting.carpet(ser) + assert plotting.carpet(ser) is not None + + def test_empty(self): + assert plotting.carpet(pd.Series(index=list('abc'))) is None if __name__ == '__main__':
33e1c57cd6186820fb95b5d04a1f494710b2ccbe
democracy_club/apps/authorities/management/commands/import_mapit_area_type.py
democracy_club/apps/authorities/management/commands/import_mapit_area_type.py
import time import requests from bs4 import BeautifulSoup from django.core.management.base import BaseCommand from django.contrib.gis.geos import GEOSGeometry from django.contrib.gis.geos import Point from authorities.models import Authority, MapitArea from authorities import constants from authorities.helpers import geocode class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('mapit_type', type=str) def handle(self, *args, **options): print(options) self.get_type_from_mapit(options['mapit_type']) def get_type_from_mapit(self, mapit_type): req = requests.get('%sareas/%s' % ( constants.MAPIT_URL, mapit_type)) for mapit_id, area in list(req.json().items()): authority = Authority.objects.get(mapit_id=area['parent_area']) MapitArea.objects.get_or_create( gss=area['codes']['gss'], parent_authority=authority, name=area['name'], area_type=area['type'], unit_id=area['codes']['unit_id'], type_name=area['type_name'], country_name=area['country_name'], )
""" DIW MTW UTW """ import time import requests from bs4 import BeautifulSoup from django.core.management.base import BaseCommand from django.contrib.gis.geos import GEOSGeometry from django.contrib.gis.geos import Point from authorities.models import Authority, MapitArea from authorities import constants from authorities.helpers import geocode class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('mapit_type', type=str) def handle(self, *args, **options): print(options) self.get_type_from_mapit(options['mapit_type']) def get_type_from_mapit(self, mapit_type): req = requests.get('%sareas/%s' % ( constants.MAPIT_URL, mapit_type)) for mapit_id, area in list(req.json().items()): print(area) authority = Authority.objects.get(mapit_id=area['parent_area']) MapitArea.objects.get_or_create( gss=area['codes']['gss'], parent_authority=authority, name=area['name'], area_type=area['type'], unit_id=area['codes']['unit_id'], type_name=area['type_name'], country_name=area['country_name'], )
Comment for types of area that need importing
Comment for types of area that need importing
Python
bsd-3-clause
DemocracyClub/Website,DemocracyClub/Website,DemocracyClub/Website,DemocracyClub/Website
--- +++ @@ -1,3 +1,9 @@ +""" +DIW +MTW +UTW +""" + import time import requests @@ -25,6 +31,7 @@ req = requests.get('%sareas/%s' % ( constants.MAPIT_URL, mapit_type)) for mapit_id, area in list(req.json().items()): + print(area) authority = Authority.objects.get(mapit_id=area['parent_area']) MapitArea.objects.get_or_create( gss=area['codes']['gss'],
c9c106f37c9fbbca1a93348695563e2587bc0c65
manoseimas/lobbyists/urls.py
manoseimas/lobbyists/urls.py
from django.conf.urls import include, patterns, url from manoseimas.lobbyists import views urlpatterns = patterns( '', url(r'^$', 'manoseimas.lobbyists.views.lobbyists.lobbyist_list'), url(r'^lobbyist/(?P<lobbyist_slug>.+)/$', views.lobbyist_profile, name='lobbyist_profile'), url(r'^json/', include('manoseimas.lobbyists.json_urls')), )
from django.conf.urls import include, patterns, url from manoseimas.lobbyists import views urlpatterns = patterns( '', url(r'^$', 'manoseimas.lobbyists.views.lobbyists.lobbyist_list'), url(r'^lobbyist/(?P<lobbyist_slug>.+)/', views.lobbyist_profile, name='lobbyist_profile'), url(r'^json/', include('manoseimas.lobbyists.json_urls')), )
Remove a useless trailing $
Remove a useless trailing $
Python
agpl-3.0
ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt
--- +++ @@ -5,7 +5,7 @@ urlpatterns = patterns( '', url(r'^$', 'manoseimas.lobbyists.views.lobbyists.lobbyist_list'), - url(r'^lobbyist/(?P<lobbyist_slug>.+)/$', + url(r'^lobbyist/(?P<lobbyist_slug>.+)/', views.lobbyist_profile, name='lobbyist_profile'), url(r'^json/', include('manoseimas.lobbyists.json_urls')), )
cc8e643902eb46f9e9d73a4367518e6ab6195308
kindergarten-garden/kindergarten_garden.py
kindergarten-garden/kindergarten_garden.py
# File: kindergarten_garden.py # Purpose: Write a program that, given a diagram, can tell you which plants each child in the kindergarten class is responsible for. # Programmer: Amal Shehu # Course: Exercism # Date: Thursday 10th September 2016, 10:51 PM
# File: kindergarten_garden.py # Purpose: Write a program that, given a diagram, can tell you which plants each child in the kindergarten class is responsible for. # Programmer: Amal Shehu # Course: Exercism # Date: Thursday 10th September 2016, 10:51 PM class Garden(object): plant_names = {"C": "Clover", "G": "Grass", "R": "Radishes", "V": "Violets"} def __init__(self, blueprint, childern=("Alice Bob Charlie David " "Eve Fred Ginny Harriet " "Ileana Joseph Kincaid Larry"):
Add plant names and childs
Add plant names and childs
Python
mit
amalshehu/exercism-python
--- +++ @@ -3,3 +3,12 @@ # Programmer: Amal Shehu # Course: Exercism # Date: Thursday 10th September 2016, 10:51 PM +class Garden(object): + + plant_names = {"C": "Clover", "G": "Grass", + "R": "Radishes", "V": "Violets"} + + def __init__(self, blueprint, childern=("Alice Bob Charlie David " "Eve Fred Ginny Harriet " "Ileana Joseph Kincaid Larry"): + + +
c386e9608eecc1e21fb30f073800755713267c07
rex/network_feeder.py
rex/network_feeder.py
import time import threading import socket class NetworkFeeder: """ A class that feeds data to a socket port """ def __init__(self, proto, host, port, data, is_client=True, delay=3, timeout=2): if not is_client: raise NotImplementedError("Server mode is not implemented.") if proto != "tcp": raise NotImplementedError("Only TCP mode is supported for now.") self._proto = proto self._is_client = is_client self._delay = delay self._data = data self._host = host self._port = port self._timeout = timeout t = threading.Thread(target=self.worker) t.start() def worker(self): if self._delay: time.sleep(self._delay) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM if self._proto == "tcp" else socket.SOCK_DGRAM) sock.settimeout(self._timeout) sock.connect((self._host, self._port)) sock.send(self._data) sock.close()
import time import threading import socket class NetworkFeeder: """ A class that feeds data to a socket port """ def __init__(self, proto, host, port, data, is_client=True, delay=5, timeout=2): if not is_client: raise NotImplementedError("Server mode is not implemented.") if proto != "tcp": raise NotImplementedError("Only TCP mode is supported for now.") self._proto = proto self._is_client = is_client self._delay = delay self._data = data self._host = host self._port = port self._timeout = timeout t = threading.Thread(target=self.worker) t.start() def worker(self): if self._delay: time.sleep(self._delay) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM if self._proto == "tcp" else socket.SOCK_DGRAM) sock.settimeout(self._timeout) sock.connect((self._host, self._port)) sock.send(self._data) sock.close()
Set default delay to 5 seconds (because of my slow laptop).
NetworkFeeder: Set default delay to 5 seconds (because of my slow laptop).
Python
bsd-2-clause
shellphish/rex,shellphish/rex
--- +++ @@ -9,7 +9,7 @@ A class that feeds data to a socket port """ - def __init__(self, proto, host, port, data, is_client=True, delay=3, timeout=2): + def __init__(self, proto, host, port, data, is_client=True, delay=5, timeout=2): if not is_client: raise NotImplementedError("Server mode is not implemented.")
6ccaf810ddd8934926fd0e1b5b580ca31b3c67c8
app/mod_budget/controller.py
app/mod_budget/controller.py
from flask import Blueprint budget = Blueprint('budget', __name__, template_folder = 'templates') @budget.route('/') def default: return "Hello World!"
from flask import Blueprint budget = Blueprint('budget', __name__, template_folder = 'templates') @budget.route('/') def default(): return "Hello World!"
Fix missing parenthesis for default route in budget module.
Fix missing parenthesis for default route in budget module.
Python
mit
Zillolo/mana-vault,Zillolo/mana-vault,Zillolo/mana-vault
--- +++ @@ -3,5 +3,5 @@ budget = Blueprint('budget', __name__, template_folder = 'templates') @budget.route('/') -def default: +def default(): return "Hello World!"
94d3b36e08a546ef470dd0d8dab55a4be3d4265b
examples/get_config.py
examples/get_config.py
import logging logging.basicConfig() from jenkinsapi.jenkins import Jenkins J = Jenkins('http://localhost:8080') jobName = 'create_fwrgmkbbzk' config = J[jobName].get_config() print config
""" An example of how to use JenkinsAPI to fetch the config XML of a job. """ from jenkinsapi.jenkins import Jenkins J = Jenkins('http://localhost:8080') jobName = 'create_fwrgmkbbzk' config = J[jobName].get_config() print config
Add a comment to this example
Add a comment to this example
Python
mit
imsardine/jenkinsapi,domenkozar/jenkinsapi,jduan/jenkinsapi,mistermocha/jenkinsapi,zaro0508/jenkinsapi,salimfadhley/jenkinsapi,zaro0508/jenkinsapi,aerickson/jenkinsapi,imsardine/jenkinsapi,JohnLZeller/jenkinsapi,aerickson/jenkinsapi,jduan/jenkinsapi,zaro0508/jenkinsapi,mistermocha/jenkinsapi,JohnLZeller/jenkinsapi,salimfadhley/jenkinsapi,imsardine/jenkinsapi,domenkozar/jenkinsapi,JohnLZeller/jenkinsapi,mistermocha/jenkinsapi
--- +++ @@ -1,6 +1,6 @@ -import logging -logging.basicConfig() - +""" +An example of how to use JenkinsAPI to fetch the config XML of a job. +""" from jenkinsapi.jenkins import Jenkins J = Jenkins('http://localhost:8080') jobName = 'create_fwrgmkbbzk'
450f082237e5b302988cece5c6eb091a5d8503df
examples/img_server.py
examples/img_server.py
#!/usr/bin/env python """ This example implements a server taking a single image when receiving a message from the client. The image will be fragmented into chunks. The first packet sent contains the number of chunks to expect. """ import io import picamera import time from nuts import UDPAuthChannel def take_single_picture(): # Create an in-memory stream my_stream = io.BytesIO() with picamera.PiCamera() as camera: camera.start_preview() # Camera warm-up time time.sleep(2) camera.capture(my_stream, 'jpeg') my_stream.seek(0) return my_stream.getvalue() def ceildiv(dividend, divisor): return (dividend + divisor - 1) // divisor channel = UDPAuthChannel('secret') channel.listen( ('10.0.0.1', 8001) ) while True: msg = channel.receive() print msg img = take_single_picture() num_chunks = ceildiv(len(img), msg.session.mtu) channel.send(str(num_chunks), msg.sender) for i in range(num_chunks): chunk = img[i*msg.session.mtu:(i+1)*msg.session.mtu] print('Sending chunk %d of %d' % (i, num_chunks)) channel.send(chunk, msg.sender) time.sleep(0.1)
#!/usr/bin/env python """ This example implements a server taking a single image when receiving a message from the client. The image will be fragmented into chunks. The first packet sent contains the number of chunks to expect. """ import io import picamera import time from nuts import UDPAuthChannel def take_single_picture(): # Create an in-memory stream my_stream = io.BytesIO() with picamera.PiCamera() as camera: camera.start_preview() # Camera warm-up time time.sleep(2) camera.capture(my_stream, 'jpeg') my_stream.seek(0) return my_stream.getvalue() def ceildiv(dividend, divisor): return (dividend + divisor - 1) // divisor channel = UDPAuthChannel('secret') channel.listen( ('10.0.0.1', 8001) ) while True: msg = channel.receive() print('%s said: %s' % (msg.sender, msg)) img = take_single_picture() num_chunks = ceildiv(len(img), msg.session.mtu) channel.send(str(num_chunks), msg.sender) for i in range(num_chunks): chunk = img[i*msg.session.mtu:(i+1)*msg.session.mtu] print('Sending chunk %d of %d' % (i, num_chunks)) channel.send(chunk, msg.sender) time.sleep(0.1)
Remove python2 print from img server
Remove python2 print from img server
Python
mit
thusoy/nuts-auth,thusoy/nuts-auth
--- +++ @@ -31,7 +31,7 @@ channel.listen( ('10.0.0.1', 8001) ) while True: msg = channel.receive() - print msg + print('%s said: %s' % (msg.sender, msg)) img = take_single_picture() num_chunks = ceildiv(len(img), msg.session.mtu) channel.send(str(num_chunks), msg.sender)
1e6f3689a21e12104792236d88e7596cb8397ba5
mezzanine/core/management.py
mezzanine/core/management.py
from django.conf import settings from django.contrib.auth.models import User from django.contrib.auth import models as auth_app from django.db.models.signals import post_syncdb def create_demo_user(app, created_models, verbosity, db, **kwargs): if settings.DEBUG and User in created_models: if verbosity >= 2: print "Creating demo User object" User.objects.create_superuser("demo", "example@example.com", "demo") post_syncdb.connect(create_demo_user, sender=auth_app)
from django.conf import settings from django.contrib.auth.models import User from django.contrib.auth import models as auth_app from django.db.models.signals import post_syncdb def create_demo_user(app, created_models, verbosity, **kwargs): if settings.DEBUG and User in created_models: if verbosity >= 2: print "Creating demo User object" User.objects.create_superuser("demo", "example@example.com", "demo") post_syncdb.connect(create_demo_user, sender=auth_app)
Fix post_syncdb signal for demo user to work with Django 1.1
Fix post_syncdb signal for demo user to work with Django 1.1
Python
bsd-2-clause
nikolas/mezzanine,AlexHill/mezzanine,webounty/mezzanine,douglaskastle/mezzanine,nikolas/mezzanine,christianwgd/mezzanine,jjz/mezzanine,guibernardino/mezzanine,stbarnabas/mezzanine,promil23/mezzanine,spookylukey/mezzanine,ryneeverett/mezzanine,gradel/mezzanine,jerivas/mezzanine,fusionbox/mezzanine,guibernardino/mezzanine,mush42/mezzanine,geodesign/mezzanine,orlenko/sfpirg,tuxinhang1989/mezzanine,viaregio/mezzanine,dsanders11/mezzanine,frankier/mezzanine,vladir/mezzanine,dovydas/mezzanine,Cajoline/mezzanine,ZeroXn/mezzanine,jerivas/mezzanine,molokov/mezzanine,Skytorn86/mezzanine,wbtuomela/mezzanine,SoLoHiC/mezzanine,spookylukey/mezzanine,adrian-the-git/mezzanine,jjz/mezzanine,Cajoline/mezzanine,gbosh/mezzanine,tuxinhang1989/mezzanine,christianwgd/mezzanine,viaregio/mezzanine,ryneeverett/mezzanine,Cajoline/mezzanine,ryneeverett/mezzanine,molokov/mezzanine,ZeroXn/mezzanine,joshcartme/mezzanine,scarcry/snm-mezzanine,wyzex/mezzanine,readevalprint/mezzanine,molokov/mezzanine,biomassives/mezzanine,industrydive/mezzanine,vladir/mezzanine,SoLoHiC/mezzanine,damnfine/mezzanine,Kniyl/mezzanine,frankchin/mezzanine,dovydas/mezzanine,saintbird/mezzanine,eino-makitalo/mezzanine,agepoly/mezzanine,spookylukey/mezzanine,orlenko/sfpirg,eino-makitalo/mezzanine,adrian-the-git/mezzanine,damnfine/mezzanine,viaregio/mezzanine,wyzex/mezzanine,readevalprint/mezzanine,batpad/mezzanine,emile2016/mezzanine,dustinrb/mezzanine,frankchin/mezzanine,Kniyl/mezzanine,wbtuomela/mezzanine,dekomote/mezzanine-modeltranslation-backport,frankier/mezzanine,Kniyl/mezzanine,saintbird/mezzanine,mush42/mezzanine,wyzex/mezzanine,dsanders11/mezzanine,PegasusWang/mezzanine,orlenko/sfpirg,joshcartme/mezzanine,cccs-web/mezzanine,promil23/mezzanine,geodesign/mezzanine,wrwrwr/mezzanine,promil23/mezzanine,theclanks/mezzanine,fusionbox/mezzanine,sjdines/mezzanine,wrwrwr/mezzanine,orlenko/plei,dsanders11/mezzanine,Skytorn86/mezzanine,Cicero-Zhao/mezzanine,readevalprint/mezzanine,wbtuomela/mezzanine,sjuxax/mezzanine,christianwgd/mezzanine,orlenko/plei,tuxinhang1989/mezzanine,stbarnabas/mezzanine,vladir/mezzanine,jjz/mezzanine,batpad/mezzanine,scarcry/snm-mezzanine,stephenmcd/mezzanine,jerivas/mezzanine,sjdines/mezzanine,orlenko/plei,gradel/mezzanine,joshcartme/mezzanine,theclanks/mezzanine,dovydas/mezzanine,saintbird/mezzanine,biomassives/mezzanine,biomassives/mezzanine,dekomote/mezzanine-modeltranslation-backport,Cicero-Zhao/mezzanine,agepoly/mezzanine,adrian-the-git/mezzanine,stephenmcd/mezzanine,PegasusWang/mezzanine,SoLoHiC/mezzanine,sjuxax/mezzanine,PegasusWang/mezzanine,sjdines/mezzanine,frankier/mezzanine,webounty/mezzanine,dustinrb/mezzanine,sjuxax/mezzanine,damnfine/mezzanine,Skytorn86/mezzanine,stephenmcd/mezzanine,theclanks/mezzanine,industrydive/mezzanine,ZeroXn/mezzanine,dekomote/mezzanine-modeltranslation-backport,emile2016/mezzanine,mush42/mezzanine,emile2016/mezzanine,gbosh/mezzanine,AlexHill/mezzanine,gradel/mezzanine,scarcry/snm-mezzanine,eino-makitalo/mezzanine,cccs-web/mezzanine,dustinrb/mezzanine,douglaskastle/mezzanine,gbosh/mezzanine,geodesign/mezzanine,nikolas/mezzanine,douglaskastle/mezzanine,frankchin/mezzanine,industrydive/mezzanine,agepoly/mezzanine,webounty/mezzanine
--- +++ @@ -5,7 +5,7 @@ from django.db.models.signals import post_syncdb -def create_demo_user(app, created_models, verbosity, db, **kwargs): +def create_demo_user(app, created_models, verbosity, **kwargs): if settings.DEBUG and User in created_models: if verbosity >= 2: print "Creating demo User object"
8ddab20fd41217fe4ea9b5e267443a4953d2d8f7
apps/authentication/forms.py
apps/authentication/forms.py
from django import forms class SignupForm(forms.Form): def signup(self, request, user): user.is_active = False user.save()
from django import forms from django.core.mail import send_mail class SignupForm(forms.Form): def signup(self, request, user): user.is_active = False user.save() send_mail( 'New user on MyQuotes', 'There is one new user asking for access. ID: {id}, Email: {email}'.format(id=user.id, email=user.email), 'MyQuotes<contact@myquotes.io>', ['lucianfurtun@gmail.com'], fail_silently=True, )
Add email notification when new user has signed up
Add email notification when new user has signed up
Python
bsd-3-clause
lucifurtun/myquotes,lucifurtun/myquotes,lucifurtun/myquotes,lucifurtun/myquotes
--- +++ @@ -1,7 +1,16 @@ from django import forms +from django.core.mail import send_mail class SignupForm(forms.Form): def signup(self, request, user): user.is_active = False user.save() + + send_mail( + 'New user on MyQuotes', + 'There is one new user asking for access. ID: {id}, Email: {email}'.format(id=user.id, email=user.email), + 'MyQuotes<contact@myquotes.io>', + ['lucianfurtun@gmail.com'], + fail_silently=True, + )
ccb558526cd738c5312556a2a6f34471a3202091
polymorphic_auth/tests/settings.py
polymorphic_auth/tests/settings.py
""" Test settings for ``polymorphic_auth`` app. """ AUTH_USER_MODEL = 'polymorphic_auth.User' POLYMORPHIC_AUTH = { 'DEFAULT_CHILD_MODEL': 'polymorphic_auth_email.EmailUser', } DATABASES = { 'default': { 'ATOMIC_REQUESTS': True, 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'polymorphic_auth', } } DEBUG = True EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django_nose', 'polymorphic_auth', 'polymorphic_auth.tests', 'polymorphic_auth.usertypes.email', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) ROOT_URLCONF = 'polymorphic_auth.tests.urls' SECRET_KEY = 'secret-key' STATIC_URL = '/static/' TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
""" Test settings for ``polymorphic_auth`` app. """ AUTH_USER_MODEL = 'polymorphic_auth.User' POLYMORPHIC_AUTH = { 'DEFAULT_CHILD_MODEL': 'polymorphic_auth_email.EmailUser', } DATABASES = { 'default': { 'ATOMIC_REQUESTS': True, 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'polymorphic_auth', } } DEBUG = True EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django_nose', 'polymorphic', 'polymorphic_auth', 'polymorphic_auth.tests', 'polymorphic_auth.usertypes.email', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'polymorphic_auth.tests.urls' SECRET_KEY = 'secret-key' STATIC_URL = '/static/' TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
Add `polymorphic` to `INSTALLED_APPS`, and also `MessageMiddlware` (because Django wants it).
Add `polymorphic` to `INSTALLED_APPS`, and also `MessageMiddlware` (because Django wants it).
Python
mit
ixc/django-polymorphic-auth
--- +++ @@ -25,6 +25,7 @@ 'django.contrib.sessions', 'django.contrib.staticfiles', 'django_nose', + 'polymorphic', 'polymorphic_auth', 'polymorphic_auth.tests', 'polymorphic_auth.usertypes.email', @@ -33,6 +34,7 @@ MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'polymorphic_auth.tests.urls'
3ff5ae10396da6571c54d1aebf7b604c2946bbe4
_tests/run_tests.py
_tests/run_tests.py
#!/usr/bin/env python # -*- encoding: utf-8 import pytest import requests @pytest.mark.parametrize('path', [ # Check pagination is working correctly '/page/2/', '/page/3/', ]) def test_pages_appear_correctly(path): resp = requests.get(f'http://localhost:5757/{path}') assert resp.status_code == 200
#!/usr/bin/env python # -*- encoding: utf-8 import pytest import requests @pytest.mark.parametrize('path', [ # Check pagination is working correctly '/page/2/', '/page/3/', ]) def test_pages_appear_correctly(path): resp = requests.get(f'http://localhost:5757/{path}') assert resp.status_code == 200 @pytest.mark.parametrize('path, text_in_page', [ ('2017/', 'Posts from 2017'), ('2017/09/', 'Posts from September 2017'), ('', 'Older posts') ]) def test_text_appears_in_pages(path, text_in_page): resp = requests.get(f'http://localhost:5757/{path}') assert resp.status_code == 200 assert text_in_page in resp.text
Add tests for year and month archives
Add tests for year and month archives
Python
mit
alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net
--- +++ @@ -12,3 +12,14 @@ def test_pages_appear_correctly(path): resp = requests.get(f'http://localhost:5757/{path}') assert resp.status_code == 200 + + +@pytest.mark.parametrize('path, text_in_page', [ + ('2017/', 'Posts from 2017'), + ('2017/09/', 'Posts from September 2017'), + ('', 'Older posts') +]) +def test_text_appears_in_pages(path, text_in_page): + resp = requests.get(f'http://localhost:5757/{path}') + assert resp.status_code == 200 + assert text_in_page in resp.text
a0f0da456ad2142a179c789f63b3dd234979c68c
contrib/python-myna/myna/__init__.py
contrib/python-myna/myna/__init__.py
import shim tmpdir = None def setUp(): global tmpdir tmpdir = shim.setup_shim_for('kubectl') def tearDown(): global tmpdir shim.teardown_shim_dir(tmpdir)
from . import shim tmpdir = None def setUp(): global tmpdir tmpdir = shim.setup_shim_for('kubectl') def tearDown(): global tmpdir shim.teardown_shim_dir(tmpdir)
Update relative imports in the Python library to support Python3
Update relative imports in the Python library to support Python3
Python
apache-2.0
SpectoLabs/myna,SpectoLabs/myna
--- +++ @@ -1,4 +1,4 @@ -import shim +from . import shim tmpdir = None
969344a4ed822eafcfbf7bd9d666ca45bf38168f
mass_mailing_partner/wizard/partner_merge.py
mass_mailing_partner/wizard/partner_merge.py
# Copyright 2020 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import models class BasePartnerMergeAutomaticWizard(models.TransientModel): _inherit = "base.partner.merge.automatic.wizard" def _merge(self, partner_ids, dst_partner=None, extra_checks=True): if dst_partner: contacts = self.env["mailing.contact"].search( [("partner_id", "in", partner_ids)] ) if contacts: contacts = contacts.sorted( lambda x: 1 if x.partner_id == dst_partner else 0 ) list_ids = contacts.mapped("list_ids").ids contacts[1:].unlink() contacts[0].partner_id = dst_partner contacts[0].list_ids = [(4, x) for x in list_ids] return super()._merge( partner_ids, dst_partner=dst_partner, extra_checks=extra_checks )
# Copyright 2020 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import models class BasePartnerMergeAutomaticWizard(models.TransientModel): _inherit = "base.partner.merge.automatic.wizard" def _merge(self, partner_ids, dst_partner=None, extra_checks=True): if dst_partner: contacts = ( self.env["mailing.contact"] .sudo() .search([("partner_id", "in", partner_ids)]) ) if contacts: contacts = contacts.sorted( lambda x: 1 if x.partner_id == dst_partner else 0 ) list_ids = contacts.mapped("list_ids").ids contacts[1:].unlink() contacts[0].partner_id = dst_partner contacts[0].list_ids = [(4, x) for x in list_ids] return super()._merge( partner_ids, dst_partner=dst_partner, extra_checks=extra_checks )
Add sudo() to prevent user without mailing access try to merge contacts
[FIX] mass_mailing_partner: Add sudo() to prevent user without mailing access try to merge contacts
Python
agpl-3.0
OCA/social,OCA/social,OCA/social
--- +++ @@ -9,8 +9,10 @@ def _merge(self, partner_ids, dst_partner=None, extra_checks=True): if dst_partner: - contacts = self.env["mailing.contact"].search( - [("partner_id", "in", partner_ids)] + contacts = ( + self.env["mailing.contact"] + .sudo() + .search([("partner_id", "in", partner_ids)]) ) if contacts: contacts = contacts.sorted(
7a50f9e69e8b9c57b87eb113e8b6736a94d43866
satchmo/product/templatetags/satchmo_product.py
satchmo/product/templatetags/satchmo_product.py
from django import template from django.conf import settings from django.core import urlresolvers from django.template import Context, Template from django.utils.translation import get_language, ugettext_lazy as _ from satchmo.configuration import config_value from satchmo.product.models import Category from satchmo.shop.templatetags import get_filter_args register = template.Library() def is_producttype(product, ptype): """Returns True if product is ptype""" if ptype in product.get_subtypes(): return "true" else: return "" register.filter('is_producttype', is_producttype) def product_images(product, args=""): args, kwargs = get_filter_args(args, keywords=('include_main', 'maximum'), boolargs=('include_main'), intargs=('maximum'), stripquotes=True) q = product.productimage_set if kwargs.get('include_main', True): q = q.all() else: main = product.main_image q = q.exclude(id = main.id) maximum = kwargs.get('maximum', -1) if maximum>-1: q = list(q)[:maximum] return q register.filter('product_images', product_images) def smart_attr(product, key): """Run the smart_attr function on the spec'd product """ return product.smart_attr(key) register.filter('smart_attr', smart_attr)
from django import template from django.conf import settings from django.core import urlresolvers from django.template import Context, Template from django.utils.translation import get_language, ugettext_lazy as _ from satchmo.configuration import config_value from satchmo.product.models import Category from satchmo.shop.templatetags import get_filter_args register = template.Library() def is_producttype(product, ptype): """Returns True if product is ptype""" if ptype in product.get_subtypes(): return True else: return False register.filter('is_producttype', is_producttype) def product_images(product, args=""): args, kwargs = get_filter_args(args, keywords=('include_main', 'maximum'), boolargs=('include_main'), intargs=('maximum'), stripquotes=True) q = product.productimage_set if kwargs.get('include_main', True): q = q.all() else: main = product.main_image q = q.exclude(id = main.id) maximum = kwargs.get('maximum', -1) if maximum>-1: q = list(q)[:maximum] return q register.filter('product_images', product_images) def smart_attr(product, key): """Run the smart_attr function on the spec'd product """ return product.smart_attr(key) register.filter('smart_attr', smart_attr)
Change the is_producttype template tag to return a boolean rather than a string.
Change the is_producttype template tag to return a boolean rather than a string.
Python
bsd-3-clause
grengojbo/satchmo,grengojbo/satchmo
--- +++ @@ -12,15 +12,15 @@ def is_producttype(product, ptype): """Returns True if product is ptype""" if ptype in product.get_subtypes(): - return "true" + return True else: - return "" + return False register.filter('is_producttype', is_producttype) def product_images(product, args=""): - args, kwargs = get_filter_args(args, - keywords=('include_main', 'maximum'), + args, kwargs = get_filter_args(args, + keywords=('include_main', 'maximum'), boolargs=('include_main'), intargs=('maximum'), stripquotes=True) @@ -31,11 +31,11 @@ else: main = product.main_image q = q.exclude(id = main.id) - + maximum = kwargs.get('maximum', -1) if maximum>-1: q = list(q)[:maximum] - + return q register.filter('product_images', product_images) @@ -44,5 +44,5 @@ """Run the smart_attr function on the spec'd product """ return product.smart_attr(key) - + register.filter('smart_attr', smart_attr)
7c85e2b278667e7340c7c6bf57c3c0c91210c471
coolfig/__init__.py
coolfig/__init__.py
""" Support for working with different sources of configuration values. class DefaultSettings(schema.Settings): SECRET_KEY = schema.Value(str) DEBUG = schema.Value(types.boolean, default=False) DB_URL = schema.Value(types.sqlalchemy_url) LOCALES = schema.Value(types.list(str)) settings = DefaultSettings( providers.DictConfig(os.environ, prefix='MYAPP_')) """ from .schema import Value, Settings __version__ = '0.2.0' __url__ = 'https://github.com/GaretJax/coolfig' __all__ = ['Value', 'Settings']
""" Support for working with different sources of configuration values. class DefaultSettings(schema.Settings): SECRET_KEY = schema.Value(str) DEBUG = schema.Value(types.boolean, default=False) DB_URL = schema.Value(types.sqlalchemy_url) LOCALES = schema.Value(types.list(str)) settings = DefaultSettings( providers.DictConfig(os.environ, prefix='MYAPP_')) """ from .schema import Value, Settings from .providers import EnvConfig, DictConfig from .django import load_django_settings __version__ = '0.2.0' __url__ = 'https://github.com/GaretJax/coolfig' __all__ = ['Value', 'Settings', 'EnvConfig', 'DictConfig', 'load_django_settings']
Add some more importing shortcuts
Add some more importing shortcuts
Python
mit
GaretJax/coolfig
--- +++ @@ -11,8 +11,11 @@ providers.DictConfig(os.environ, prefix='MYAPP_')) """ from .schema import Value, Settings +from .providers import EnvConfig, DictConfig +from .django import load_django_settings __version__ = '0.2.0' __url__ = 'https://github.com/GaretJax/coolfig' -__all__ = ['Value', 'Settings'] +__all__ = ['Value', 'Settings', 'EnvConfig', 'DictConfig', + 'load_django_settings']
726662d102453f7c7be5fb31499a8c4d5ab34444
apps/storybase_user/models.py
apps/storybase_user/models.py
from django.contrib.auth.models import User from django.db import models from uuidfield.fields import UUIDField from storybase.fields import ShortTextField class Organization(models.Model): """ An organization or a community group that users and stories can be associated with. """ organization_id = UUIDField(auto=True) name = ShortTextField() slug = models.SlugField() website_url = models.URLField(blank=True) description = models.TextField(blank=True) members = models.ManyToManyField(User, related_name='organizations', blank=True) created = models.DateTimeField(auto_now_add=True) last_edited = models.DateTimeField(auto_now=True) def __unicode__(self): return self.name @models.permalink def get_absolute_url(self): return ('organization_detail', [self.organization_id]) class Project(models.Model): """ A project that collects related stories. Users can also be related to projects. """ project_id = UUIDField(auto=True) name = ShortTextField() slug = models.SlugField() website_url = models.URLField(blank=True) description = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True) last_edited = models.DateTimeField(auto_now=True) organizations = models.ManyToManyField(Organization, related_name='projects', blank=True) members = models.ManyToManyField(User, related_name='projects', blank=True) # TODO: Add Stories field to Project def __unicode__(self): return self.name
from django.contrib.auth.models import User from django.db import models from uuidfield.fields import UUIDField from storybase.fields import ShortTextField class Organization(models.Model): """ An organization or a community group that users and stories can be associated with. """ organization_id = UUIDField(auto=True) name = ShortTextField() slug = models.SlugField() website_url = models.URLField(blank=True) description = models.TextField(blank=True) members = models.ManyToManyField(User, related_name='organizations', blank=True) created = models.DateTimeField(auto_now_add=True) last_edited = models.DateTimeField(auto_now=True) def __unicode__(self): return self.name @models.permalink def get_absolute_url(self): return ('organization_detail', [self.organization_id]) class Project(models.Model): """ A project that collects related stories. Users can also be related to projects. """ project_id = UUIDField(auto=True) name = models.CharField(max_length=200) slug = models.SlugField() members = models.ManyToManyField(User, related_name='projects', blank=True) def __unicode__(self): return self.name
Revert "Updated fields for Project model."
Revert "Updated fields for Project model." This reverts commit f68fc56dd2a7ec59d472806ffc14e993686e1f24.
Python
mit
denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase
--- +++ @@ -28,15 +28,9 @@ Users can also be related to projects. """ project_id = UUIDField(auto=True) - name = ShortTextField() + name = models.CharField(max_length=200) slug = models.SlugField() - website_url = models.URLField(blank=True) - description = models.TextField(blank=True) - created = models.DateTimeField(auto_now_add=True) - last_edited = models.DateTimeField(auto_now=True) - organizations = models.ManyToManyField(Organization, related_name='projects', blank=True) members = models.ManyToManyField(User, related_name='projects', blank=True) - # TODO: Add Stories field to Project def __unicode__(self): return self.name
787abe44ca65fb879ef8a6534bdf671d01f8a045
runtests.py
runtests.py
import sys try: from django.conf import settings settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, ROOT_URLCONF='publisher.urls', INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sites', 'publisher', ], SITE_ID=1, NOSE_ARGS=['-s'], ) try: import django setup = django.setup except AttributeError: pass else: setup() from django_nose import NoseTestSuiteRunner except ImportError: raise ImportError('To fix this error, run: pip install -r requirements-test.txt') def run_tests(*test_args): if not test_args: test_args = ['tests'] # Run tests test_runner = NoseTestSuiteRunner(verbosity=1) failures = test_runner.run_tests(test_args) if failures: sys.exit(failures) if __name__ == '__main__': run_tests(*sys.argv[1:])
import sys try: from django.conf import settings settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, ROOT_URLCONF='publisher.urls', INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sites', 'publisher', ], SITE_ID=1, NOSE_ARGS=['-s'], ) try: import django setup = django.setup except AttributeError: pass else: setup() from django_nose import NoseTestSuiteRunner except ImportError: raise ImportError('To fix this error, run: pip install -r requirements-test.txt') def run_tests(*test_args): if not test_args: test_args = ['publisher.tests.tests'] # Run tests test_runner = NoseTestSuiteRunner(verbosity=1) failures = test_runner.run_tests(test_args) if failures: sys.exit(failures) if __name__ == '__main__': run_tests(*sys.argv[1:])
Fix test runner importing wrong module.
Fix test runner importing wrong module.
Python
bsd-3-clause
wearehoods/django-model-publisher-ai,wearehoods/django-model-publisher-ai,wearehoods/django-model-publisher-ai,jp74/django-model-publisher,jp74/django-model-publisher,jp74/django-model-publisher
--- +++ @@ -37,7 +37,7 @@ def run_tests(*test_args): if not test_args: - test_args = ['tests'] + test_args = ['publisher.tests.tests'] # Run tests test_runner = NoseTestSuiteRunner(verbosity=1)
00e5adf2aa4223e37a191a454300d888af5687f5
src/pip/__pip-runner__.py
src/pip/__pip-runner__.py
"""Execute exactly this copy of pip, within a different environment. This file is named as it is, to ensure that this module can't be imported via an import statement. """ import importlib.util import runpy import sys import types from importlib.machinery import ModuleSpec from os.path import dirname, join from typing import Optional, Sequence, Union PIP_SOURCES_ROOT = dirname(dirname(dirname(__file__))) class PipImportRedirectingFinder: @classmethod def find_spec( self, fullname: str, path: Optional[Sequence[Union[bytes, str]]] = None, target: Optional[types.ModuleType] = None, ) -> Optional[ModuleSpec]: if not fullname.startswith("pip."): return None # Import pip from the source directory of this file location = join(PIP_SOURCES_ROOT, *fullname.split(".")) return importlib.util.spec_from_file_location(fullname, location) sys.meta_path.insert(0, PipImportRedirectingFinder()) assert __name__ == "__main__", "Cannot run __pip-runner__.py as a non-main module" runpy.run_module("pip", run_name="__main__")
"""Execute exactly this copy of pip, within a different environment. This file is named as it is, to ensure that this module can't be imported via an import statement. """ import runpy import sys import types from importlib.machinery import ModuleSpec, PathFinder from os.path import dirname from typing import Optional, Sequence, Union PIP_SOURCES_ROOT = dirname(dirname(__file__)) class PipImportRedirectingFinder: @classmethod def find_spec( self, fullname: str, path: Optional[Sequence[Union[bytes, str]]] = None, target: Optional[types.ModuleType] = None, ) -> Optional[ModuleSpec]: if fullname != "pip": return None spec = PathFinder.find_spec(fullname, [PIP_SOURCES_ROOT], target) assert spec, (PIP_SOURCES_ROOT, fullname) return spec sys.meta_path.insert(0, PipImportRedirectingFinder()) assert __name__ == "__main__", "Cannot run __pip-runner__.py as a non-main module" runpy.run_module("pip", run_name="__main__", alter_sys=True)
Rework the pip runner to use `PathFinder`
Rework the pip runner to use `PathFinder` This makes it possible to only "replace" `pip` and have the submodules get correctly located by the regular importlib machinery. This also asserts that it was able to locate the module, ensuring that failure to locate the module results in an exception.
Python
mit
pypa/pip,sbidoul/pip,pfmoore/pip,pfmoore/pip,pypa/pip,pradyunsg/pip,pradyunsg/pip,sbidoul/pip
--- +++ @@ -4,15 +4,14 @@ an import statement. """ -import importlib.util import runpy import sys import types -from importlib.machinery import ModuleSpec -from os.path import dirname, join +from importlib.machinery import ModuleSpec, PathFinder +from os.path import dirname from typing import Optional, Sequence, Union -PIP_SOURCES_ROOT = dirname(dirname(dirname(__file__))) +PIP_SOURCES_ROOT = dirname(dirname(__file__)) class PipImportRedirectingFinder: @@ -23,15 +22,15 @@ path: Optional[Sequence[Union[bytes, str]]] = None, target: Optional[types.ModuleType] = None, ) -> Optional[ModuleSpec]: - if not fullname.startswith("pip."): + if fullname != "pip": return None - # Import pip from the source directory of this file - location = join(PIP_SOURCES_ROOT, *fullname.split(".")) - return importlib.util.spec_from_file_location(fullname, location) + spec = PathFinder.find_spec(fullname, [PIP_SOURCES_ROOT], target) + assert spec, (PIP_SOURCES_ROOT, fullname) + return spec sys.meta_path.insert(0, PipImportRedirectingFinder()) assert __name__ == "__main__", "Cannot run __pip-runner__.py as a non-main module" -runpy.run_module("pip", run_name="__main__") +runpy.run_module("pip", run_name="__main__", alter_sys=True)
7d722b5ff87ae1306e089e1bf5839632e628b663
aws/customise-stack-template.py
aws/customise-stack-template.py
from amazonia.classes.sns import SNS from troposphere import Ref, Join, cloudwatch from troposphere.sns import Topic, Subscription def user_registration_topic(emails): return topic("UserRegistrationReceived", emails) def topic(topic_title, emails): topic = Topic(topic_title, DisplayName=Join("", [Ref("AWS::StackName"), "-", topic_title])) topic.Subscription = [] for index, email in enumerate(emails): topic.Subscription.append(Subscription( topic_title + "Subscription" + str(index), Endpoint=email, Protocol="email")) return topic def customise_stack_template(template): template.add_resource(user_registration_topic([])) return template
from amazonia.classes.sns import SNS from troposphere import Ref, Join, cloudwatch from troposphere.sns import Topic, Subscription def user_registration_topic(emails): return topic("UserRegistrationReceived", emails) def new_cors_site_request_received_topic(emails): return topic("NewCorsSiteRequestReceived", emails) def topic(topic_title, emails): topic = Topic(topic_title, DisplayName=Join("", [Ref("AWS::StackName"), "-", topic_title])) topic.Subscription = [] for index, email in enumerate(emails): topic.Subscription.append(Subscription( topic_title + "Subscription" + str(index), Endpoint=email, Protocol="email")) return topic def customise_stack_template(template): template.add_resource(user_registration_topic([])) template.add_resource(new_cors_site_request_received_topic([])) return template
Add SNS topic for event NewCorsSiteRequestReceived
Add SNS topic for event NewCorsSiteRequestReceived
Python
bsd-3-clause
GeoscienceAustralia/geodesy-domain-model,GeoscienceAustralia/Geodesy-Web-Services,GeoscienceAustralia/Geodesy-Web-Services,GeoscienceAustralia/Geodesy-Web-Services,GeoscienceAustralia/geodesy-domain-model,GeoscienceAustralia/Geodesy-Web-Services
--- +++ @@ -5,6 +5,9 @@ def user_registration_topic(emails): return topic("UserRegistrationReceived", emails) + +def new_cors_site_request_received_topic(emails): + return topic("NewCorsSiteRequestReceived", emails) def topic(topic_title, emails): topic = Topic(topic_title, @@ -21,4 +24,5 @@ def customise_stack_template(template): template.add_resource(user_registration_topic([])) + template.add_resource(new_cors_site_request_received_topic([])) return template
d0e634e4472dcd82009801626c8e51d0a16fcae6
cfp/management/commands/update_talks_and_workshops_from_applications.py
cfp/management/commands/update_talks_and_workshops_from_applications.py
from django.core.management.base import BaseCommand, CommandError from events.models import Event class Command(BaseCommand): help = "Copies talk title and descriptions from the application." def add_arguments(self, parser): parser.add_argument('event_id', type=int) def handle(self, *args, **options): event_id = options["event_id"] event = Event.objects.filter(pk=event_id).first() if not event: raise CommandError("Event id={} does not exist.".format(event_id)) talks = event.talks.all().order_by("title") talk_count = talks.count() workshops = event.workshops.all().order_by("title") workshop_count = workshops.count() if not talk_count and not workshops: raise CommandError("No talks or workshops matched.") print(f"Matched {talk_count} talks:") for talk in talks: print("> ", talk) print(f"\nMatched {workshop_count} workshops:") for workshop in workshops: print("> ", workshop) print("\nUpdate talk descriptions from talks?") input("Press any key to continue or Ctrl+C to abort") for talk in talks: talk.update_from_application() talk.save() print("Done.")
from django.core.management.base import BaseCommand, CommandError from events.models import Event class Command(BaseCommand): help = "Copies talk title and descriptions from the application." def add_arguments(self, parser): parser.add_argument('event_id', type=int) def handle(self, *args, **options): event_id = options["event_id"] event = Event.objects.filter(pk=event_id).first() if not event: raise CommandError("Event id={} does not exist.".format(event_id)) talks = event.talks.all().order_by("title") talk_count = talks.count() workshops = event.workshops.all().order_by("title") workshop_count = workshops.count() if not talk_count and not workshops: raise CommandError("No talks or workshops matched.") print(f"Matched {talk_count} talks:") for talk in talks: print("> ", talk) print(f"\nMatched {workshop_count} workshops:") for workshop in workshops: print("> ", workshop) print("\nUpdate talk descriptions from talks?") input("Press any key to continue or Ctrl+C to abort") for talk in talks: talk.update_from_application() talk.save() for workshop in workshops: workshop.update_from_application() workshop.save() print("Done.")
Update workshops as well as talks
Update workshops as well as talks
Python
bsd-3-clause
WebCampZg/conference-web,WebCampZg/conference-web,WebCampZg/conference-web
--- +++ @@ -40,4 +40,8 @@ talk.update_from_application() talk.save() + for workshop in workshops: + workshop.update_from_application() + workshop.save() + print("Done.")
2c4524c1f40ef9963caefec4ed258974b80a6db1
messente/api/sms/__init__.py
messente/api/sms/__init__.py
# -*- coding: utf-8 -*- # Copyright 2016 Messente Communications OÜ # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function from messente.api.sms import api from messente.api.sms.constants import VERSION from messente.api.sms.messente import Messente
# -*- coding: utf-8 -*- # Copyright 2016 Messente Communications OÜ # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function from messente.api.sms import api from messente.api.sms.constants import VERSION from messente.api.sms.messente import Messente __all__ = ["api", "VERSION", "Messente"]
Define public interface in sms module
Define public interface in sms module
Python
apache-2.0
messente/messente-python
--- +++ @@ -19,3 +19,6 @@ from messente.api.sms import api from messente.api.sms.constants import VERSION from messente.api.sms.messente import Messente + + +__all__ = ["api", "VERSION", "Messente"]
456bf650d0c6c487616869986ca29bab4768b0cb
dash2012/fabfile.py
dash2012/fabfile.py
#encoding: utf-8 from fabric.api import run, settings, cd, env env.use_ssh_config = True env.ssh_config_path = '~/.ssh/config' def deploy(): with settings(host_string='dash.daltonmatos.com'): with cd("/var/mongrel2/apps/djangodash2012.daltonmatos.com"): with cd("app/djangodash2012/"): run("git reset --hard") run("git pull origin master") run("wsgid restart")
#encoding: utf-8 from fabric.api import run, settings, cd, env env.use_ssh_config = True env.ssh_config_path = '~/.ssh/config' def deploy(branch='master'): with settings(host_string='dash.daltonmatos.com'): with cd("/var/mongrel2/apps/djangodash2012.daltonmatos.com"): with cd("app/djangodash2012/"): run("git reset --hard") run("git checkout {branch}".format(branch=branch)) run("git pull origin {branch}".format(branch=branch)) run("wsgid restart")
Choose which branch will be deployed
Choose which branch will be deployed
Python
bsd-3-clause
losmiserables/djangodash2012,losmiserables/djangodash2012
--- +++ @@ -5,10 +5,11 @@ env.ssh_config_path = '~/.ssh/config' -def deploy(): +def deploy(branch='master'): with settings(host_string='dash.daltonmatos.com'): with cd("/var/mongrel2/apps/djangodash2012.daltonmatos.com"): with cd("app/djangodash2012/"): run("git reset --hard") - run("git pull origin master") + run("git checkout {branch}".format(branch=branch)) + run("git pull origin {branch}".format(branch=branch)) run("wsgid restart")
5b63b724a89c11aa06a8281cf778063c4a8a7096
Artifactor/views.py
Artifactor/views.py
# -*- coding: utf-8 -*- # vim: set ts=4 from django.forms import ModelForm from django.http import Http404, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.views.decorators.csrf import csrf_exempt from Artifactor.models import Artifact def index(request): artifacts = Artifact.objects.all() return render_to_response('Artifactor/index.html', {'artifacts': artifacts}, context_instance=RequestContext(request)) class ArtifactForm(ModelForm): class Meta: model = Artifact fields = ('path',) @csrf_exempt def post(request): if request.method == 'POST': form = ArtifactForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect('/') else: raise Http404
# -*- coding: utf-8 -*- # vim: set ts=4 from django.forms import ModelForm from django.http import Http404, HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext from django.views.decorators.csrf import csrf_exempt from Artifactor.models import Artifact def index(request): artifacts = Artifact.objects.all() return render_to_response('Artifactor/index.html', {'artifacts': artifacts}, context_instance=RequestContext(request)) class ArtifactForm(ModelForm): class Meta: model = Artifact fields = ('path',) @csrf_exempt def post(request): if request.method == 'POST': form = ArtifactForm(request.POST, request.FILES) if form.is_valid(): artifact = form.save() return HttpResponse(artifact.path.url, content_type='text/plain') else: raise Http404
Return the right URL when a file is posted
Return the right URL when a file is posted
Python
mit
ivoire/Artifactorial,ivoire/Artifactorial,ivoire/Artifactorial
--- +++ @@ -2,7 +2,7 @@ # vim: set ts=4 from django.forms import ModelForm -from django.http import Http404, HttpResponseRedirect +from django.http import Http404, HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext from django.views.decorators.csrf import csrf_exempt @@ -28,7 +28,7 @@ if request.method == 'POST': form = ArtifactForm(request.POST, request.FILES) if form.is_valid(): - form.save() - return HttpResponseRedirect('/') + artifact = form.save() + return HttpResponse(artifact.path.url, content_type='text/plain') else: raise Http404
5706257685820787b70bfef6798491c34b9b9ad9
ckanext/romania_theme/plugin.py
ckanext/romania_theme/plugin.py
import ckan.model as model import ckan.plugins as plugins import ckan.plugins.toolkit as toolkit import os def get_number_of_files(): return model.Session.execute("select count(*) from resource where state = 'active'").first()[0] def get_number_of_external_links(): return model.Session.execute("select count(*) from resource where state = 'active' and url not LIKE '%data.gov.ro%'").first()[0] class Romania_ThemePlugin(plugins.SingletonPlugin): plugins.implements(plugins.IConfigurer) plugins.implements(plugins.ITemplateHelpers) def update_config(self, config): toolkit.add_template_directory(config, 'templates') toolkit.add_public_directory(config, 'public') toolkit.add_resource('fanstatic', 'romania_theme') def get_helpers(self): return {'get_number_of_files': get_number_of_files, 'get_number_of_external_links': get_number_of_external_links}
import ckan.model as model import ckan.plugins as plugins import ckan.plugins.toolkit as toolkit import os def get_number_of_files(): return model.Session.execute("select count(*) from resource where state = 'active'").first()[0] def get_number_of_external_links(): return model.Session.execute("select count(*) from resource where state = 'active' and url not LIKE '%data.gov.ro%'").first()[0] class Romania_ThemePlugin(plugins.SingletonPlugin): plugins.implements(plugins.IConfigurer) plugins.implements(plugins.ITemplateHelpers) plugins.implements(plugins.IResourceController) # IConfigurer def update_config(self, config): toolkit.add_template_directory(config, 'templates') toolkit.add_public_directory(config, 'public') toolkit.add_resource('fanstatic', 'romania_theme') def get_helpers(self): return {'get_number_of_files': get_number_of_files, 'get_number_of_external_links': get_number_of_external_links} + # IResourceController def before_create(self, context, resource): if resource['upload'].type == 'application/pdf': raise ValidationError(['Resource type not allowed as resource.'])
Add check for PDF files
Add check for PDF files
Python
agpl-3.0
govro/ckanext-romania_theme,govro/ckanext-romania_theme,govro/ckanext-romania_theme,govro/ckanext-romania_theme
--- +++ @@ -15,7 +15,9 @@ class Romania_ThemePlugin(plugins.SingletonPlugin): plugins.implements(plugins.IConfigurer) plugins.implements(plugins.ITemplateHelpers) + plugins.implements(plugins.IResourceController) + # IConfigurer def update_config(self, config): toolkit.add_template_directory(config, 'templates') toolkit.add_public_directory(config, 'public') @@ -24,3 +26,8 @@ def get_helpers(self): return {'get_number_of_files': get_number_of_files, 'get_number_of_external_links': get_number_of_external_links} + ++ # IResourceController + def before_create(self, context, resource): + if resource['upload'].type == 'application/pdf': + raise ValidationError(['Resource type not allowed as resource.'])
14dcd8789c764743cfcb2e7a7b9b7d33b21a2779
fluent_blogs/models/managers.py
fluent_blogs/models/managers.py
""" The manager class for the CMS models """ from datetime import datetime from django.db import models from django.db.models.query import QuerySet from django.db.models.query_utils import Q class EntryQuerySet(QuerySet): def published(self): """ Return only published entries """ from fluent_blogs.models import Entry # the import can't be globally, that gives a circular dependency return self \ .filter(status=Entry.PUBLISHED) \ .filter( Q(publication_date__isnull=True) | Q(publication_date__lt=datetime.now()) ).filter( Q(publication_end_date__isnull=True) | Q(publication_end_date__gte=datetime.now()) ) class EntryManager(models.Manager): """ Extra methods attached to ``Entry.objects`` . """ def get_query_set(self): return EntryQuerySet(self.model, using=self._db) def published(self): """ Return only published entries """ return self.get_query_set().published()
""" The manager class for the CMS models """ from datetime import datetime from django.db import models from django.db.models.query import QuerySet from django.db.models.query_utils import Q class EntryQuerySet(QuerySet): def published(self): """ Return only published entries """ from fluent_blogs.models import Entry # the import can't be globally, that gives a circular dependency return self \ .filter(status=Entry.PUBLISHED) \ .filter( Q(publication_date__isnull=True) | Q(publication_date__lte=datetime.now()) ).filter( Q(publication_end_date__isnull=True) | Q(publication_end_date__gte=datetime.now()) ) class EntryManager(models.Manager): """ Extra methods attached to ``Entry.objects`` . """ def get_query_set(self): return EntryQuerySet(self.model, using=self._db) def published(self): """ Return only published entries """ return self.get_query_set().published()
Fix .published() to accept current date as well.
Fix .published() to accept current date as well.
Python
apache-2.0
edoburu/django-fluent-blogs,edoburu/django-fluent-blogs
--- +++ @@ -17,7 +17,7 @@ .filter(status=Entry.PUBLISHED) \ .filter( Q(publication_date__isnull=True) | - Q(publication_date__lt=datetime.now()) + Q(publication_date__lte=datetime.now()) ).filter( Q(publication_end_date__isnull=True) | Q(publication_end_date__gte=datetime.now())
618bf6d4c1fc5e60b7e94d1ad1030bf2cf0de5c2
src/main/python/alppaca/server_mock/__init__.py
src/main/python/alppaca/server_mock/__init__.py
from __future__ import print_function, absolute_import, unicode_literals, division from datetime import datetime, timedelta from textwrap import dedent from bottle import Bottle import pytz """ Super simple IMS mock. Just listens on localhost:8080 for the appropriate url, returns a test role and a dummy JSON response. """ def expiration_10s_from_now(): n = datetime.now(tz=pytz.utc) + timedelta(seconds=10) return n.strftime("%Y-%m-%dT%H:%M:%SZ") class MockIms(Bottle): PATH = '/latest/meta-data/iam/security-credentials/' json_response = dedent(""" {"Code": "Success", "AccessKeyId": "ASIAI", "SecretAccessKey": "XXYYZZ", "Token": "0123456789abcdefghijklmnopqrstuvwxyzAB", "Expiration": "%s", "Type": "AWS-HMAC"} """) def __init__(self): super(MockIms, self).__init__() self.route(self.PATH, callback=self.get_roles) self.route(self.PATH + '<role>', callback=self.get_credentials) def get_roles(self): return 'test_role' def get_credentials(self, role): return self.json_response % expiration_10s_from_now() if role == 'test_role' else '' if __name__ == "__main__": MockIms().run()
""" Super simple IMS mock. Just listens on localhost:8080 for the appropriate url, returns a test role and a dummy JSON response. """ from __future__ import print_function, absolute_import, unicode_literals, division from datetime import datetime, timedelta from textwrap import dedent from bottle import Bottle import pytz def expiration_10s_from_now(): n = datetime.now(tz=pytz.utc) + timedelta(seconds=10) return n.strftime("%Y-%m-%dT%H:%M:%SZ") class MockIms(Bottle): PATH = '/latest/meta-data/iam/security-credentials/' json_response = dedent(""" {"Code": "Success", "AccessKeyId": "ASIAI", "SecretAccessKey": "XXYYZZ", "Token": "0123456789abcdefghijklmnopqrstuvwxyzAB", "Expiration": "%s", "Type": "AWS-HMAC"} """) def __init__(self): super(MockIms, self).__init__() self.route(self.PATH, callback=self.get_roles) self.route(self.PATH + '<role>', callback=self.get_credentials) def get_roles(self): return 'test_role' def get_credentials(self, role): return self.json_response % expiration_10s_from_now() if role == 'test_role' else '' if __name__ == "__main__": MockIms().run()
Move string above the imports so it becomes a docstring
Move string above the imports so it becomes a docstring
Python
apache-2.0
ImmobilienScout24/afp-alppaca,ImmobilienScout24/alppaca,ImmobilienScout24/alppaca,ImmobilienScout24/afp-alppaca
--- +++ @@ -1,3 +1,9 @@ +""" Super simple IMS mock. + +Just listens on localhost:8080 for the appropriate url, returns a test role and +a dummy JSON response. + +""" from __future__ import print_function, absolute_import, unicode_literals, division from datetime import datetime, timedelta @@ -6,12 +12,6 @@ from bottle import Bottle import pytz -""" Super simple IMS mock. - -Just listens on localhost:8080 for the appropriate url, returns a test role and -a dummy JSON response. - -""" def expiration_10s_from_now():
65be9926d1e6d769fcf6d88a6a9788791beef187
id3lab/__init__.py
id3lab/__init__.py
import IPython import ts_charting.lab.lab as tslab import ipycli.standalone as sa from workbench import sharedx class ID3Lab(tslab.Lab): def get_varname(self): """ Try to get the variable that this lab is bound to in the IPython kernel """ inst = IPython.InteractiveShell._instance for k,v in inst.user_ns.iteritems(): if v is self and not k.startswith('_'): return k def link(self): name = self.get_varname() return sa.link(name) def _repr_javascript_(self): """ Output: stations: AAPL IBM <link> Note: Uses Javascript because sa.link() returns javascript. This is because sa.link needs to use the location.href to get the notebook_id since we cannot grab that from within the notebook kernel. """ js = """ element.append('{0}'); container.show(); """ station_text = '<strong>stations:</strong> <br />' station_text += '<br />'.join(self.stations.keys()) out = js.format(station_text) link = self.link().data out += 'element.append("<br />");' + link return out @property def html_obj(self): # for now default to sharedx return sharedx def __str__(self): return
import IPython import ts_charting.lab.lab as tslab import ipycli.standalone as sa from workbench import sharedx class ID3Lab(tslab.Lab): _html_obj = None def __init__(self, draw=False, html_obj=None): super(ID3Lab, self).__init__(draw=draw) if html_obj is None: html_obj = sharedx self._html_obj = html_obj def get_varname(self): """ Try to get the variable that this lab is bound to in the IPython kernel """ inst = IPython.InteractiveShell._instance for k,v in inst.user_ns.iteritems(): if v is self and not k.startswith('_'): return k def link(self): name = self.get_varname() return sa.link(name) def _repr_javascript_(self): """ Output: stations: AAPL IBM <link> Note: Uses Javascript because sa.link() returns javascript. This is because sa.link needs to use the location.href to get the notebook_id since we cannot grab that from within the notebook kernel. """ js = """ element.append('{0}'); container.show(); """ station_text = '<strong>stations:</strong> <br />' station_text += '<br />'.join(self.stations.keys()) out = js.format(station_text) link = self.link().data out += 'element.append("<br />");' + link return out @property def html_obj(self): return self._html_obj def __str__(self): return
Make ID3Lab allow attr to be pluggable
ENH: Make ID3Lab allow attr to be pluggable
Python
apache-2.0
dalejung/id3lab,dalejung/id3lab
--- +++ @@ -6,6 +6,13 @@ from workbench import sharedx class ID3Lab(tslab.Lab): + _html_obj = None + def __init__(self, draw=False, html_obj=None): + super(ID3Lab, self).__init__(draw=draw) + if html_obj is None: + html_obj = sharedx + self._html_obj = html_obj + def get_varname(self): """ Try to get the variable that this lab is @@ -23,7 +30,7 @@ def _repr_javascript_(self): """ Output: - + stations: AAPL IBM @@ -31,11 +38,11 @@ <link> Note: - Uses Javascript because sa.link() returns javascript. This is + Uses Javascript because sa.link() returns javascript. This is because sa.link needs to use the location.href to get the notebook_id since we cannot grab that from within the notebook kernel. """ - js = """ + js = """ element.append('{0}'); container.show(); """ @@ -49,8 +56,7 @@ @property def html_obj(self): - # for now default to sharedx - return sharedx + return self._html_obj def __str__(self): - return + return
f0871086222be67ba4add4574cf03d3cb9d39d63
tests/circular/template/test_interpolatedstr.py
tests/circular/template/test_interpolatedstr.py
from src.circular.template.interpolatedstr import InterpolatedStr from src.circular.template.context import Context from tests.utils import TObserver def test_string_interp(): ctx = Context() ctx.name = "James" s = InterpolatedStr("My name is {{ surname }}, {{name}} {{ surname}}.") s.bind_ctx(ctx) t = TObserver(s) assert s.value == "My name is , James ." ctx.surname = "Bond" data = t.events.pop().data assert s.value == "My name is Bond, James Bond."
from src.circular.template.interpolatedstr import InterpolatedStr from src.circular.template.context import Context from tests.utils import TObserver def test_string_interp(): ctx = Context() ctx.name = "James" s = InterpolatedStr("My name is {{ surname }}, {{name}} {{ surname}}.") s.bind_ctx(ctx) t = TObserver(s) assert s.value == "My name is , James ." ctx.surname = "Bond" data = t.events.pop().data assert s.value == "My name is Bond, James Bond." # Should correctly interpolate two immediately succeeding expressions ctx.sur="B" s = InterpolatedStr('{{name}}{{sur}}') s.bind_ctx(ctx) assert s.value == "JamesB"
Add test for run-together interpolated expressions.
Add test for run-together interpolated expressions.
Python
mit
jonathanverner/circular,jonathanverner/circular,jonathanverner/circular
--- +++ @@ -17,6 +17,11 @@ data = t.events.pop().data assert s.value == "My name is Bond, James Bond." + # Should correctly interpolate two immediately succeeding expressions + ctx.sur="B" + s = InterpolatedStr('{{name}}{{sur}}') + s.bind_ctx(ctx) + assert s.value == "JamesB" @@ -25,3 +30,4 @@ +
7ce48df1dc525b214a5993853d313d7e1ab6050d
cms/templatetags/cms_js_tags.py
cms/templatetags/cms_js_tags.py
# -*- coding: utf-8 -*- from classytags.core import Tag, Options from django import template from django.core.serializers.json import DjangoJSONEncoder from django.utils import simplejson from django.utils.text import javascript_quote register = template.Library() @register.filter def js(value): return simplejson.dumps(value, cls=DjangoJSONEncoder) @register.filter def bool(value): if value: return 'true' else: return 'false' class JavascriptString(Tag): name = 'javascript_string' options = Options( blocks=[ ('end_javascript_string', 'nodelist'), ] ) def render_tag(self, context, **kwargs): rendered = self.nodelist.render(context) return u"'%s'" % javascript_quote(rendered.strip()) register.tag(JavascriptString)
# -*- coding: utf-8 -*- from distutils.version import LooseVersion from classytags.core import Tag, Options import django from django import template from django.core.serializers.json import DjangoJSONEncoder from django.utils.text import javascript_quote DJANGO_1_4 = LooseVersion(django.get_version()) < LooseVersion('1.5') if DJANGO_1_4: from django.utils import simplejson as json else: import json register = template.Library() @register.filter def js(value): return json.dumps(value, cls=DjangoJSONEncoder) @register.filter def bool(value): if value: return 'true' else: return 'false' class JavascriptString(Tag): name = 'javascript_string' options = Options( blocks=[ ('end_javascript_string', 'nodelist'), ] ) def render_tag(self, context, **kwargs): rendered = self.nodelist.render(context) return u"'%s'" % javascript_quote(rendered.strip()) register.tag(JavascriptString)
Use json module instead of django.utils.simplejson for Django 1.5
Use json module instead of django.utils.simplejson for Django 1.5
Python
bsd-3-clause
wyg3958/django-cms,cyberintruder/django-cms,josjevv/django-cms,jproffitt/django-cms,webu/django-cms,mkoistinen/django-cms,czpython/django-cms,ojii/django-cms,memnonila/django-cms,Jaccorot/django-cms,11craft/django-cms,mkoistinen/django-cms,isotoma/django-cms,jsma/django-cms,bittner/django-cms,jproffitt/django-cms,intgr/django-cms,DylannCordel/django-cms,evildmp/django-cms,jsma/django-cms,360youlun/django-cms,jsma/django-cms,memnonila/django-cms,donce/django-cms,benzkji/django-cms,frnhr/django-cms,sephii/django-cms,foobacca/django-cms,farhaadila/django-cms,petecummings/django-cms,jrief/django-cms,SinnerSchraderMobileMirrors/django-cms,Livefyre/django-cms,divio/django-cms,stefanfoulis/django-cms,wuzhihui1123/django-cms,nimbis/django-cms,wuzhihui1123/django-cms,frnhr/django-cms,benzkji/django-cms,keimlink/django-cms,DylannCordel/django-cms,selecsosi/django-cms,isotoma/django-cms,czpython/django-cms,robmagee/django-cms,Jaccorot/django-cms,irudayarajisawa/django-cms,frnhr/django-cms,jrief/django-cms,netzkolchose/django-cms,vad/django-cms,yakky/django-cms,netzkolchose/django-cms,nostalgiaz/django-cms,astagi/django-cms,SachaMPS/django-cms,Livefyre/django-cms,keimlink/django-cms,liuyisiyisi/django-cms,pixbuffer/django-cms,sznekol/django-cms,benzkji/django-cms,petecummings/django-cms,Livefyre/django-cms,iddqd1/django-cms,jeffreylu9/django-cms,owers19856/django-cms,Jaccorot/django-cms,ojii/django-cms,liuyisiyisi/django-cms,ScholzVolkmer/django-cms,robmagee/django-cms,jeffreylu9/django-cms,leture/django-cms,foobacca/django-cms,wyg3958/django-cms,11craft/django-cms,cyberintruder/django-cms,SmithsonianEnterprises/django-cms,sephii/django-cms,takeshineshiro/django-cms,astagi/django-cms,Livefyre/django-cms,petecummings/django-cms,kk9599/django-cms,chmberl/django-cms,datakortet/django-cms,chkir/django-cms,rsalmaso/django-cms,SofiaReis/django-cms,frnhr/django-cms,bittner/django-cms,stefanfoulis/django-cms,vstoykov/django-cms,pancentric/django-cms,datakortet/django-cms,qnub/django-cms,irudayarajisawa/django-cms,nostalgiaz/django-cms,FinalAngel/django-cms,vstoykov/django-cms,dhorelik/django-cms,leture/django-cms,timgraham/django-cms,liuyisiyisi/django-cms,andyzsf/django-cms,vxsx/django-cms,qnub/django-cms,SinnerSchraderMobileMirrors/django-cms,pancentric/django-cms,stefanw/django-cms,farhaadila/django-cms,rscnt/django-cms,stefanw/django-cms,donce/django-cms,MagicSolutions/django-cms,SachaMPS/django-cms,vxsx/django-cms,mkoistinen/django-cms,divio/django-cms,dhorelik/django-cms,takeshineshiro/django-cms,ScholzVolkmer/django-cms,andyzsf/django-cms,rsalmaso/django-cms,rscnt/django-cms,philippze/django-cms,nostalgiaz/django-cms,ScholzVolkmer/django-cms,11craft/django-cms,astagi/django-cms,jsma/django-cms,SofiaReis/django-cms,chkir/django-cms,stefanfoulis/django-cms,webu/django-cms,Vegasvikk/django-cms,SofiaReis/django-cms,FinalAngel/django-cms,sephii/django-cms,andyzsf/django-cms,rryan/django-cms,iddqd1/django-cms,owers19856/django-cms,intip/django-cms,intgr/django-cms,kk9599/django-cms,rsalmaso/django-cms,jrief/django-cms,pixbuffer/django-cms,intip/django-cms,evildmp/django-cms,SinnerSchraderMobileMirrors/django-cms,timgraham/django-cms,mkoistinen/django-cms,chkir/django-cms,divio/django-cms,saintbird/django-cms,11craft/django-cms,qnub/django-cms,josjevv/django-cms,evildmp/django-cms,vad/django-cms,MagicSolutions/django-cms,rryan/django-cms,rscnt/django-cms,netzkolchose/django-cms,vstoykov/django-cms,jrclaramunt/django-cms,intip/django-cms,philippze/django-cms,yakky/django-cms,yakky/django-cms,pixbuffer/django-cms,selecsosi/django-cms,isotoma/django-cms,farhaadila/django-cms,vxsx/django-cms,dhorelik/django-cms,iddqd1/django-cms,nimbis/django-cms,jeffreylu9/django-cms,takeshineshiro/django-cms,FinalAngel/django-cms,stefanfoulis/django-cms,jrief/django-cms,divio/django-cms,DylannCordel/django-cms,nostalgiaz/django-cms,nimbis/django-cms,Vegasvikk/django-cms,datakortet/django-cms,jeffreylu9/django-cms,owers19856/django-cms,webu/django-cms,netzkolchose/django-cms,evildmp/django-cms,intgr/django-cms,sephii/django-cms,vxsx/django-cms,saintbird/django-cms,FinalAngel/django-cms,intip/django-cms,vad/django-cms,saintbird/django-cms,sznekol/django-cms,Vegasvikk/django-cms,datakortet/django-cms,stefanw/django-cms,jrclaramunt/django-cms,youprofit/django-cms,stefanw/django-cms,memnonila/django-cms,josjevv/django-cms,timgraham/django-cms,jproffitt/django-cms,pancentric/django-cms,jproffitt/django-cms,SmithsonianEnterprises/django-cms,ojii/django-cms,SmithsonianEnterprises/django-cms,isotoma/django-cms,wuzhihui1123/django-cms,rsalmaso/django-cms,chmberl/django-cms,czpython/django-cms,keimlink/django-cms,irudayarajisawa/django-cms,wyg3958/django-cms,czpython/django-cms,intgr/django-cms,leture/django-cms,philippze/django-cms,MagicSolutions/django-cms,360youlun/django-cms,vad/django-cms,donce/django-cms,nimbis/django-cms,AlexProfi/django-cms,sznekol/django-cms,foobacca/django-cms,foobacca/django-cms,bittner/django-cms,yakky/django-cms,wuzhihui1123/django-cms,youprofit/django-cms,rryan/django-cms,bittner/django-cms,kk9599/django-cms,rryan/django-cms,andyzsf/django-cms,AlexProfi/django-cms,selecsosi/django-cms,youprofit/django-cms,cyberintruder/django-cms,benzkji/django-cms,selecsosi/django-cms,chmberl/django-cms,360youlun/django-cms,jrclaramunt/django-cms,AlexProfi/django-cms,SachaMPS/django-cms,robmagee/django-cms
--- +++ @@ -1,15 +1,24 @@ # -*- coding: utf-8 -*- +from distutils.version import LooseVersion + from classytags.core import Tag, Options +import django from django import template from django.core.serializers.json import DjangoJSONEncoder -from django.utils import simplejson from django.utils.text import javascript_quote + +DJANGO_1_4 = LooseVersion(django.get_version()) < LooseVersion('1.5') + +if DJANGO_1_4: + from django.utils import simplejson as json +else: + import json register = template.Library() @register.filter def js(value): - return simplejson.dumps(value, cls=DjangoJSONEncoder) + return json.dumps(value, cls=DjangoJSONEncoder) @register.filter def bool(value):
27c451c8490e0f70ceb96327bc6d2aeb29605a40
ui/helpers.py
ui/helpers.py
def get_referrer_from_request(request): # determine what source led the user to the export directory # if navigating internally then return None return 'aaa'
def get_referrer_from_request(request): # TODO: determine what source led the user to the export directory # if navigating internally then return None (ticket ED-138) return 'aaa'
Add TODO to comment in registration helper to reduce risk of task being forgotten
Add TODO to comment in registration helper to reduce risk of task being forgotten
Python
mit
uktrade/directory-ui-supplier,uktrade/directory-ui-supplier,uktrade/directory-ui-supplier
--- +++ @@ -1,4 +1,4 @@ def get_referrer_from_request(request): - # determine what source led the user to the export directory - # if navigating internally then return None + # TODO: determine what source led the user to the export directory + # if navigating internally then return None (ticket ED-138) return 'aaa'
793c477f4e365d47d9245f43e9d49fccce303d2a
vcs/models.py
vcs/models.py
from django.db import models class Activity(models.Model): group = models.CharField(max_length=4) grouptype = models.TextField() groupdetail = models.TextField() details = models.TextField() disabled = models.BooleanField() time = models.DecimalField(decimal_places=2, max_digits=10) unique_together = (("group", "grouptype", "disabled", "time"),) class ActivityEntry(models.Model): user = models.ManyToManyField( 'tracker.Tbluser', related_name="user_foreign" ) activity = models.ManyToManyField( Activity, related_name="activity_foreign" ) amount = models.BigIntegerField() def time(self): return self.activity.time * self.amount
from django.db import models class Activity(models.Model): group = models.CharField(max_length=4) grouptype = models.TextField() groupdetail = models.TextField() details = models.TextField() disabled = models.BooleanField() time = models.DecimalField(decimal_places=2, max_digits=10) unique_together = (("group", "grouptype", "disabled", "time"),) class ActivityEntry(models.Model): user = models.OneToOneField( 'tracker.Tbluser', related_name="user_foreign" ) activity = models.OneToOneField( Activity, related_name="activity_foreign" ) amount = models.BigIntegerField() def time(self): return self.activity.time * self.amount
Use a OneToMany field for the activity joiner.
Use a OneToMany field for the activity joiner.
Python
bsd-3-clause
AeroNotix/django-timetracker,AeroNotix/django-timetracker,AeroNotix/django-timetracker
--- +++ @@ -10,11 +10,11 @@ unique_together = (("group", "grouptype", "disabled", "time"),) class ActivityEntry(models.Model): - user = models.ManyToManyField( + user = models.OneToOneField( 'tracker.Tbluser', related_name="user_foreign" ) - activity = models.ManyToManyField( + activity = models.OneToOneField( Activity, related_name="activity_foreign" )
5a12255e0af4666a5a197bad94e2cbfe4229a310
src/kernels/util.py
src/kernels/util.py
import numba def selfparams(f): def wrapped_func(obj, x1, x2): return f(x1.astype('f8', copy=False), x2.astype('f8', copy=False), *obj.params) wrapped_func.__name__ = f.__name__ wrapped_func.__doc__ = f.__doc__ return wrapped_func def lazyjit(*args, **kwargs): compiler = numba.jit(*args, **kwargs) def compile(f): f.compiled = None def thunk(*fargs, **fkwargs): if not f.compiled: f.compiled = compiler(f) return f.compiled(*fargs, **fkwargs) thunk.__name__ = f.__name__ thunk.__doc__ = f.__doc__ return thunk return compile
import numba def selfparams(f): def wrapped_func(self, x1, x2): return f(x1.astype('f8', copy=False), x2.astype('f8', copy=False), *self.params) wrapped_func.__name__ = f.__name__ wrapped_func.__doc__ = f.__doc__ return wrapped_func def lazyjit(*args, **kwargs): compiler = numba.jit(*args, **kwargs) def compile(f): f.compiled = None def thunk(*fargs, **fkwargs): if not f.compiled: f.compiled = compiler(f) return f.compiled(*fargs, **fkwargs) thunk.__name__ = f.__name__ thunk.__doc__ = f.__doc__ return thunk return compile
Change obj to self in selfparams
Change obj to self in selfparams This is so sphinx detects the first parameter in decorated functions as `self`, and therefore does not display it in the method signature.
Python
mit
jhamrick/gaussian_processes,jhamrick/gaussian_processes
--- +++ @@ -2,10 +2,10 @@ def selfparams(f): - def wrapped_func(obj, x1, x2): + def wrapped_func(self, x1, x2): return f(x1.astype('f8', copy=False), x2.astype('f8', copy=False), - *obj.params) + *self.params) wrapped_func.__name__ = f.__name__ wrapped_func.__doc__ = f.__doc__ return wrapped_func
0b7d69869009888c26d1fdf3dee8a4f858fa70a3
diary/forms.py
diary/forms.py
from django import forms import cube.diary.models class DiaryIdeaForm(forms.ModelForm): class Meta(object): model = cube.diary.models.DiaryIdea class EventForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Event class ShowingForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by') class NewShowingForm(forms.ModelForm): # Same as Showing, but without the role field class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by', 'roles')
from django import forms import cube.diary.models class DiaryIdeaForm(forms.ModelForm): class Meta(object): model = cube.diary.models.DiaryIdea class EventForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Event # Ensure soft wrapping is set for textareas: widgets = { 'copy': forms.Textarea(attrs={'wrap':'soft'}), 'copy_summary': forms.Textarea(attrs={'wrap':'soft'}), 'terms': forms.Textarea(attrs={'wrap':'soft'}), 'notes': forms.Textarea(attrs={'wrap':'soft'}), } class ShowingForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by') class NewShowingForm(forms.ModelForm): # Same as Showing, but without the role field class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by', 'roles')
Set wrapping to soft on textareas
Set wrapping to soft on textareas
Python
agpl-3.0
BenMotz/cubetoolkit,BenMotz/cubetoolkit,BenMotz/cubetoolkit,BenMotz/cubetoolkit
--- +++ @@ -8,6 +8,13 @@ class EventForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Event + # Ensure soft wrapping is set for textareas: + widgets = { + 'copy': forms.Textarea(attrs={'wrap':'soft'}), + 'copy_summary': forms.Textarea(attrs={'wrap':'soft'}), + 'terms': forms.Textarea(attrs={'wrap':'soft'}), + 'notes': forms.Textarea(attrs={'wrap':'soft'}), + } class ShowingForm(forms.ModelForm): class Meta(object):
6018abc4a1c2dfa139bb104ae6db69fef5994ff6
plugins/chrome_extensions.py
plugins/chrome_extensions.py
################################################################################################### # # chrome_extensions.py # Adds the name and description of each Chrome extension found in a URLItem to the Interpretation field # # Plugin Author: Ryan Benson (ryan@obsidianforensics.com) # ################################################################################################### import re # Config friendlyName = "Chrome Extension Names" description = "Adds the name and description of each Chrome extension found in a URLItem to the Interpretation field" artifactTypes = ["url", "url (archived)"] remoteLookups = 0 browser = "Chrome" browserVersion = 1 version = "20150117" parsedItems = 0 def plugin(target_browser): extension_re = re.compile(r'^chrome-extension://([a-z]{32})') global parsedItems for item in target_browser.parsed_artifacts: if item.row_type in artifactTypes: if item.interpretation is None: m = re.search(extension_re, item.url) if m: for ext in target_browser.installed_extensions['data']: if ext.app_id == m.group(1): item.interpretation = "%s (%s) [Chrome Extension]" % (ext.name, ext.description) parsedItems += 1 # Description of what the plugin did return "%s extension URLs parsed" % parsedItems
################################################################################################### # # chrome_extensions.py # Adds the name and description of each Chrome extension found in a URLItem to the Interpretation field # # Plugin Author: Ryan Benson (ryan@obsidianforensics.com) # ################################################################################################### import re # Config friendlyName = "Chrome Extension Names" description = "Adds the name and description of each Chrome extension found in a URLItem to the Interpretation field" artifactTypes = ["url", "url (archived)"] remoteLookups = 0 browser = "Chrome" browserVersion = 1 version = "20150125" parsedItems = 0 def plugin(target_browser): extension_re = re.compile(r'^chrome-extension://([a-z]{32})') global parsedItems for item in target_browser.parsed_artifacts: if item.row_type in artifactTypes: if item.interpretation is None: m = re.search(extension_re, item.url) if m: try: for ext in target_browser.installed_extensions['data']: if ext.app_id == m.group(1): item.interpretation = "%s (%s) [Chrome Extension]" % (ext.name, ext.description) parsedItems += 1 except: pass # Description of what the plugin did return "%s extension URLs parsed" % parsedItems
Add try/except to catch if no extensions are parsed.
Add try/except to catch if no extensions are parsed.
Python
apache-2.0
obsidianforensics/hindsight,obsidianforensics/hindsight
--- +++ @@ -16,7 +16,7 @@ remoteLookups = 0 browser = "Chrome" browserVersion = 1 -version = "20150117" +version = "20150125" parsedItems = 0 @@ -29,10 +29,13 @@ if item.interpretation is None: m = re.search(extension_re, item.url) if m: - for ext in target_browser.installed_extensions['data']: - if ext.app_id == m.group(1): - item.interpretation = "%s (%s) [Chrome Extension]" % (ext.name, ext.description) - parsedItems += 1 + try: + for ext in target_browser.installed_extensions['data']: + if ext.app_id == m.group(1): + item.interpretation = "%s (%s) [Chrome Extension]" % (ext.name, ext.description) + parsedItems += 1 + except: + pass # Description of what the plugin did return "%s extension URLs parsed" % parsedItems
1b23ca7327d5414233222fdb26c1c1e88d0137a6
takeyourmeds/telephony/views.py
takeyourmeds/telephony/views.py
import os import json from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from . import actions def info(request, uuid): """ Return the Twillio ML that we generated when the user called /call """ data = open(os.path.join("/tmp", uuid + ".xml")).read() return HttpResponse(data, content_type="text/xml")
import os from django.http import HttpResponse def info(request, uuid): """ Return the Twillio ML that we generated when the user called /call """ with open(os.path.join('/tmp', '%s.xml' % uuid)) as f: data = f.read() return HttpResponse(data, content_type='text/xml')
Tidy imports and opening the tmpfile
Tidy imports and opening the tmpfile
Python
mit
takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web
--- +++ @@ -1,17 +1,13 @@ import os -import json from django.http import HttpResponse -from django.views.decorators.csrf import csrf_exempt - -from . import actions - def info(request, uuid): """ - Return the Twillio ML that we generated when the user - called /call + Return the Twillio ML that we generated when the user called /call """ - data = open(os.path.join("/tmp", uuid + ".xml")).read() - return HttpResponse(data, content_type="text/xml") + with open(os.path.join('/tmp', '%s.xml' % uuid)) as f: + data = f.read() + + return HttpResponse(data, content_type='text/xml')
1c12843b251184d3e683d9cebf9948565bbfe518
tests/conftest.py
tests/conftest.py
# pylint: disable=C0111 import pytest import os import tarfile BASEDIR = os.path.dirname(__file__) @pytest.fixture(autouse=True) def set_up(tmpdir): # print BASEDIR tmpdir.chdir() tar = tarfile.open(os.path.join(BASEDIR, "MockRepos.tar.gz")) tar.extractall() tar.close() os.chdir('MockRepos') print('In directory ' + os.getcwd()) # does not need teardown, since tmpdir directories get autodeleted
# pylint: disable=C0111 import pytest import os import tarfile BASEDIR = os.path.dirname(__file__) @pytest.fixture(autouse=False) def set_up(tmpdir): # print BASEDIR tmpdir.chdir() tar = tarfile.open(os.path.join(BASEDIR, "MockRepos.tar.gz")) tar.extractall() tar.close() os.chdir('MockRepos') print('In directory ' + os.getcwd()) # does not need teardown, since tmpdir directories get autodeleted
Disable autouse for set_up so that help tests don't generate unnecessary files.
Disable autouse for set_up so that help tests don't generate unnecessary files.
Python
mit
bilderbuchi/ofStateManager
--- +++ @@ -6,7 +6,7 @@ BASEDIR = os.path.dirname(__file__) -@pytest.fixture(autouse=True) +@pytest.fixture(autouse=False) def set_up(tmpdir): # print BASEDIR tmpdir.chdir()
b7b0724b7f663a8a0d0e5c46d66f42726d700f45
djng/router.py
djng/router.py
from django.conf.urls.defaults import patterns from django.core import urlresolvers class Router(object): """ Convenient wrapper around Django's urlresolvers, allowing them to be used from normal application code. from django.http import HttpResponse from django_openid.request_factory import RequestFactory from django.conf.urls.defaults import url router = Router( url('^foo/$', lambda r: HttpResponse('foo'), name='foo'), url('^bar/$', lambda r: HttpResponse('bar'), name='bar') ) rf = RequestFactory() print router(rf.get('/bar/')) """ def __init__(self, *urlpairs): self.urlpatterns = patterns('', *urlpairs) self.resolver = urlresolvers.RegexURLResolver(r'^/', self) def handle(self, request): path = request.path_info callback, callback_args, callback_kwargs = self.resolver.resolve(path) return callback(request, *callback_args, **callback_kwargs) def __call__(self, request): return self.handle(request)
from django.conf.urls.defaults import patterns from django.core import urlresolvers class Router(object): """ Convenient wrapper around Django's urlresolvers, allowing them to be used from normal application code. from django.http import HttpResponse from django_openid.request_factory import RequestFactory from django.conf.urls.defaults import url router = Router( url('^foo/$', lambda r: HttpResponse('foo'), name='foo'), url('^bar/$', lambda r: HttpResponse('bar'), name='bar') ) rf = RequestFactory() print router(rf.get('/bar/')) """ def __init__(self, *urlpairs): self.urlpatterns = patterns('', *urlpairs) # for 1.0 compatibility we pass in None for urlconf_name and then # modify the _urlconf_module to make self hack as if its the module. self.resolver = urlresolvers.RegexURLResolver(r'^/', None) self.resolver._urlconf_module = self def handle(self, request): path = request.path_info callback, callback_args, callback_kwargs = self.resolver.resolve(path) return callback(request, *callback_args, **callback_kwargs) def __call__(self, request): return self.handle(request)
Add back 1.0.X compatibility for Router URL resolution.
Add back 1.0.X compatibility for Router URL resolution. Signed-off-by: Simon Willison <088e16a1019277b15d58faf0541e11910eb756f6@simonwillison.net>
Python
bsd-2-clause
simonw/djng
--- +++ @@ -18,7 +18,10 @@ """ def __init__(self, *urlpairs): self.urlpatterns = patterns('', *urlpairs) - self.resolver = urlresolvers.RegexURLResolver(r'^/', self) + # for 1.0 compatibility we pass in None for urlconf_name and then + # modify the _urlconf_module to make self hack as if its the module. + self.resolver = urlresolvers.RegexURLResolver(r'^/', None) + self.resolver._urlconf_module = self def handle(self, request): path = request.path_info
97e048d0a743808ab0ec62b39306940b59dd3c8a
test.py
test.py
import bluePoV import pygame x,y = (480,64) MAC = "00:00:00:00:00:00" pygame.init() pygame.display.set_mode((x,y)) s = pygame.display.get_surface() driver = bluePoV.Driver([x,y],1) #driver.connect(MAC) s.fill([0,255,0]) driver.blit(s) pygame.display.flip() input("Press any key... ")
import bluePoV import pygame x,y = (480,64) MAC = "00:00:00:00:00:00" pygame.init() pygame.display.set_mode((x,y)) s = pygame.display.get_surface() driver = bluePoV.Driver([x,y],depth=1,asServer=True) #driver.connect(MAC) s.fill([0,255,0]) driver.blit(s) pygame.display.flip() input("Press any key... ")
Throw an error if bluetooth is not supported on the py3 installation
Throw an error if bluetooth is not supported on the py3 installation
Python
mit
ABorgna/BluePoV-PC,ABorgna/BluePoV-PC,ABorgna/BluePoV-PC
--- +++ @@ -9,7 +9,7 @@ s = pygame.display.get_surface() -driver = bluePoV.Driver([x,y],1) +driver = bluePoV.Driver([x,y],depth=1,asServer=True) #driver.connect(MAC)
e4717e8017b9a476db1ed016c19d883cd786c7ce
tests/penn_chime/test_parameters.py
tests/penn_chime/test_parameters.py
"""""" from penn_chime.parameters import Parameters def test_cli_defaults(): """Ensure if the cli defaults have been updated.""" # TODO how to make this work when the module is installed? _ = Parameters.create({'PARAMETERS': './defaults/cli.cfg'}, []) def test_webapp_defaults(): """Ensure the webapp defaults have been updated.""" # TODO how to make this work when the module is installed? _ = Parameters.create({'PARAMETERS': './defaults/webapp.cfg'}, [])
"""Test Parameters.""" from penn_chime.parameters import Parameters def test_cypress_defaults(): """Ensure the cypress defaults have been updated.""" # TODO how to make this work when the module is installed? _ = Parameters.create({"PARAMETERS": "./defaults/cypress.cfg"}, []) def test_cli_defaults(): """Ensure the cli defaults have been updated.""" # TODO how to make this work when the module is installed? _ = Parameters.create({"PARAMETERS": "./defaults/cli.cfg"}, []) def test_webapp_defaults(): """Ensure the webapp defaults have been updated.""" # TODO how to make this work when the module is installed? _ = Parameters.create({"PARAMETERS": "./defaults/webapp.cfg"}, [])
Add test for cypress defaults
Add test for cypress defaults
Python
mit
CodeForPhilly/chime,CodeForPhilly/chime,CodeForPhilly/chime
--- +++ @@ -1,14 +1,21 @@ -"""""" +"""Test Parameters.""" + from penn_chime.parameters import Parameters +def test_cypress_defaults(): + """Ensure the cypress defaults have been updated.""" + # TODO how to make this work when the module is installed? + _ = Parameters.create({"PARAMETERS": "./defaults/cypress.cfg"}, []) + + def test_cli_defaults(): - """Ensure if the cli defaults have been updated.""" + """Ensure the cli defaults have been updated.""" # TODO how to make this work when the module is installed? - _ = Parameters.create({'PARAMETERS': './defaults/cli.cfg'}, []) + _ = Parameters.create({"PARAMETERS": "./defaults/cli.cfg"}, []) def test_webapp_defaults(): """Ensure the webapp defaults have been updated.""" # TODO how to make this work when the module is installed? - _ = Parameters.create({'PARAMETERS': './defaults/webapp.cfg'}, []) + _ = Parameters.create({"PARAMETERS": "./defaults/webapp.cfg"}, [])
88b198ff1de67d675b81c736eceeb7a2308851db
json2csv_business.py
json2csv_business.py
import json def main(): # print the header of output csv file print 'business_id,city,latitude,longitude' # for each entry in input json file print one csv row for line in open("data/yelp_academic_dataset_business.json"): input_json = json.loads(line) business_id = input_json['business_id'] city = input_json['city'].encode('ascii', 'ignore') latitude = str(input_json['latitude']) longitude = str(input_json['longitude']) print business_id + ',' + city + ',' + latitude + ',' + longitude if __name__ == "__main__": main()
import json def main(): # print the header of output csv file print 'business_id,city,latitude,longitude' # for each entry in input json file print one csv row for line in open("data/yelp_academic_dataset_business.json"): input_json = json.loads(line) business_id = input_json['business_id'] city = input_json['city'].encode('ascii', 'ignore').replace(',', '') latitude = str(input_json['latitude']) longitude = str(input_json['longitude']) print business_id + ',' + city + ',' + latitude + ',' + longitude if __name__ == "__main__": main()
Replace commas in names of cities with spaces
Replace commas in names of cities with spaces
Python
mit
aysent/yelp-photo-explorer
--- +++ @@ -9,7 +9,7 @@ for line in open("data/yelp_academic_dataset_business.json"): input_json = json.loads(line) business_id = input_json['business_id'] - city = input_json['city'].encode('ascii', 'ignore') + city = input_json['city'].encode('ascii', 'ignore').replace(',', '') latitude = str(input_json['latitude']) longitude = str(input_json['longitude']) print business_id + ',' + city + ',' + latitude + ',' + longitude
853490b9d89b6e72d3b3f0e83fa2edb17d684547
jupyterlab/__init__.py
jupyterlab/__init__.py
"""Server extension for JupyterLab.""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. try: from ._version import __version__ except ImportError as e: # when we are python 3 only, add 'from e' at the end to chain the exception. raise ImportError("No module named 'jupyter._version'. Build the jupyterlab package to generate this module, for example, with `pip install -e /path/to/jupyterlab/repo`.") from .extension import load_jupyter_server_extension def _jupyter_server_extension_paths(): return [{ "module": "jupyterlab" }]
"""Server extension for JupyterLab.""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. try: from ._version import __version__ except ImportError as e: # when we are python 3 only, add 'from e' at the end to chain the exception. raise ImportError("No module named 'jupyterlab._version'. Build the jupyterlab package to generate this module, for example, with `pip install -e /path/to/jupyterlab/repo`.") from .extension import load_jupyter_server_extension def _jupyter_server_extension_paths(): return [{ "module": "jupyterlab" }]
Fix jupyterlab import error message
Fix jupyterlab import error message
Python
bsd-3-clause
jupyter/jupyterlab,charnpreetsingh185/jupyterlab,eskirk/jupyterlab,charnpreetsingh185/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,charnpreetsingh185/jupyterlab,charnpreetsingh185/jupyterlab,eskirk/jupyterlab
--- +++ @@ -7,7 +7,7 @@ from ._version import __version__ except ImportError as e: # when we are python 3 only, add 'from e' at the end to chain the exception. - raise ImportError("No module named 'jupyter._version'. Build the jupyterlab package to generate this module, for example, with `pip install -e /path/to/jupyterlab/repo`.") + raise ImportError("No module named 'jupyterlab._version'. Build the jupyterlab package to generate this module, for example, with `pip install -e /path/to/jupyterlab/repo`.") from .extension import load_jupyter_server_extension
89485bf26ebb7cf4570549cda42543061d6b4fd7
docker/transport/basehttpadapter.py
docker/transport/basehttpadapter.py
import requests.adapters class BaseHTTPAdapter(requests.adapters.HTTPAdapter): def close(self): self.pools.clear()
import requests.adapters class BaseHTTPAdapter(requests.adapters.HTTPAdapter): def close(self): super(BaseHTTPAdapter, self).close() if hasattr(self, 'pools'): self.pools.clear()
Fix BaseHTTPAdapter for the SSL case
Fix BaseHTTPAdapter for the SSL case Signed-off-by: Ulysses Souza <a0ff1337c6a0e43e9559f5f67fc3acb852912071@docker.com>
Python
apache-2.0
docker/docker-py,funkyfuture/docker-py,funkyfuture/docker-py,vdemeester/docker-py,vdemeester/docker-py,docker/docker-py
--- +++ @@ -3,4 +3,6 @@ class BaseHTTPAdapter(requests.adapters.HTTPAdapter): def close(self): - self.pools.clear() + super(BaseHTTPAdapter, self).close() + if hasattr(self, 'pools'): + self.pools.clear()
b4d86431806cc9ce3019aa65db2a3b22c2bd4ac3
flask_skeleton_api/views/general.py
flask_skeleton_api/views/general.py
from flask import request, Blueprint, Response from flask import current_app import json # This is the blueprint object that gets registered into the app in blueprints.py. general = Blueprint('general', __name__) @general.route("/health") def check_status(): return Response(response=json.dumps({ "app": "flask-skeleton-api", "status": "OK", "headers": str(request.headers), "commit": current_app.config["COMMIT"] }), mimetype='application/json', status=200)
from flask import request, Blueprint, Response from flask import current_app import json # This is the blueprint object that gets registered into the app in blueprints.py. general = Blueprint('general', __name__) @general.route("/health") def check_status(): return Response(response=json.dumps({ "app": "flask-skeleton-api", "status": "OK", "headers": request.headers.to_list(), "commit": current_app.config["COMMIT"] }), mimetype='application/json', status=200)
Improve list of headers returned with health route in order to remove /r/n
Improve list of headers returned with health route in order to remove /r/n
Python
mit
matthew-shaw/thing-api
--- +++ @@ -11,8 +11,6 @@ return Response(response=json.dumps({ "app": "flask-skeleton-api", "status": "OK", - "headers": str(request.headers), + "headers": request.headers.to_list(), "commit": current_app.config["COMMIT"] }), mimetype='application/json', status=200) - -
357db324df4b1bd8444c4bf2b89d210e968c8cd7
tests/frame/test_frame_1.py
tests/frame/test_frame_1.py
import lz4.frame as lz4frame import pytest def test_create_compression_context(): context = lz4frame.create_compression_context() assert context != None def test_create_decompression_context(): context = lz4frame.create_decompression_context() assert context != None # TODO add source_size fixture def test_roundtrip(data, block_size, block_mode, content_checksum, frame_type, compression_level, auto_flush): c_context = lz4frame.create_compression_context() compressed = lz4frame.compress_begin( c_context, source_size=len(data), compression_level=compression_level, block_size=block_size, content_checksum=content_checksum, frame_type=frame_type, auto_flush=auto_flush ) compressed += lz4frame.compress_chunk( c_context, data) compressed += lz4frame.compress_end(c_context) decompressed, bytes_read = lz4frame.decompress(compressed) assert bytes_read == len(compressed) assert decompressed == data
import lz4.frame as lz4frame import pytest def test_create_compression_context(): context = lz4frame.create_compression_context() assert context != None def test_create_decompression_context(): context = lz4frame.create_decompression_context() assert context != None # TODO add store_source fixture def test_roundtrip_1(data, block_size, block_mode, content_checksum, frame_type, compression_level, auto_flush): c_context = lz4frame.create_compression_context() compressed = lz4frame.compress( data, store_size=True, compression_level=compression_level, block_size=block_size, content_checksum=content_checksum, frame_type=frame_type, ) decompressed, bytes_read = lz4frame.decompress(compressed) assert bytes_read == len(compressed) assert decompressed == data # TODO add source_size fixture def test_roundtrip_2(data, block_size, block_mode, content_checksum, frame_type, compression_level, auto_flush): c_context = lz4frame.create_compression_context() compressed = lz4frame.compress_begin( c_context, source_size=len(data), compression_level=compression_level, block_size=block_size, content_checksum=content_checksum, frame_type=frame_type, auto_flush=auto_flush ) compressed += lz4frame.compress_chunk( c_context, data) compressed += lz4frame.compress_end(c_context) decompressed, bytes_read = lz4frame.decompress(compressed) assert bytes_read == len(compressed) assert decompressed == data
Add tests for non-chunked roundtrip
Add tests for non-chunked roundtrip
Python
bsd-3-clause
python-lz4/python-lz4,python-lz4/python-lz4
--- +++ @@ -9,10 +9,27 @@ context = lz4frame.create_decompression_context() assert context != None +# TODO add store_source fixture +def test_roundtrip_1(data, block_size, block_mode, + content_checksum, frame_type, + compression_level, auto_flush): + c_context = lz4frame.create_compression_context() + compressed = lz4frame.compress( + data, + store_size=True, + compression_level=compression_level, + block_size=block_size, + content_checksum=content_checksum, + frame_type=frame_type, + ) + decompressed, bytes_read = lz4frame.decompress(compressed) + assert bytes_read == len(compressed) + assert decompressed == data + # TODO add source_size fixture -def test_roundtrip(data, block_size, block_mode, - content_checksum, frame_type, - compression_level, auto_flush): +def test_roundtrip_2(data, block_size, block_mode, + content_checksum, frame_type, + compression_level, auto_flush): c_context = lz4frame.create_compression_context() compressed = lz4frame.compress_begin( c_context,
e1df9380be8891c813a8c87e8d8175393171ac17
rest_framework_sso/querysets.py
rest_framework_sso/querysets.py
# coding: utf-8 from __future__ import absolute_import, unicode_literals from django.db.models import QuerySet, Q from django.utils import timezone import logging logger = logging.getLogger(__name__) class SessionTokenQuerySet(QuerySet): def active(self): return self.filter(Q(revoked_at__isnull=True) | Q(revoked_at__gt=timezone.now())) def first_or_create(self, defaults=None, request_meta=None, **kwargs): """ Looks up an object with the given kwargs, creating one if necessary. Returns a tuple of (object, created), where created is a boolean specifying whether an object was created. """ if request_meta and "HTTP_USER_AGENT" in request_meta: kwargs["user_agent__startswith"] = request_meta.get("HTTP_USER_AGENT")[:100] params = self._extract_model_params(defaults, **kwargs) # The get() needs to be targeted at the write database in order # to avoid potential transaction consistency problems. self._for_write = True obj = self.filter(**kwargs).first() if obj: return obj, False else: return self._create_object_from_params(kwargs, params)
# coding: utf-8 from __future__ import absolute_import, unicode_literals from django.db.models import QuerySet, Q from django.utils import timezone import logging logger = logging.getLogger(__name__) class SessionTokenQuerySet(QuerySet): def active(self): return self.filter(Q(revoked_at__isnull=True) | Q(revoked_at__gt=timezone.now())) def first_or_create(self, request_meta=None, **kwargs): """ Looks up an object with the given kwargs, creating one if necessary. Returns a tuple of (object, created), where created is a boolean specifying whether an object was created. """ if request_meta and "HTTP_USER_AGENT" in request_meta: kwargs["user_agent__startswith"] = request_meta.get("HTTP_USER_AGENT")[:100] obj = self.filter(**kwargs).first() created = False if not obj: obj = self.create(**kwargs) created = True return obj, created
Stop using django's internal `_create_object_from_params`
Stop using django's internal `_create_object_from_params`
Python
mit
namespace-ee/django-rest-framework-sso,namespace-ee/django-rest-framework-sso
--- +++ @@ -13,7 +13,7 @@ def active(self): return self.filter(Q(revoked_at__isnull=True) | Q(revoked_at__gt=timezone.now())) - def first_or_create(self, defaults=None, request_meta=None, **kwargs): + def first_or_create(self, request_meta=None, **kwargs): """ Looks up an object with the given kwargs, creating one if necessary. Returns a tuple of (object, created), where created is a boolean @@ -22,13 +22,10 @@ if request_meta and "HTTP_USER_AGENT" in request_meta: kwargs["user_agent__startswith"] = request_meta.get("HTTP_USER_AGENT")[:100] - params = self._extract_model_params(defaults, **kwargs) - # The get() needs to be targeted at the write database in order - # to avoid potential transaction consistency problems. - self._for_write = True + obj = self.filter(**kwargs).first() + created = False + if not obj: + obj = self.create(**kwargs) + created = True - obj = self.filter(**kwargs).first() - if obj: - return obj, False - else: - return self._create_object_from_params(kwargs, params) + return obj, created
ff4b34cda7c0b5bc516d9f9e3689818000301336
tests/test_planner.py
tests/test_planner.py
import cutplanner import unittest class TestPlanner(unittest.TestCase): def setUp(self): sizes = [80, 120] needed = [10, 25, 75] loss = 0.25 self.planner = cutplanner.Planner(sizes, needed, loss) def test_get_largest(self): largest = self.planner.get_largest_stock() self.assertEqual(largest, 120) if __name__ == '__main__': unittest.main()
import cutplanner import unittest class TestPlanner(unittest.TestCase): def setUp(self): sizes = [80, 120] needed = [10, 25, 75] loss = 0.25 self.planner = cutplanner.Planner(sizes, needed, loss) def test_largest_stock(self): largest = self.planner.largest_stock self.assertEqual(largest, 120) if __name__ == '__main__': unittest.main()
Update test for largest stock
Update test for largest stock
Python
mit
alanc10n/py-cutplanner
--- +++ @@ -9,8 +9,8 @@ loss = 0.25 self.planner = cutplanner.Planner(sizes, needed, loss) - def test_get_largest(self): - largest = self.planner.get_largest_stock() + def test_largest_stock(self): + largest = self.planner.largest_stock self.assertEqual(largest, 120) if __name__ == '__main__':
14e39e28c22da59049feeae0efd1a9fa2bfb51e6
dockci/models/job_meta/config.py
dockci/models/job_meta/config.py
""" Job metadata stored along side the code """ from yaml_model import LoadOnAccess, Model, OnAccess def get_job(slug): """ Wrapper to import, and return a Job object for the JobConfig to avoid cyclic import """ from dockci.models.job import Job return Job.query.filter_by(slug=slug).first() class JobConfig(Model): # pylint:disable=too-few-public-methods """ Job config, loaded from the repo """ slug = 'dockci.yaml' job = OnAccess(lambda self: get_job(self.job_slug)) job_slug = OnAccess(lambda self: self.job.slug) # TODO infinite loop job_output = LoadOnAccess(default=lambda _: {}) services = LoadOnAccess(default=lambda _: {}) utilities = LoadOnAccess(default=lambda _: []) dockerfile = LoadOnAccess(default='Dockerfile') repo_name = LoadOnAccess(default=lambda self: self.job.project.slug) skip_tests = LoadOnAccess(default=False) def __init__(self, job): super(JobConfig, self).__init__() assert job is not None, "Job is given" self.job = job self.job_slug = job.slug def data_file_path(self): # Our data file path is <job output>/<slug> return self.job.job_output_path().join(JobConfig.slug)
""" Job metadata stored along side the code """ from yaml_model import LoadOnAccess, Model, OnAccess def get_job(slug): """ Wrapper to import, and return a Job object for the JobConfig to avoid cyclic import """ from dockci.models.job import Job return Job.load(slug) class JobConfig(Model): # pylint:disable=too-few-public-methods """ Job config, loaded from the repo """ slug = 'dockci.yaml' job = OnAccess(lambda self: get_job(self.job_slug)) job_slug = OnAccess(lambda self: self.job.slug) # TODO infinite loop job_output = LoadOnAccess(default=lambda _: {}) services = LoadOnAccess(default=lambda _: {}) utilities = LoadOnAccess(default=lambda _: []) dockerfile = LoadOnAccess(default='Dockerfile') repo_name = LoadOnAccess(default=lambda self: self.job.project.slug) skip_tests = LoadOnAccess(default=False) def __init__(self, job): super(JobConfig, self).__init__() assert job is not None, "Job is given" self.job = job self.job_slug = job.slug def data_file_path(self): # Our data file path is <job output>/<slug> return self.job.job_output_path().join(JobConfig.slug)
Fix OnAccess job link for JobConfig
Fix OnAccess job link for JobConfig
Python
isc
sprucedev/DockCI-Agent,sprucedev/DockCI-Agent
--- +++ @@ -11,7 +11,7 @@ cyclic import """ from dockci.models.job import Job - return Job.query.filter_by(slug=slug).first() + return Job.load(slug) class JobConfig(Model): # pylint:disable=too-few-public-methods
a1679be616d6d0d6ee807a708690549ec1798d04
python/array_manipulation.py
python/array_manipulation.py
#!/bin/python3 import math import os import random import re import sys def arrayManipulation(n, queries): array = [0] * n for a, b, k in queries: # Start is a - 1 because this is a one indexed array for i in range(a - 1, b): array[i] += k print(array) return max(array) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nm = input().split() n = int(nm[0]) m = int(nm[1]) queries = [] for _ in range(m): queries.append(list(map(int, input().rstrip().split()))) result = arrayManipulation(n, queries) fptr.write(str(result) + '\n') fptr.close()
#!/bin/python3 import math import os import random import re import sys def arrayManipulation(n, queries): # An array used to capture the difference of an element # compared to the previous element. # Therefore the value of diffs[n] after all array manipulations is # the cumulative sum of values from diffs[0] to diffs[n - 1] diffs = [0] * n for a, b, k in queries: # Adds "k" to all subsequent elements in the array diffs[a - 1] += k # Ignore if b is out of range if (b < n): # Subtracts "k" from all subsequent elements in the array diffs[b] -= k sumSoFar = 0 maxSoFar = 0 for diff in diffs: sumSoFar += diff if sumSoFar > maxSoFar: maxSoFar = sumSoFar return maxSoFar if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nm = input().split() n = int(nm[0]) m = int(nm[1]) queries = [] for _ in range(m): queries.append(list(map(int, input().rstrip().split()))) result = arrayManipulation(n, queries) fptr.write(str(result) + '\n') fptr.close()
Improve runtime by using an array of diffs
Improve runtime by using an array of diffs
Python
mit
rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank
--- +++ @@ -8,13 +8,26 @@ def arrayManipulation(n, queries): - array = [0] * n + # An array used to capture the difference of an element + # compared to the previous element. + # Therefore the value of diffs[n] after all array manipulations is + # the cumulative sum of values from diffs[0] to diffs[n - 1] + diffs = [0] * n for a, b, k in queries: - # Start is a - 1 because this is a one indexed array - for i in range(a - 1, b): - array[i] += k - print(array) - return max(array) + # Adds "k" to all subsequent elements in the array + diffs[a - 1] += k + # Ignore if b is out of range + if (b < n): + # Subtracts "k" from all subsequent elements in the array + diffs[b] -= k + + sumSoFar = 0 + maxSoFar = 0 + for diff in diffs: + sumSoFar += diff + if sumSoFar > maxSoFar: + maxSoFar = sumSoFar + return maxSoFar if __name__ == '__main__':
34a3bf209c1bb09e2057eb4dd91ef426e3107c11
monitor_temperature.py
monitor_temperature.py
import time import serial import matplotlib.pyplot as plt import csv import os import brewkettle reload(brewkettle) filename = time.strftime("%Y-%m-%d %H:%M") + ".csv" path = os.path.join("data", filename) f = open(path, "w") csv_writer = csv.writer(f) kettle = brewkettle.BrewKettle() kettle.turn_pump_on() start = time.time() previous = start while(True): try: now = time.time() if (now - previous > 2): temperature = kettle.get_temperature() current = now - start print "Time:\t\t" + str(current) print "Temperature:\t" + str(temperature) csv_writer.writerow((current, temperature)) previous = now except KeyboardInterrupt: f.close() kettle.exit() print "Done" break
import time import serial import matplotlib.pyplot as plt import csv import os import brewkettle reload(brewkettle) filename = time.strftime("%Y-%m-%d %H:%M") + ".csv" path = os.path.join("data", filename) f = open(path, "w") csv_writer = csv.writer(f) csv_writer.writerow(["Time [s]", "Temperature [C]"]) kettle = brewkettle.BrewKettle() kettle.turn_pump_on() kettle.turn_heater_on() start = time.time() previous = 0 while(True): try: now = time.time() if (now - previous > 10): temperature = kettle.get_temperature() current = now - start print "Time:\t\t" + str(current) print "Temperature:\t" + str(temperature) csv_writer.writerow((current, temperature)) previous = now except KeyboardInterrupt: f.close() kettle.exit() print "Done" break
Monitor temperature script as used for heating measurement
Monitor temperature script as used for heating measurement
Python
mit
beercanlah/ardumashtun,beercanlah/ardumashtun
--- +++ @@ -10,16 +10,18 @@ path = os.path.join("data", filename) f = open(path, "w") csv_writer = csv.writer(f) +csv_writer.writerow(["Time [s]", "Temperature [C]"]) kettle = brewkettle.BrewKettle() kettle.turn_pump_on() +kettle.turn_heater_on() start = time.time() -previous = start +previous = 0 while(True): try: now = time.time() - if (now - previous > 2): + if (now - previous > 10): temperature = kettle.get_temperature() current = now - start print "Time:\t\t" + str(current)
60c0f2b74d7459b955da28ff16f67db1e81f5789
moogle/search/views.py
moogle/search/views.py
# Stdlib imports # E.g.: from math import sqrt # Core Django imports from django.contrib.auth.decorators import login_required from django.shortcuts import redirect, render # Third-party app imports # E.g.: from django_extensions.db.models import TimeStampedModel # Imports from local apps from tokens.models import BearerToken, Provider from .snooper import Snooper def home(request, template='home.html'): if not request.user.is_authenticated(): return redirect('showcase_tour') args = { 'name_drive': Provider.NAME_DRIVE, 'name_gmail': Provider.NAME_GMAIL, 'name_facebook': Provider.NAME_FACEBOOK, 'name_twitter': Provider.NAME_TWITTER, 'name_dropbox': Provider.NAME_DROPBOX, } args.update(BearerToken.objects.providers_breakdown_for_user(request.user)) return render(request, template, args) @login_required def search(request, template='search.html'): q = request.GET.get('q', '') args = dict() for provider_name, __ in Provider.NAME_CHOICES: is_selected = True if request.GET.get(provider_name).lower() == 'true' else False args['{}_is_selected'.format(provider_name)] = is_selected results = Snooper(provider_name, request.user).search(q) if is_selected else [] args['{}_results'.format(provider_name)] = results return render(request, template, args)
# Stdlib imports # E.g.: from math import sqrt # Core Django imports from django.contrib.auth.decorators import login_required from django.shortcuts import redirect, render # Third-party app imports # E.g.: from django_extensions.db.models import TimeStampedModel # Imports from local apps from tokens.models import BearerToken, Provider from .snooper import Snooper def home(request, template='home.html'): if not request.user.is_authenticated(): return redirect('showcase_tour') args = { 'name_drive': Provider.NAME_DRIVE, 'name_gmail': Provider.NAME_GMAIL, 'name_facebook': Provider.NAME_FACEBOOK, 'name_twitter': Provider.NAME_TWITTER, 'name_dropbox': Provider.NAME_DROPBOX, } args.update(BearerToken.objects.providers_breakdown_for_user(request.user)) return render(request, template, args) @login_required def search(request, template='search.html'): q = request.GET.get('q', '') args = dict() for provider_name, __ in Provider.NAME_CHOICES: is_selected = True if request.GET.get(provider_name, '').lower() == 'true' else False args['{}_is_selected'.format(provider_name)] = is_selected results = Snooper(provider_name, request.user).search(q) if is_selected else [] args['{}_results'.format(provider_name)] = results return render(request, template, args)
Fix a issue when a provider has not been added
Fix a issue when a provider has not been added
Python
apache-2.0
nimiq/moogle-project
--- +++ @@ -33,7 +33,7 @@ q = request.GET.get('q', '') args = dict() for provider_name, __ in Provider.NAME_CHOICES: - is_selected = True if request.GET.get(provider_name).lower() == 'true' else False + is_selected = True if request.GET.get(provider_name, '').lower() == 'true' else False args['{}_is_selected'.format(provider_name)] = is_selected results = Snooper(provider_name, request.user).search(q) if is_selected else []
f748ed437bb37e10433d0ca1e695122b2c799a15
symposion/reviews/templatetags/review_tags.py
symposion/reviews/templatetags/review_tags.py
from django import template from symposion.reviews.models import ReviewAssignment register = template.Library() @register.assignment_tag(takes_context=True) def review_assignments(context): request = context["request"] assignments = ReviewAssignment.objects.filter(user=request.user) return assignments
from django import template from symposion.reviews.models import ReviewAssignment register = template.Library() @register.simple_tag(takes_context=True) def review_assignments(context): request = context["request"] assignments = ReviewAssignment.objects.filter(user=request.user) return assignments
Use simple_tag instead of assignment_tag.
Use simple_tag instead of assignment_tag. https://docs.djangoproject.com/en/2.2/releases/1.9/#assignment-tag
Python
mit
pydata/conf_site,pydata/conf_site,pydata/conf_site
--- +++ @@ -6,7 +6,7 @@ register = template.Library() -@register.assignment_tag(takes_context=True) +@register.simple_tag(takes_context=True) def review_assignments(context): request = context["request"] assignments = ReviewAssignment.objects.filter(user=request.user)
86fa8271b5788aadcbbde3decbcd413b9d22871c
util/namespace.py
util/namespace.py
""" Stuff for building namespace """ from _compat import * class Namespace(object): """ Backport of SimpleNamespace() class added in Python 3.3 """ __slots__ = '__doc__', '__dict__', '__weakref__' def __init__(self, **kwargs): self.__dict__.update(kwargs) def __iter__(self): return iter(self.__dict__) def __getitem__(self, key): return self.__dict__[key] def __setitem__(self, key, value): self.__dict__[key] = value def __delitem__(self, key): del self.__dict__[key] __hash__ = None def __eq__(self, other): return self.__dict__ == other.__dict__ def __repr__(self): keys = sorted(self.__dict__) items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys) return "{}({})".format(type(self).__name__, ", ".join(items))
""" Stuff for building namespace """ from _compat import * class Namespace(object): """ Backport of SimpleNamespace() class added in Python 3.3 """ __slots__ = '__doc__', '__dict__', '__weakref__' def __init__(self, **kwargs): super(Namespace, self).__init__() self.__dict__.update(kwargs) def __iter__(self): return iter(self.__dict__) def __getitem__(self, key): return self.__dict__[key] def __setitem__(self, key, value): self.__dict__[key] = value def __delitem__(self, key): del self.__dict__[key] __hash__ = None def __eq__(self, other): return self.__dict__ == other.__dict__ def __repr__(self): keys = sorted(self.__dict__) items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys) return "{}({})".format(type(self).__name__, ", ".join(items))
Call super __init__ from Namespace.__init__
util: Call super __init__ from Namespace.__init__
Python
unknown
embox/mybuild,abusalimov/mybuild,embox/mybuild,abusalimov/mybuild
--- +++ @@ -11,6 +11,7 @@ __slots__ = '__doc__', '__dict__', '__weakref__' def __init__(self, **kwargs): + super(Namespace, self).__init__() self.__dict__.update(kwargs) def __iter__(self):
253daeb2e826a9fe87cd93c9bc1a2060d9b8fead
tests/project/settings.py
tests/project/settings.py
DATABASES = { 'default': { 'ENGINE': 'sqlite3', 'NAME': ':memory:' } } MIDDLEWARE_CLASSES = [ 'fandjango.middleware.FacebookMiddleware' ] INSTALLED_APPS = [ 'fandjango', 'south', 'tests.project.app' ] ROOT_URLCONF = 'tests.project.urls' FACEBOOK_APPLICATION_ID = 181259711925270 FACEBOOK_APPLICATION_SECRET_KEY = '214e4cb484c28c35f18a70a3d735999b' FACEBOOK_APPLICATION_NAMESPACE = 'fandjango-test' FACEBOOK_APPLICATION_CANVAS_URL = 'http://example.org/foo'
DATABASES = { 'default': { 'ENGINE': 'sqlite3', 'NAME': ':memory:' } } MIDDLEWARE_CLASSES = [ 'fandjango.middleware.FacebookMiddleware' ] INSTALLED_APPS = [ 'fandjango', 'south', 'tests.project.app' ] SOUTH_TESTS_MIGRATE = False ROOT_URLCONF = 'tests.project.urls' FACEBOOK_APPLICATION_ID = 181259711925270 FACEBOOK_APPLICATION_SECRET_KEY = '214e4cb484c28c35f18a70a3d735999b' FACEBOOK_APPLICATION_NAMESPACE = 'fandjango-test' FACEBOOK_APPLICATION_CANVAS_URL = 'http://example.org/foo'
Disable South migrations for tests.
Disable South migrations for tests.
Python
mit
jgorset/fandjango,jgorset/fandjango
--- +++ @@ -15,6 +15,8 @@ 'tests.project.app' ] +SOUTH_TESTS_MIGRATE = False + ROOT_URLCONF = 'tests.project.urls' FACEBOOK_APPLICATION_ID = 181259711925270
9771381323e4eb44a13ffc8742615fba61ad2b85
lino/modlib/notify/consumers.py
lino/modlib/notify/consumers.py
from channels import Group def ws_echo(message): Group(str(message.content['text'])).add(message.reply_channel) message.reply_channel.send({ "text": message.content['text'], })
import json from channels import Channel from channels import Group from channels.auth import channel_session_user, channel_session_user_from_http from django.utils import timezone from lino.modlib.notify.models import Notification # This decorator copies the user from the HTTP session (only available in # websocket.connect or http.request messages) to the channel session (available # in all consumers with the same reply_channel, so all three here) @channel_session_user_from_http def ws_connect(message): pass def ws_receive(message): # All WebSocket frames have either a text or binary payload; we decode the # text part here assuming it's JSON. # You could easily build up a basic framework that did this encoding/decoding # for you as well as handling common errors. payload = json.loads(message['text']) payload['reply_channel'] = message.content['reply_channel'] Channel("notify.receive").send(payload) @channel_session_user def set_notification_as_seen(message): notification_id = message['notification_id'] notif = Notification.objects.get(pk=notification_id) notif.seen = timezone.now() notif.save() @channel_session_user def user_connected(message): username = message['username'] Group(username).add(message.reply_channel) message.reply_channel.send({ "text": username, })
Update receive and send functions according to the new requirements
Update receive and send functions according to the new requirements
Python
unknown
lsaffre/lino,lsaffre/lino,khchine5/lino,khchine5/lino,khchine5/lino,lino-framework/lino,lino-framework/lino,lsaffre/lino,lsaffre/lino,lino-framework/lino,lino-framework/lino,lsaffre/lino,khchine5/lino,khchine5/lino,lino-framework/lino
--- +++ @@ -1,8 +1,42 @@ +import json + +from channels import Channel from channels import Group +from channels.auth import channel_session_user, channel_session_user_from_http +from django.utils import timezone +from lino.modlib.notify.models import Notification -def ws_echo(message): - Group(str(message.content['text'])).add(message.reply_channel) +# This decorator copies the user from the HTTP session (only available in +# websocket.connect or http.request messages) to the channel session (available +# in all consumers with the same reply_channel, so all three here) +@channel_session_user_from_http +def ws_connect(message): + pass + + +def ws_receive(message): + # All WebSocket frames have either a text or binary payload; we decode the + # text part here assuming it's JSON. + # You could easily build up a basic framework that did this encoding/decoding + # for you as well as handling common errors. + payload = json.loads(message['text']) + payload['reply_channel'] = message.content['reply_channel'] + Channel("notify.receive").send(payload) + + +@channel_session_user +def set_notification_as_seen(message): + notification_id = message['notification_id'] + notif = Notification.objects.get(pk=notification_id) + notif.seen = timezone.now() + notif.save() + + +@channel_session_user +def user_connected(message): + username = message['username'] + Group(username).add(message.reply_channel) message.reply_channel.send({ - "text": message.content['text'], + "text": username, })
50ba0c2c576a4b9eddaa64537dadfd8684463794
ibmcnx/doc/DataSources.py
ibmcnx/doc/DataSources.py
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions cell = AdminConfig.getid( '/Cell:' + AdminControl.getCell() + '/' ) dbs = AdminConfig.list( 'DataSource', cell ) for db in dbs: t1 = ibmcnx.functions.getDSId( db ) AdminConfig.list( t1 )
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions cell = AdminConfig.getid( '"/Cell:' + AdminControl.getCell() + '/"' ) dbs = AdminConfig.list( 'DataSource', cell ) for db in dbs: t1 = ibmcnx.functions.getDSId( db ) AdminConfig.list( t1 )
Create script to save documentation to a file
4: Create script to save documentation to a file Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
--- +++ @@ -14,7 +14,7 @@ import ibmcnx.functions -cell = AdminConfig.getid( '/Cell:' + AdminControl.getCell() + '/' ) +cell = AdminConfig.getid( '"/Cell:' + AdminControl.getCell() + '/"' ) dbs = AdminConfig.list( 'DataSource', cell ) for db in dbs:
cd996486b25ab35369994a4470f795ae31e06a9c
unit_tests/test_ccs.py
unit_tests/test_ccs.py
#!/usr/bin/env python3 import unittest import sys # This line allows the tests to run if you just naively run this script. # But the preferred way is to use run_tests.sh sys.path.insert(0,'../MultiQC') from multiqc.modules.ccs.ccs import parse_ccs_log class Test(unittest.TestCase): def test_nothing(self): pass if __name__ == '__main__': unittest.main()
#!/usr/bin/env python3 import unittest import sys # This line allows the tests to run if you just naively run this script. # But the preferred way is to use run_tests.sh sys.path.insert(0,'../MultiQC') from multiqc.modules.ccs.ccs import parse_ccs_log class Test(unittest.TestCase): def test_parse_line(self): with open('data/ccs/ccs.report.txt') as fin: data = parse_ccs_log(fin) assert data['ZMWs input'] == 93 if __name__ == '__main__': unittest.main()
Add first test for ccs
Add first test for ccs
Python
mit
ewels/MultiQC_TestData,ewels/MultiQC_TestData,ewels/MultiQC_TestData,ewels/MultiQC_TestData,ewels/MultiQC_TestData
--- +++ @@ -11,8 +11,10 @@ class Test(unittest.TestCase): - def test_nothing(self): - pass + def test_parse_line(self): + with open('data/ccs/ccs.report.txt') as fin: + data = parse_ccs_log(fin) + assert data['ZMWs input'] == 93 if __name__ == '__main__': unittest.main()
9a52024ff5b8175ee8b8d4665d3c8c667003019b
glitter/blocks/redactor/tests.py
glitter/blocks/redactor/tests.py
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.assertEqual(1 + 1, 2)
# -*- coding: utf-8 -*- from __future__ import unicode_literals """ This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from django.test import TestCase from glitter.models import Version, ContentBlock from glitter.pages.models import Page from .models import Redactor class RedactorTestCase(TestCase): def setUp(self): User = get_user_model() page = Page.objects.create(url='/redactor/', title='Test page') self.page_content_type = ContentType.objects.get_for_model(Page) self.editor = User.objects.create_user(username='redactor', password='redactor') page_version = Version.objects.create( content_type=self.page_content_type, object_id=page.id, template_name='glitter/sample.html', owner=self.editor ) self.redactor_block = Redactor.objects.create( content='Test' ) self.content_block = ContentBlock.objects.create( obj_version=page_version, column='content', position=1, content_type=ContentType.objects.get_for_model(self.redactor_block), object_id=self.redactor_block.id ) self.redactor_block.content_block = self.content_block self.redactor_block.save() def test_existance(self): redactor = Redactor.objects.get(id=self.redactor_block.id) self.assertEqual(redactor.id, self.redactor_block.id)
Add test for redactor block creation
Add test for redactor block creation
Python
bsd-3-clause
developersociety/django-glitter,blancltd/django-glitter,developersociety/django-glitter,developersociety/django-glitter,blancltd/django-glitter,blancltd/django-glitter
--- +++ @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals """ This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". @@ -5,12 +7,43 @@ Replace this with more appropriate tests for your application. """ +from django.contrib.auth import get_user_model +from django.contrib.contenttypes.models import ContentType from django.test import TestCase +from glitter.models import Version, ContentBlock +from glitter.pages.models import Page -class SimpleTest(TestCase): - def test_basic_addition(self): - """ - Tests that 1 + 1 always equals 2. - """ - self.assertEqual(1 + 1, 2) +from .models import Redactor + + +class RedactorTestCase(TestCase): + def setUp(self): + User = get_user_model() + page = Page.objects.create(url='/redactor/', title='Test page') + + self.page_content_type = ContentType.objects.get_for_model(Page) + + self.editor = User.objects.create_user(username='redactor', password='redactor') + + page_version = Version.objects.create( + content_type=self.page_content_type, object_id=page.id, + template_name='glitter/sample.html', owner=self.editor + ) + self.redactor_block = Redactor.objects.create( + content='Test' + ) + + self.content_block = ContentBlock.objects.create( + obj_version=page_version, + column='content', + position=1, + content_type=ContentType.objects.get_for_model(self.redactor_block), + object_id=self.redactor_block.id + ) + self.redactor_block.content_block = self.content_block + self.redactor_block.save() + + def test_existance(self): + redactor = Redactor.objects.get(id=self.redactor_block.id) + self.assertEqual(redactor.id, self.redactor_block.id)
0b296bdef138ffc48363745e39d0d605e81b24cc
server.py
server.py
import bottle import waitress import controller import breathe from pytz import timezone from apscheduler.schedulers.background import BackgroundScheduler bottle_app = bottle.app() scheduler = BackgroundScheduler() scheduler.configure(timezone=timezone('US/Pacific')) breather = breathe.Breathe() my_controller = controller.Controller(bottle_app, breather) @scheduler.scheduled_job(trigger='cron', hour=22, minute=0) def on_job(): """Start at 10:00pm PT""" print('STARTING BREATHER') breather.restart() @scheduler.scheduled_job(trigger='cron', hour=0, minute=1) def off_job(): """End at 12:01am PT""" print("STOPPING BREATHER") breather.shutdown() if __name__ == '__main__': scheduler.start() waitress.serve(bottle_app, host='0.0.0.0', port=7000)
import bottle import waitress import controller import breathe from pytz import timezone from apscheduler.schedulers.background import BackgroundScheduler bottle_app = bottle.app() scheduler = BackgroundScheduler() scheduler.configure(timezone=timezone('US/Pacific')) breather = breathe.Breathe() my_controller = controller.Controller(bottle_app, breather) @scheduler.scheduled_job(trigger='cron', hour=20, minute=0) def on_job(): """Start at 10:00pm PT""" print('STARTING BREATHER') breather.restart() @scheduler.scheduled_job(trigger='cron', hour=0, minute=1) def off_job(): """End at 12:01am PT""" print("STOPPING BREATHER") breather.shutdown() if __name__ == '__main__': scheduler.start() waitress.serve(bottle_app, host='0.0.0.0', port=7000)
Set scheduler to start at 8pm
Set scheduler to start at 8pm
Python
mit
tipsqueal/duwamish-lighthouse,tipsqueal/duwamish-lighthouse,illumenati/duwamish-lighthouse,illumenati/duwamish-lighthouse,YonasBerhe/duwamish-lighthouse
--- +++ @@ -12,7 +12,7 @@ my_controller = controller.Controller(bottle_app, breather) -@scheduler.scheduled_job(trigger='cron', hour=22, minute=0) +@scheduler.scheduled_job(trigger='cron', hour=20, minute=0) def on_job(): """Start at 10:00pm PT""" print('STARTING BREATHER')
0fa002e66f82eff593514c2249c4229604ec0f0a
server.py
server.py
import web import cPickle as pickle import json urls = ( '/latest', 'latest', '/history', 'history' ) class latest: def GET(self): try: latest = pickle.load(open("latest.p", "r")) return json.dumps(latest) except: return "Could not read latest data" class history: def GET(self): try: history = pickle.load(open("history.p", "r")) return json.dumps(history) except: return "Could not read historic data" if __name__ == "__main__": app = web.application(urls, globals()) app.run()
import web import cPickle as pickle import json urls = ( '/latest', 'latest', '/history', 'history' ) class latest: def GET(self): try: with open("latest.p", 'r') as f: latest = pickle.load(f) return json.dumps(latest) except: return "Could not read latest data" class history: def GET(self): try: with open("history.p", 'r') as f: history = pickle.load(f) return json.dumps(history) except: return "Could not read historic data" if __name__ == "__main__": app = web.application(urls, globals()) app.run()
Make sure to close the file afterwards
Make sure to close the file afterwards
Python
mit
martindisch/SensorTag,martindisch/SensorTag,martindisch/SensorTag,martindisch/SensorTag
--- +++ @@ -10,7 +10,8 @@ class latest: def GET(self): try: - latest = pickle.load(open("latest.p", "r")) + with open("latest.p", 'r') as f: + latest = pickle.load(f) return json.dumps(latest) except: return "Could not read latest data" @@ -18,7 +19,8 @@ class history: def GET(self): try: - history = pickle.load(open("history.p", "r")) + with open("history.p", 'r') as f: + history = pickle.load(f) return json.dumps(history) except: return "Could not read historic data"
d936f53ae422fab360f5e1cd62f7114d91ba270c
extra_plots.py
extra_plots.py
""" Generate nice plots providing additional information """ import sys import numpy as np import matplotlib.pylab as plt def neural_spike(): """ Plot various neural spikes """ def do_plot(cell_evo): """ Plot [cAMP] for single cell over time """ plt.plot(range(len(cell_evo)), cell_evo) plt.title('cAMP concentration in single cell') plt.xlabel('t') plt.ylabel('cAMP concentration') #plt.savefig('images/neural_spike.png', bbox_inches='tight', dpi=300) plt.show() camp, pacemaker = np.load(sys.argv[1]) camp = np.rollaxis(camp, 0, 3) width, height, depth = camp.shape for j in range(width): for i in range(height): do_plot(camp[i, j]) if __name__ == '__main__': neural_spike()
""" Generate nice plots providing additional information """ import sys import numpy as np import matplotlib.pylab as plt from singularity_finder import compute_tau def neural_spike(): """ Plot various neural spikes """ def do_plot(cell_evo): """ Plot [cAMP] for single cell over time """ plt.plot(range(len(cell_evo)), cell_evo) plt.title('cAMP concentration in single cell') plt.xlabel('t') plt.ylabel('cAMP concentration') #plt.savefig('images/neural_spike.png', bbox_inches='tight', dpi=300) plt.show() camp, pacemaker = np.load(sys.argv[1]) camp = np.rollaxis(camp, 0, 3) width, height, depth = camp.shape for j in range(width): for i in range(height): do_plot(camp[i, j]) def lagged_phase_space(): """ Plot phase space lagged by tau """ def do_plot(cell_evo): x = [] y = [] for t in range(len(cell_evo) - tau): x.append(cell_evo[t + tau]) y.append(cell_evo[t]) plt.plot(x, y) plt.title(r'Lagged phase space of neural spike ($\tau = %d$)' % tau) plt.xlabel(r'$x_{ij}(t - \tau)$') plt.ylabel(r'$x_{ij}(t)$') #plt.savefig('images/lagged_phase_space.png', bbox_inches='tight', dpi=300) plt.show() camp, pacemaker = np.load(sys.argv[1]) camp = np.rollaxis(camp, 0, 3) tau = compute_tau(camp) width, height, depth = camp.shape for j in range(width): for i in range(height): do_plot(camp[i, j]) if __name__ == '__main__': #neural_spike() lagged_phase_space()
Add lagged phase space plot
Add lagged phase space plot
Python
mit
kpj/PyWave
--- +++ @@ -5,6 +5,8 @@ import numpy as np import matplotlib.pylab as plt + +from singularity_finder import compute_tau def neural_spike(): @@ -30,6 +32,36 @@ for i in range(height): do_plot(camp[i, j]) +def lagged_phase_space(): + """ Plot phase space lagged by tau + """ + def do_plot(cell_evo): + x = [] + y = [] + for t in range(len(cell_evo) - tau): + x.append(cell_evo[t + tau]) + y.append(cell_evo[t]) + + plt.plot(x, y) + + plt.title(r'Lagged phase space of neural spike ($\tau = %d$)' % tau) + plt.xlabel(r'$x_{ij}(t - \tau)$') + plt.ylabel(r'$x_{ij}(t)$') + + #plt.savefig('images/lagged_phase_space.png', bbox_inches='tight', dpi=300) + plt.show() + + camp, pacemaker = np.load(sys.argv[1]) + camp = np.rollaxis(camp, 0, 3) + + tau = compute_tau(camp) + + width, height, depth = camp.shape + for j in range(width): + for i in range(height): + do_plot(camp[i, j]) + if __name__ == '__main__': - neural_spike() + #neural_spike() + lagged_phase_space()
7316d1cb953812ae0286d59d1abc014b2f90794b
locust/__init__.py
locust/__init__.py
from .user.sequential_taskset import SequentialTaskSet from .user.task import task, TaskSet from .user.users import HttpUser, User from .event import Events from .wait_time import between, constant, constant_pacing events = Events() __version__ = "1.0b1"
from .user.sequential_taskset import SequentialTaskSet from .user.task import task, TaskSet from .user.users import HttpUser, User from .user.wait_time import between, constant, constant_pacing from .event import Events events = Events() __version__ = "1.0b1"
Move wait_time.py into user module
Move wait_time.py into user module
Python
mit
locustio/locust,mbeacom/locust,mbeacom/locust,mbeacom/locust,locustio/locust,locustio/locust,mbeacom/locust,locustio/locust
--- +++ @@ -1,8 +1,8 @@ from .user.sequential_taskset import SequentialTaskSet from .user.task import task, TaskSet from .user.users import HttpUser, User +from .user.wait_time import between, constant, constant_pacing from .event import Events -from .wait_time import between, constant, constant_pacing events = Events()
71eeb919373787569034225e8047079075df5569
Challenges/chall_06.py
Challenges/chall_06.py
#!/usr/local/bin/python3 # Python Challenge - 6 # http://www.pythonchallenge.com/pc/def/channel.html # http://www.pythonchallenge.com/pc/def/channel.zip # Keyword: hockey -> oxygen import re import zipfile def main(): ''' Hint: zip, now there are pairs In the readme.txt: welcome to my zipped list. hint1: start from 90052 hint2: answer is inside the zip Last nothing = 46145 Collect the comments ''' nothing = '90052' file_ext = '.txt' file_pattern = re.compile(r'Next nothing is (\d+)') zf = zipfile.ZipFile('./zip_chall_06/channel.zip') comments = [] while True: filename = nothing + file_ext data = zf.read(filename).decode('utf-8') match = re.search(file_pattern, data) if match: nothing = match.group(1) comments.append(zf.getinfo(filename).comment.decode('utf-8')) else: break # print('Last nothing is: {}'.format(nothing)) print(''.join(comments)) return 0 if __name__ == '__main__': main()
#!/usr/local/bin/python3 # Python Challenge - 6 # http://www.pythonchallenge.com/pc/def/channel.html # http://www.pythonchallenge.com/pc/def/channel.zip # Keyword: hockey -> oxygen import re import zipfile def main(): ''' Hint: zip, now there are pairs In the readme.txt: welcome to my zipped list. hint1: start from 90052 hint2: answer is inside the zip Last nothing = 46145 Collect the comments ''' nothing = '90052' file_ext = '.txt' file_pattern = re.compile(r'Next nothing is (\d+)') zf = zipfile.ZipFile('./zip_chall_06/channel.zip') comments = [] while True: filename = nothing + file_ext data = zf.read(filename).decode('utf-8') match = re.search(file_pattern, data) if match: nothing = match.group(1) # com = zf.getinfo(filename).comment.decode('utf-8') comments.append(zf.getinfo(filename).comment.decode('utf-8')) # print('Comment: {}'.format(com)) else: break # print('Last nothing is: {}'.format(nothing)) print(''.join(comments)) return 0 if __name__ == '__main__': main()
Add print statements for clarity
Add print statements for clarity
Python
mit
HKuz/PythonChallenge
--- +++ @@ -33,7 +33,9 @@ match = re.search(file_pattern, data) if match: nothing = match.group(1) + # com = zf.getinfo(filename).comment.decode('utf-8') comments.append(zf.getinfo(filename).comment.decode('utf-8')) + # print('Comment: {}'.format(com)) else: break
3d1521892ba17120ca4461335713b9d2254311fe
marble/tests/test_clustering.py
marble/tests/test_clustering.py
""" Tests for the clustering computation """ from nose.tools import * import marble as mb # Test c = 0 in the checkerboard case # Test c = 1 in the fully clustered case # Test an intermediate situation with known result
""" Tests for the clustering computation """ from nose.tools import * import itertools from shapely.geometry import Polygon import marble as mb # # Synthetic data for tests # def grid(): """ Areal units arranged in a grid """ au = [i*3+j for i,j in itertools.product(range(3), repeat=2)] units = {a:Polygon([(a%3, a/3), (a%3, 1+a/3), (1+a%3, 1+a/3), (1+a%3, a/3)]) for a in au} return units def checkerboard_city(): city = {0: {"A":100, "B":1}, 1: {"A":1, "B":100}, 2: {"A":100, "B":1}, 3: {"A":1, "B":100}, 4: {"A":100, "B":1}, 5: {"A":1, "B":100}, 6: {"A":100, "B":1}, 7: {"A":1, "B":100}, 8: {"A":100, "B":1}} return city def clustered_city(): city = {0: {"A":100, "B":1}, 1: {"A":100, "B":1}, 2: {"A":1, "B":100}, 3: {"A":100, "B":1}, 4: {"A":1, "B":100}, 5: {"A":1, "B":100}, 6: {"A":100, "B":1}, 7: {"A":1, "B":100}, 8: {"A":1, "B":100}} return city # # Perform tests # class TestClustering(object): def test_clustering_checkerboard(self): units = grid() city = checkerboard_city() c = mb.clustering(city, units) assert c["A"] == 0.0 assert c["B"] == 0.0 def test_clustering_checkerboard(self): units = grid() city = clustered_city() c = mb.clustering(city, units) assert c["A"] == 1.0 assert c["B"] == 1.0
Add tests for the clustering of cities
Add tests for the clustering of cities
Python
bsd-3-clause
walkerke/marble,scities/marble
--- +++ @@ -1,9 +1,66 @@ """ Tests for the clustering computation """ from nose.tools import * +import itertools +from shapely.geometry import Polygon import marble as mb -# Test c = 0 in the checkerboard case -# Test c = 1 in the fully clustered case -# Test an intermediate situation with known result +# +# Synthetic data for tests +# +def grid(): + """ Areal units arranged in a grid """ + au = [i*3+j for i,j in itertools.product(range(3), repeat=2)] + units = {a:Polygon([(a%3, a/3), + (a%3, 1+a/3), + (1+a%3, 1+a/3), + (1+a%3, a/3)]) for a in au} + return units +def checkerboard_city(): + city = {0: {"A":100, "B":1}, + 1: {"A":1, "B":100}, + 2: {"A":100, "B":1}, + 3: {"A":1, "B":100}, + 4: {"A":100, "B":1}, + 5: {"A":1, "B":100}, + 6: {"A":100, "B":1}, + 7: {"A":1, "B":100}, + 8: {"A":100, "B":1}} + return city + +def clustered_city(): + city = {0: {"A":100, "B":1}, + 1: {"A":100, "B":1}, + 2: {"A":1, "B":100}, + 3: {"A":100, "B":1}, + 4: {"A":1, "B":100}, + 5: {"A":1, "B":100}, + 6: {"A":100, "B":1}, + 7: {"A":1, "B":100}, + 8: {"A":1, "B":100}} + return city + + + +# +# Perform tests +# +class TestClustering(object): + + def test_clustering_checkerboard(self): + units = grid() + city = checkerboard_city() + c = mb.clustering(city, units) + + assert c["A"] == 0.0 + assert c["B"] == 0.0 + + def test_clustering_checkerboard(self): + units = grid() + city = clustered_city() + c = mb.clustering(city, units) + + assert c["A"] == 1.0 + assert c["B"] == 1.0 +
36ac84a0c8967b994242903a4cd404eac33af381
sipa/model/pycroft/schema.py
sipa/model/pycroft/schema.py
# -*- coding: utf-8 -*- from __future__ import annotations from typing import List, Optional from sipa.model.pycroft.unserialize import unserializer @unserializer class UserData: id: int user_id: str login: str name: str status: UserStatus room: str mail: str cache: bool traffic_balance: int traffic_history: List[TrafficHistoryEntry] interfaces: List[Interface] finance_balance: int finance_history: List[FinanceHistoryEntry] # TODO implement `cls.Meta.custom_constructors`, use `parse_date` for this last_finance_update: str # TODO introduce properties once they can be excluded @unserializer class UserStatus: member: bool traffic_exceeded: bool network_access: bool account_balanced: bool violation: bool @unserializer class Interface: id: int mac: str ips: List[str] @unserializer class TrafficHistoryEntry: timestamp: str ingress: Optional[int] egress: Optional[int] balance: Optional[int] @unserializer class FinanceHistoryEntry: valid_on: str amount: int description: str
# -*- coding: utf-8 -*- from __future__ import annotations from typing import List, Optional from sipa.model.pycroft.unserialize import unserializer @unserializer class UserData: id: int user_id: str login: str name: str status: UserStatus room: str mail: str cache: bool traffic_history: List[TrafficHistoryEntry] interfaces: List[Interface] finance_balance: int finance_history: List[FinanceHistoryEntry] # TODO implement `cls.Meta.custom_constructors`, use `parse_date` for this last_finance_update: str # TODO introduce properties once they can be excluded @unserializer class UserStatus: member: bool traffic_exceeded: bool network_access: bool account_balanced: bool violation: bool @unserializer class Interface: id: int mac: str ips: List[str] @unserializer class TrafficHistoryEntry: timestamp: str ingress: Optional[int] egress: Optional[int] @unserializer class FinanceHistoryEntry: valid_on: str amount: int description: str
Remove references to traffic balance
Remove references to traffic balance
Python
mit
MarauderXtreme/sipa,agdsn/sipa,MarauderXtreme/sipa,MarauderXtreme/sipa,agdsn/sipa,agdsn/sipa,agdsn/sipa
--- +++ @@ -15,7 +15,6 @@ room: str mail: str cache: bool - traffic_balance: int traffic_history: List[TrafficHistoryEntry] interfaces: List[Interface] finance_balance: int @@ -47,7 +46,6 @@ timestamp: str ingress: Optional[int] egress: Optional[int] - balance: Optional[int] @unserializer
610fb9c9ac6a225df10ec770d44564e61af53ce0
polling_stations/apps/addressbase/management/commands/import_cleaned_addresses.py
polling_stations/apps/addressbase/management/commands/import_cleaned_addresses.py
import os import glob from django.apps import apps from django.db import connection from django.core.management.base import BaseCommand class Command(BaseCommand): """ Turn off auto system check for all apps We will maunally run system checks only for the 'addressbase' and 'pollingstations' apps """ requires_system_checks = False def add_arguments(self, parser): parser.add_argument( 'cleaned_ab_path', help='The path to the folder containing the cleaned AddressBase CSVs' ) def handle(self, *args, **kwargs): """ Manually run system checks for the 'addressbase' and 'pollingstations' apps Management commands can ignore checks that only apply to the apps supporting the website part of the project """ self.check([ apps.get_app_config('addressbase'), apps.get_app_config('pollingstations') ]) glob_str = os.path.join( kwargs['cleaned_ab_path'], "*_cleaned.csv" ) for cleaned_file_path in glob.glob(glob_str): print(cleaned_file_path) cursor = connection.cursor() cursor.execute(""" COPY addressbase_address (UPRN,address,postcode,location) FROM '{}' (FORMAT CSV, DELIMITER ',', quote '"'); """.format(cleaned_file_path))
import os import glob from django.apps import apps from django.db import connection from django.core.management.base import BaseCommand class Command(BaseCommand): """ Turn off auto system check for all apps We will maunally run system checks only for the 'addressbase' and 'pollingstations' apps """ requires_system_checks = False def add_arguments(self, parser): parser.add_argument( 'cleaned_ab_path', help='The path to the folder containing the cleaned AddressBase CSVs' ) def handle(self, *args, **kwargs): """ Manually run system checks for the 'addressbase' and 'pollingstations' apps Management commands can ignore checks that only apply to the apps supporting the website part of the project """ self.check([ apps.get_app_config('addressbase'), apps.get_app_config('pollingstations') ]) glob_str = os.path.join( kwargs['cleaned_ab_path'], "*_cleaned.csv" ) for cleaned_file_path in glob.glob(glob_str): cleaned_file_path = os.path.abspath(cleaned_file_path) print(cleaned_file_path) cursor = connection.cursor() cursor.execute(""" COPY addressbase_address (UPRN,address,postcode,location) FROM '{}' (FORMAT CSV, DELIMITER ',', quote '"'); """.format(cleaned_file_path))
Use abspath for COPY command
Use abspath for COPY command
Python
bsd-3-clause
chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations
--- +++ @@ -38,6 +38,7 @@ "*_cleaned.csv" ) for cleaned_file_path in glob.glob(glob_str): + cleaned_file_path = os.path.abspath(cleaned_file_path) print(cleaned_file_path) cursor = connection.cursor()
b556bffeb5ed48812258b452e05cc00cfb160453
girder/app/app/configuration.py
girder/app/app/configuration.py
from girder.api import access from girder.api.describe import Description, autoDescribeRoute from girder.api.rest import Resource, RestException from girder.constants import AccessType, TokenScope from girder.models.setting import Setting from .constants import Features, Deployment, Branding class Configuration(Resource): def __init__(self): super(Configuration, self).__init__() self.resourceName = 'configuration' self.route('GET', (), self.get) @access.public @autoDescribeRoute( Description('Get the deployment configuration.') ) def get(self): return { 'features': { 'notebooks': Setting().get(Features.NOTEBOOKS, True) }, 'deployment': { 'site': Setting().get(Deployment.SITE, '') }, 'branding': { 'license': Setting().get(Branding.LICENSE), 'privacy': Setting().get(Branding.PRIVACY), 'headerLogoFileId': Setting().get(Branding.HEADER_LOGO_ID), 'footerLogoFileId': Setting().get(Branding.FOOTER_LOGO_ID), 'footerLogoUrl': Setting().get(Branding.FOOTER_LOGO_URL), 'faviconFileId': Setting().get(Branding.FAVICON_ID) } }
from girder.api import access from girder.api.describe import Description, autoDescribeRoute from girder.api.rest import Resource, RestException from girder.constants import AccessType, TokenScope from girder.models.setting import Setting from .constants import Features, Deployment, Branding class Configuration(Resource): def __init__(self): super(Configuration, self).__init__() self.resourceName = 'configuration' self.route('GET', (), self.get) @access.public @autoDescribeRoute( Description('Get the deployment configuration.') ) def get(self): notebooks = Setting().get(Features.NOTEBOOKS) if notebooks is None: notebooks = True site = Setting().get(Deployment.SITE) if site is None: site = '' return { 'features': { 'notebooks': notebooks }, 'deployment': { 'site': site }, 'branding': { 'license': Setting().get(Branding.LICENSE), 'privacy': Setting().get(Branding.PRIVACY), 'headerLogoFileId': Setting().get(Branding.HEADER_LOGO_ID), 'footerLogoFileId': Setting().get(Branding.FOOTER_LOGO_ID), 'footerLogoUrl': Setting().get(Branding.FOOTER_LOGO_URL), 'faviconFileId': Setting().get(Branding.FAVICON_ID) } }
Fix up settings for upstream Girder change
Fix up settings for upstream Girder change
Python
bsd-3-clause
OpenChemistry/mongochemserver
--- +++ @@ -18,12 +18,21 @@ Description('Get the deployment configuration.') ) def get(self): + + notebooks = Setting().get(Features.NOTEBOOKS) + if notebooks is None: + notebooks = True + + site = Setting().get(Deployment.SITE) + if site is None: + site = '' + return { 'features': { - 'notebooks': Setting().get(Features.NOTEBOOKS, True) + 'notebooks': notebooks }, 'deployment': { - 'site': Setting().get(Deployment.SITE, '') + 'site': site }, 'branding': { 'license': Setting().get(Branding.LICENSE),
a242100ccbeb1f647e9778ea853da40a2420e56a
fedimg/consumers.py
fedimg/consumers.py
#!/bin/env python # -*- coding: utf8 -*- import fedmsg.consumers import fedmsg.encoding import fedimg.uploader class KojiConsumer(fedmsg.consumers.FedmsgConsumer): # To our knowledge, all *image* builds appear under this # exact topic, along with scratch builds. topic = 'org.fedoraproject.prod.buildsys.task.state.change' config_key = 'kojiconsumer' def __init__(self, *args, **kwargs): super(KojiConsumer, self).__init__(*args, **kwargs) def consume(self, msg): """Here we put what we'd like to do when we receive the message.""" builds = list() # These will be the Koji build IDs to upload, if any. msg_info = msg["msg"]["info"] # If the build method is "image", we check to see if the child # task's method is "createImage". if msg_info["method"] == "image": if isinstance(msg_info["children"], list): for child in msg_info["children"]: if child["method"] == "createImage": # We only care about the image if the build # completed successfully (with state code 2). if child["state"] == 2: builds.append(child["id"]) if len(builds) > 0: fedimg.uploader.upload(builds)
#!/bin/env python # -*- coding: utf8 -*- import fedmsg.consumers import fedmsg.encoding import fedimg.uploader class KojiConsumer(fedmsg.consumers.FedmsgConsumer): # To our knowledge, all *image* builds appear under this # exact topic, along with scratch builds. topic = 'org.fedoraproject.prod.buildsys.task.state.change' config_key = 'kojiconsumer' def __init__(self, *args, **kwargs): super(KojiConsumer, self).__init__(*args, **kwargs) def consume(self, msg): """Here we put what we'd like to do when we receive the message.""" builds = list() # These will be the Koji build IDs to upload, if any. msg_info = msg["body"]["msg"]["info"] # If the build method is "image", we check to see if the child # task's method is "createImage". if msg_info["method"] == "image": if isinstance(msg_info["children"], list): for child in msg_info["children"]: if child["method"] == "createImage": # We only care about the image if the build # completed successfully (with state code 2). if child["state"] == 2: builds.append(child["id"]) if len(builds) > 0: fedimg.uploader.upload(builds)
Fix KeyError when getting fedmsg message info.
Fix KeyError when getting fedmsg message info.
Python
agpl-3.0
fedora-infra/fedimg,fedora-infra/fedimg
--- +++ @@ -21,7 +21,7 @@ builds = list() # These will be the Koji build IDs to upload, if any. - msg_info = msg["msg"]["info"] + msg_info = msg["body"]["msg"]["info"] # If the build method is "image", we check to see if the child # task's method is "createImage".
b382c57e84d239f3f239f9e2587a3559e704f071
mozcal/events/api.py
mozcal/events/api.py
from tastypie.resources import ModelResource from models import Event from mozcal.base.serializers import MozcalSerializer class EventResource(ModelResource): class Meta: queryset = Event.objects.all() filtering = { "title": ('startswith',), } allowed_methods = ['get'] serializer = MozcalSerializer(formats=['json', 'csv'])
from tastypie.resources import ModelResource from models import Event from mozcal.base.serializers import MozcalSerializer class EventResource(ModelResource): class Meta: queryset = Event.objects.all() filtering = { "title": ('startswith',), } allowed_methods = ['get'] include_resource_uri = False include_absolute_url = False serializer = MozcalSerializer(formats=['json', 'csv'])
Exclude uri fields from EventResource
Exclude uri fields from EventResource
Python
bsd-3-clause
yvan-sraka/wprevents,yvan-sraka/wprevents,yvan-sraka/wprevents,ppapadeas/wprevents,ppapadeas/wprevents,ppapadeas/wprevents,yvan-sraka/wprevents
--- +++ @@ -11,5 +11,7 @@ "title": ('startswith',), } allowed_methods = ['get'] + include_resource_uri = False + include_absolute_url = False serializer = MozcalSerializer(formats=['json', 'csv'])
6c922f593dba7f3604763bbb489a910dee4c915a
.vim/templates/argparse.py
.vim/templates/argparse.py
import argparse parser = argparse.ArgumentParser(description='A useful description of this script (might want to set this to __doc__)', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-x', metavar='nameofx', nargs='+', type=float, default=32*32*32, help='Helpful message about this argument') grp = parser.add_mutually_exclusive_group() grp.add_argument('--option1', dest='destination', action='store_const', const='option1_const') grp.add_argument('--option2', dest='destination', action='store_const', const='option2_const') args = parser.parse_args()
import argparse parser = argparse.ArgumentParser(description='A useful description of this script (might want to set this to __doc__)', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('strarg', type=str, help='A string argument') parser.add_argument('numarg', type=float, help='A numerical argument') parser.add_argument('-x', metavar='nameofx', nargs='+', type=float, default=32*32*32, help='Helpful message about this argument') grp = parser.add_mutually_exclusive_group() grp.add_argument('--option1', dest='destination', action='store_const', const='option1_const') grp.add_argument('--option2', dest='destination', action='store_const', const='option2_const') args = parser.parse_args()
Add typed positional argument examples
Add typed positional argument examples
Python
mit
SnoopJeDi/dotfiles,SnoopJeDi/dotfiles,SnoopJeDi/dotfiles
--- +++ @@ -1,6 +1,8 @@ import argparse parser = argparse.ArgumentParser(description='A useful description of this script (might want to set this to __doc__)', formatter_class=argparse.ArgumentDefaultsHelpFormatter) +parser.add_argument('strarg', type=str, help='A string argument') +parser.add_argument('numarg', type=float, help='A numerical argument') parser.add_argument('-x', metavar='nameofx', nargs='+', type=float, default=32*32*32, help='Helpful message about this argument') grp = parser.add_mutually_exclusive_group()
0377db272c5535b478732fbf045a73b30a5eac00
migrations/versions/849170064430_.py
migrations/versions/849170064430_.py
"""add enqueue_job column to smtpserver table Revision ID: 849170064430 Revises: a63df077051a Create Date: 2018-11-22 10:04:00.330101 """ # revision identifiers, used by Alembic. revision = '849170064430' down_revision = 'a63df077051a' from alembic import op import sqlalchemy as sa def upgrade(): try: op.add_column('smtpserver', sa.Column('enqueue_job', sa.Boolean(), nullable=False, server_default=sa.false())) except Exception as exx: print("Could not add column 'smtpserver.enqueue_job'") print(exx) def downgrade(): op.drop_column('smtpserver', 'enqueue_job')
"""add enqueue_job column to smtpserver table Revision ID: 849170064430 Revises: a63df077051a Create Date: 2018-11-22 10:04:00.330101 """ # revision identifiers, used by Alembic. revision = '849170064430' down_revision = '48ee74b8a7c8' from alembic import op import sqlalchemy as sa def upgrade(): try: op.add_column('smtpserver', sa.Column('enqueue_job', sa.Boolean(), nullable=False, server_default=sa.false())) except Exception as exx: print("Could not add column 'smtpserver.enqueue_job'") print(exx) def downgrade(): op.drop_column('smtpserver', 'enqueue_job')
Update down-revision of queue migration script
Update down-revision of queue migration script
Python
agpl-3.0
privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea
--- +++ @@ -8,7 +8,7 @@ # revision identifiers, used by Alembic. revision = '849170064430' -down_revision = 'a63df077051a' +down_revision = '48ee74b8a7c8' from alembic import op import sqlalchemy as sa
3ad640e7881903caaa9faee12aaedf9990881513
weather_api/weather/management/commands/save_locations_to_database.py
weather_api/weather/management/commands/save_locations_to_database.py
from django.core.management import BaseCommand from django_pyowm.models import Location from pyowm.webapi25.location import Location as LocationEntity from weather_api.weather.singletons import owm class Command(BaseCommand): help = 'Save all locations from file to database' def handle(self, *args, **options): if Location.objects.exists(): self.stderr.write('You can save locations only to empty table') return city_registry = owm.city_id_registry() locations = [] for line in city_registry._get_all_lines(): tokens = line.strip().split(',') try: location_entity = LocationEntity(tokens[0], float(tokens[3]), float(tokens[2]), int(tokens[1]), tokens[4]) location = Location.from_entity(location_entity) locations.append(location) except ValueError: pass Location.objects.bulk_create(locations, 10000) self.stdout.write(self.style.SUCCESS('{} locations saved to database'.format(len(locations))))
from django.core.management import BaseCommand from django_pyowm.models import Location from pyowm.webapi25.location import Location as LocationEntity from weather_api.weather.singletons import owm class Command(BaseCommand): help = 'Save all locations from file to database' def handle(self, *args, **options): if Location.objects.exists(): self.stderr.write('You can save locations only to empty table') return city_registry = owm.city_id_registry() locations = [] for line in city_registry._get_all_lines(): tokens = line.strip().split(',') try: location_entity = LocationEntity(tokens[0], float(tokens[3]), float(tokens[2]), int(tokens[1]), tokens[4]) location = Location.from_entity(location_entity) locations.append(location) except ValueError: pass Location.objects.bulk_create(locations, 500) self.stdout.write(self.style.SUCCESS('{} locations saved to database'.format(len(locations))))
Make batch less, because sqlite cannot handle big batches
Make batch less, because sqlite cannot handle big batches
Python
mit
dimka2014/weather-api,dimka2014/weather-api
--- +++ @@ -23,5 +23,5 @@ locations.append(location) except ValueError: pass - Location.objects.bulk_create(locations, 10000) + Location.objects.bulk_create(locations, 500) self.stdout.write(self.style.SUCCESS('{} locations saved to database'.format(len(locations))))
30c2463fbe5c14273bd23d05ac2d97450285132e
client/config.py
client/config.py
# set debug to False on non prod env IS_DEV = True # profile speed of methods and output it to terminal PROFILE_METHODS = False # set to false if you want to disable accessing redis CACHE_DATA = True
# set debug to False on non prod env IS_DEV = True # profile speed of methods and output it to terminal PROFILE_METHODS = False # set to false if you want to disable accessing redis CACHE_DATA = False
Reset caching variable to False
Reset caching variable to False
Python
mit
SAAVY/magpie,SAAVY/magpie
--- +++ @@ -5,4 +5,4 @@ PROFILE_METHODS = False # set to false if you want to disable accessing redis -CACHE_DATA = True +CACHE_DATA = False
dfbae8fd2f2346ecf7bb1e04c9c43c18e4da234d
src/encoded/authorization.py
src/encoded/authorization.py
from sqlalchemy.orm.exc import NoResultFound from .storage import ( DBSession, UserMap, ) def groupfinder(login, request): if ':' not in login: return None namespace, localname = login.split(':', 1) if namespace == 'mailto': session = DBSession() query = session.query(UserMap).filter(UserMap.login == login) try: user = query.one().user principals = ['userid:' + str(user.rid)] principals.extend('lab:' + lab_uuid for lab_uuid in user.statement.object.get('lab_uuids', [])) return principals except NoResultFound: return None elif namespace == 'remoteuser': if localname in ['TEST', 'IMPORT']: return ['group:admin']
from sqlalchemy.orm.exc import NoResultFound from .storage import ( DBSession, UserMap, ) def groupfinder(login, request): if ':' not in login: return None namespace, localname = login.split(':', 1) if namespace == 'mailto': session = DBSession() model = session.query(UserMap).get(login) if model is None: return None user = model.user principals = ['userid:' + str(user.rid)] principals.extend('lab:' + lab_uuid for lab_uuid in user.statement.object.get('lab_uuids', [])) return principals elif namespace == 'remoteuser': if localname in ['TEST', 'IMPORT']: return ['group:admin']
Simplify the groupfinder a little. In general we should try to use session.query(...).get() rather than .filter().
Simplify the groupfinder a little. In general we should try to use session.query(...).get() rather than .filter().
Python
mit
kidaa/encoded,philiptzou/clincoded,ENCODE-DCC/snovault,T2DREAM/t2dream-portal,hms-dbmi/fourfront,hms-dbmi/fourfront,ClinGen/clincoded,ENCODE-DCC/snovault,ClinGen/clincoded,ENCODE-DCC/encoded,T2DREAM/t2dream-portal,philiptzou/clincoded,T2DREAM/t2dream-portal,4dn-dcic/fourfront,kidaa/encoded,kidaa/encoded,T2DREAM/t2dream-portal,hms-dbmi/fourfront,ENCODE-DCC/encoded,philiptzou/clincoded,philiptzou/clincoded,hms-dbmi/fourfront,ClinGen/clincoded,4dn-dcic/fourfront,ENCODE-DCC/encoded,4dn-dcic/fourfront,kidaa/encoded,philiptzou/clincoded,hms-dbmi/fourfront,ClinGen/clincoded,ClinGen/clincoded,4dn-dcic/fourfront,ENCODE-DCC/snovault,ENCODE-DCC/encoded,ENCODE-DCC/snovault,ENCODE-DCC/snovault,kidaa/encoded
--- +++ @@ -12,14 +12,13 @@ if namespace == 'mailto': session = DBSession() - query = session.query(UserMap).filter(UserMap.login == login) - try: - user = query.one().user - principals = ['userid:' + str(user.rid)] - principals.extend('lab:' + lab_uuid for lab_uuid in user.statement.object.get('lab_uuids', [])) - return principals - except NoResultFound: + model = session.query(UserMap).get(login) + if model is None: return None + user = model.user + principals = ['userid:' + str(user.rid)] + principals.extend('lab:' + lab_uuid for lab_uuid in user.statement.object.get('lab_uuids', [])) + return principals elif namespace == 'remoteuser': if localname in ['TEST', 'IMPORT']:
4765390537713d09b683c3cdbe22d128e00662f2
tests/integration/test_frontend.py
tests/integration/test_frontend.py
""" Test the frontend. """ from base import IntegrationTestCase from abilian.web.frontend import CRUDApp, BreadCrumbs class FrontendTestCase(IntegrationTestCase): def test(self): pass
""" Test the frontend. """ from flask.ext.wtf import Form from sqlalchemy import Column, UnicodeText, String from abilian.core.entities import Entity from abilian.web.frontend import CRUDApp, Module from .base import IntegrationTestCase class EmailAddress(object): pass class Contact(Entity): __tablename__ = 'contact' email = Column(String, nullable=False) first_name = Column(UnicodeText) last_name = Column(UnicodeText) class ContactEditForm(Form): _groups = [ [u'Main', ['email', 'first_name', 'last_name']] ] class Contacts(Module): managed_class = Contact list_view_columns = [ dict(name='_name', width=35), dict(name='partenaire', width=25), dict(name='titre', width=14), dict(name='email', width=20)] edit_form_class = ContactEditForm related_views = [ # TODO #('Visites', 'visites', ('partenaire', 'visiteur', 'date')), ] class SimpleCRM(CRUDApp): modules = [Contacts()] url = "/crm" class FrontendTestCase(IntegrationTestCase): def setUp(self): crm = SimpleCRM(self.app) def test(self): pass
Add integration tests for CRM app.
Add integration tests for CRM app.
Python
lgpl-2.1
abilian/abilian-core,abilian/abilian-core,abilian/abilian-core,abilian/abilian-core,abilian/abilian-core
--- +++ @@ -1,12 +1,58 @@ """ Test the frontend. """ +from flask.ext.wtf import Form +from sqlalchemy import Column, UnicodeText, String +from abilian.core.entities import Entity +from abilian.web.frontend import CRUDApp, Module -from base import IntegrationTestCase -from abilian.web.frontend import CRUDApp, BreadCrumbs +from .base import IntegrationTestCase + + +class EmailAddress(object): + pass + + +class Contact(Entity): + __tablename__ = 'contact' + + email = Column(String, nullable=False) + first_name = Column(UnicodeText) + last_name = Column(UnicodeText) + + +class ContactEditForm(Form): + _groups = [ + [u'Main', ['email', 'first_name', 'last_name']] + ] + + +class Contacts(Module): + managed_class = Contact + + list_view_columns = [ + dict(name='_name', width=35), + dict(name='partenaire', width=25), + dict(name='titre', width=14), + dict(name='email', width=20)] + + edit_form_class = ContactEditForm + + related_views = [ + # TODO + #('Visites', 'visites', ('partenaire', 'visiteur', 'date')), + ] + + +class SimpleCRM(CRUDApp): + modules = [Contacts()] + url = "/crm" class FrontendTestCase(IntegrationTestCase): + def setUp(self): + crm = SimpleCRM(self.app) + def test(self): pass
b7bb3b0782fcece12531b90a17eda98c4ae59be0
notes/templatetags/note_tags.py
notes/templatetags/note_tags.py
from django.template import Library, Node, TemplateSyntaxError from django.utils.html import escape from django.utils.http import urlquote from django.utils.safestring import mark_safe from notes.models import Note from castle.models import Profile register = Library() #----------------------------------------------------------------------------- @register.filter def note_link(note): if note is None: return u'<NULL NOTE>' if note.read_date is None: return mark_safe(u'<b><a href="/notes/view/' + unicode(note.id) + u'" class="note-link">' + escape(note.subject) + u'</a></b>') else: return mark_safe(u'<a href="/notes/view/' + unicode(note.id) + u'" class="note-link">' + escape(note.subject) + u'</a>') #----------------------------------------------------------------------------- @register.filter def inbox_count(profile): count = Note.objects.filter(recipient=profile, read_date__isnull=True, recipient_deleted_date__isnull=True).count() return mark_safe(u'<span class="inbox-count">' + escape(count) + u'</span>') #----------------------------------------------------------------------------- @register.filter def author_msg(profile): return mark_safe(u'<a class="btn btn-success author-msg-btn" href="/notes/compose?recipient=' + escape(profile.pen_name) + u'" type="button"><span class="glyphicon glyphicon-pencil"></span> Message ' + escape(profile.pen_name) + u'</a>')
from django.template import Library, Node, TemplateSyntaxError from django.utils.html import escape from django.utils.http import urlquote from django.utils.safestring import mark_safe from notes.models import Note from castle.models import Profile register = Library() #----------------------------------------------------------------------------- @register.filter def note_link(note): if note is None: return u'<NULL NOTE>' if note.read_date is None: return mark_safe(u'<b><a href="/notes/view/' + unicode(note.id) + u'" class="note-link">' + escape(note.subject) + u'</a></b>') else: return mark_safe(u'<a href="/notes/view/' + unicode(note.id) + u'" class="note-link">' + escape(note.subject) + u'</a>') #----------------------------------------------------------------------------- @register.filter def inbox_count(profile): count = Note.objects.filter(recipient=profile, read_date__isnull=True, recipient_deleted_date__isnull=True).count() if count > 0: return mark_safe(u'<span class="inbox-count">' + escape(count) + u'</span>') else: return mark_safe(u'<span>' + escape(count) + u'</span>') #----------------------------------------------------------------------------- @register.filter def author_msg(profile): return mark_safe(u'<a class="btn btn-success author-msg-btn" href="/notes/compose?recipient=' + escape(profile.pen_name) + u'" type="button"><span class="glyphicon glyphicon-pencil"></span> Message ' + escape(profile.pen_name) + u'</a>')
Update to display notes count bubble only when new notes are available
Update to display notes count bubble only when new notes are available
Python
agpl-3.0
ficlatte/main,HSAR/Ficlatte,stitzelj/Ficlatte,ficlatte/main,HSAR/Ficlatte,stitzelj/Ficlatte
--- +++ @@ -10,20 +10,23 @@ #----------------------------------------------------------------------------- @register.filter def note_link(note): - if note is None: - return u'<NULL NOTE>' - if note.read_date is None: - return mark_safe(u'<b><a href="/notes/view/' + unicode(note.id) + u'" class="note-link">' + escape(note.subject) + u'</a></b>') - else: - return mark_safe(u'<a href="/notes/view/' + unicode(note.id) + u'" class="note-link">' + escape(note.subject) + u'</a>') + if note is None: + return u'<NULL NOTE>' + if note.read_date is None: + return mark_safe(u'<b><a href="/notes/view/' + unicode(note.id) + u'" class="note-link">' + escape(note.subject) + u'</a></b>') + else: + return mark_safe(u'<a href="/notes/view/' + unicode(note.id) + u'" class="note-link">' + escape(note.subject) + u'</a>') #----------------------------------------------------------------------------- @register.filter def inbox_count(profile): - count = Note.objects.filter(recipient=profile, read_date__isnull=True, recipient_deleted_date__isnull=True).count() - return mark_safe(u'<span class="inbox-count">' + escape(count) + u'</span>') + count = Note.objects.filter(recipient=profile, read_date__isnull=True, recipient_deleted_date__isnull=True).count() + if count > 0: + return mark_safe(u'<span class="inbox-count">' + escape(count) + u'</span>') + else: + return mark_safe(u'<span>' + escape(count) + u'</span>') #----------------------------------------------------------------------------- @register.filter def author_msg(profile): - return mark_safe(u'<a class="btn btn-success author-msg-btn" href="/notes/compose?recipient=' + escape(profile.pen_name) + u'" type="button"><span class="glyphicon glyphicon-pencil"></span> Message ' + escape(profile.pen_name) + u'</a>') + return mark_safe(u'<a class="btn btn-success author-msg-btn" href="/notes/compose?recipient=' + escape(profile.pen_name) + u'" type="button"><span class="glyphicon glyphicon-pencil"></span> Message ' + escape(profile.pen_name) + u'</a>')
6d333d74d75c346c922dc65d8e311b4d976a9dd6
tests/test_NistRandomnessBeacon.py
tests/test_NistRandomnessBeacon.py
from unittest import TestCase from unittest.mock import ( Mock, patch, ) import requests.exceptions from py_nist_beacon import NistRandomnessBeacon from py_nist_beacon.nist_randomness_beacon_value import ( NistRandomnessBeaconValue ) class TestNistRandomnessBeacon(TestCase): def test_get_last_record(self): last_record = NistRandomnessBeacon.get_last_record() self.assertIsInstance(last_record, NistRandomnessBeaconValue) def test_get_last_record_404(self): with patch('requests.get') as patched_requests: mock_response = Mock() mock_response.status_code = 404 patched_requests.return_value = mock_response self.assertIsNone(NistRandomnessBeacon.get_last_record()) def test_get_last_record_exceptions(self): with patch('requests.get') as patched_requests: exceptions_to_test = [ requests.exceptions.RequestException(), requests.exceptions.ConnectionError(), requests.exceptions.HTTPError(), requests.exceptions.URLRequired(), requests.exceptions.TooManyRedirects(), requests.exceptions.Timeout(), ] for exception_test in exceptions_to_test: patched_requests.side_effect = exception_test self.assertIsNone(NistRandomnessBeacon.get_last_record())
Test that get last record method
Test that get last record method
Python
apache-2.0
urda/nistbeacon
--- +++ @@ -0,0 +1,43 @@ +from unittest import TestCase +from unittest.mock import ( + Mock, + patch, +) + +import requests.exceptions + +from py_nist_beacon import NistRandomnessBeacon +from py_nist_beacon.nist_randomness_beacon_value import ( + NistRandomnessBeaconValue +) + + +class TestNistRandomnessBeacon(TestCase): + def test_get_last_record(self): + last_record = NistRandomnessBeacon.get_last_record() + + self.assertIsInstance(last_record, NistRandomnessBeaconValue) + + def test_get_last_record_404(self): + with patch('requests.get') as patched_requests: + mock_response = Mock() + mock_response.status_code = 404 + patched_requests.return_value = mock_response + + self.assertIsNone(NistRandomnessBeacon.get_last_record()) + + def test_get_last_record_exceptions(self): + with patch('requests.get') as patched_requests: + + exceptions_to_test = [ + requests.exceptions.RequestException(), + requests.exceptions.ConnectionError(), + requests.exceptions.HTTPError(), + requests.exceptions.URLRequired(), + requests.exceptions.TooManyRedirects(), + requests.exceptions.Timeout(), + ] + + for exception_test in exceptions_to_test: + patched_requests.side_effect = exception_test + self.assertIsNone(NistRandomnessBeacon.get_last_record())
c4880ef0350d7cf58d9dff344f98f3b3096f2613
this_app/models.py
this_app/models.py
from werkzeug.security import generate_password_hash, check_password_hash class User(object): """represents a user who can CRUD his own bucketlists""" users = {} def __init__(self, email, username, password): """Constructor class to initialize class""" self.email = email self.username = username self.password = generate_password_hash(password) def create_user(self): """ Class to create and store a user object """ self.users.update({ self.email: { 'email': self.email, 'username': self.username, 'password': self.password } }) return self.users
from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash class User(UserMixin): """Represents a user who can Create, Read, Update & Delete his own bucketlists""" counter = 0 users = {} def __init__(self, email, username, password): """Constructor class to initialize class""" self.email = email self.username = username self.password = password User.counter += 1 def create_user(self): """ Class to create and store a user object """ self.users.update({ self.counter: { 'email': self.email, 'username': self.username, 'password': self.password } }) return self.users def is_active(self): """True, as all users are active.""" return True def get_id(self): """Return the email address to satisfy Flask-Login's requirements.""" return self.email def is_authenticated(self): """Return True if the user is authenticated.""" return True def is_anonymous(self): """False, as anonymous users aren't supported.""" return False
Update User model class with flask-login methods
Update User model class with flask-login methods
Python
mit
borenho/flask-bucketlist,borenho/flask-bucketlist
--- +++ @@ -1,8 +1,10 @@ +from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash -class User(object): - """represents a user who can CRUD his own bucketlists""" +class User(UserMixin): + """Represents a user who can Create, Read, Update & Delete his own bucketlists""" + counter = 0 users = {} def __init__(self, email, username, password): @@ -10,14 +12,15 @@ self.email = email self.username = username - self.password = generate_password_hash(password) + self.password = password + User.counter += 1 def create_user(self): """ Class to create and store a user object """ self.users.update({ - self.email: { + self.counter: { 'email': self.email, 'username': self.username, 'password': self.password @@ -25,3 +28,19 @@ }) return self.users + + def is_active(self): + """True, as all users are active.""" + return True + + def get_id(self): + """Return the email address to satisfy Flask-Login's requirements.""" + return self.email + + def is_authenticated(self): + """Return True if the user is authenticated.""" + return True + + def is_anonymous(self): + """False, as anonymous users aren't supported.""" + return False
1c07b3b29c18147578c94a21abf6c34647a7185d
tests/test_parse.py
tests/test_parse.py
import pytest from skidl import * from .setup_teardown import * def test_parser_1(): netlist_to_skidl(r'C:\xesscorp\KiCad\tools\skidl\tests\Arduino_Uno_R3_From_Scratch.net')
import pytest from skidl import * from .setup_teardown import * def test_parser_1(): netlist_to_skidl(get_filename('Arduino_Uno_R3_From_Scratch.net'))
Fix remaining absolute path in tests
Fix remaining absolute path in tests
Python
mit
xesscorp/skidl,xesscorp/skidl
--- +++ @@ -3,4 +3,4 @@ from .setup_teardown import * def test_parser_1(): - netlist_to_skidl(r'C:\xesscorp\KiCad\tools\skidl\tests\Arduino_Uno_R3_From_Scratch.net') + netlist_to_skidl(get_filename('Arduino_Uno_R3_From_Scratch.net'))
8cfbbe13d9a2c94529e2d2c06a8e154d9892c8c4
numpy/distutils/fcompiler/nag.py
numpy/distutils/fcompiler/nag.py
import os import sys from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler class NAGFCompiler(FCompiler): compiler_type = 'nag' version_pattern = r'NAGWare Fortran 95 compiler Release (?P<version>[^\s]*)' executables = { 'version_cmd' : ["f95", "-V"], 'compiler_f77' : ["f95", "-fixed"], 'compiler_fix' : ["f95", "-fixed"], 'compiler_f90' : ["f95"], 'linker_so' : ["f95"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } def get_flags_linker_so(self): if sys.platform=='darwin': return ['-unsharedf95','-Wl,-bundle,-flat_namespace,-undefined,suppress'] return ["-Wl,shared"] def get_flags_opt(self): return ['-O4'] def get_flags_arch(self): return ['-target=native'] def get_flags_debug(self): return ['-g','-gline','-g90','-nan','-C'] if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils.fcompiler import new_fcompiler compiler = new_fcompiler(compiler='nag') compiler.customize() print compiler.get_version()
import os import sys from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler class NAGFCompiler(FCompiler): compiler_type = 'nag' version_pattern = r'NAGWare Fortran 95 compiler Release (?P<version>[^\s]*)' executables = { 'version_cmd' : ["f95", "-V"], 'compiler_f77' : ["f95", "-fixed"], 'compiler_fix' : ["f95", "-fixed"], 'compiler_f90' : ["f95"], 'linker_so' : ["f95"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } def get_flags_linker_so(self): if sys.platform=='darwin': return ['-unsharedf95','-Wl,-bundle,-flat_namespace,-undefined,suppress'] return ["-Wl,-shared"] def get_flags_opt(self): return ['-O4'] def get_flags_arch(self): return ['-target=native'] def get_flags_debug(self): return ['-g','-gline','-g90','-nan','-C'] if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils.fcompiler import new_fcompiler compiler = new_fcompiler(compiler='nag') compiler.customize() print compiler.get_version()
Fix for using NAG Fortran 95, due to James Graham <jg307@cam.ac.uk>
Fix for using NAG Fortran 95, due to James Graham <jg307@cam.ac.uk>
Python
bsd-3-clause
mingwpy/numpy,rmcgibbo/numpy,jakirkham/numpy,githubmlai/numpy,BabeNovelty/numpy,pizzathief/numpy,ogrisel/numpy,astrofrog/numpy,andsor/numpy,cowlicks/numpy,rhythmsosad/numpy,simongibbons/numpy,felipebetancur/numpy,stefanv/numpy,GrimDerp/numpy,CMartelLML/numpy,githubmlai/numpy,pyparallel/numpy,madphysicist/numpy,Dapid/numpy,ewmoore/numpy,SiccarPoint/numpy,njase/numpy,ContinuumIO/numpy,ddasilva/numpy,kirillzhuravlev/numpy,ekalosak/numpy,pdebuyl/numpy,rgommers/numpy,dato-code/numpy,WarrenWeckesser/numpy,stefanv/numpy,mingwpy/numpy,AustereCuriosity/numpy,ChanderG/numpy,Eric89GXL/numpy,ChanderG/numpy,kirillzhuravlev/numpy,ajdawson/numpy,groutr/numpy,numpy/numpy,tacaswell/numpy,larsmans/numpy,NextThought/pypy-numpy,charris/numpy,chatcannon/numpy,tdsmith/numpy,GaZ3ll3/numpy,chiffa/numpy,b-carter/numpy,immerrr/numpy,mhvk/numpy,shoyer/numpy,bringingheavendown/numpy,SunghanKim/numpy,AustereCuriosity/numpy,endolith/numpy,kiwifb/numpy,KaelChen/numpy,SunghanKim/numpy,jonathanunderwood/numpy,nguyentu1602/numpy,trankmichael/numpy,stuarteberg/numpy,chatcannon/numpy,simongibbons/numpy,ESSS/numpy,nbeaver/numpy,brandon-rhodes/numpy,GrimDerp/numpy,madphysicist/numpy,joferkington/numpy,ajdawson/numpy,mathdd/numpy,skymanaditya1/numpy,ChanderG/numpy,anntzer/numpy,SunghanKim/numpy,Eric89GXL/numpy,Linkid/numpy,naritta/numpy,MichaelAquilina/numpy,jankoslavic/numpy,BabeNovelty/numpy,skymanaditya1/numpy,behzadnouri/numpy,immerrr/numpy,pizzathief/numpy,tacaswell/numpy,tdsmith/numpy,trankmichael/numpy,WarrenWeckesser/numpy,nguyentu1602/numpy,pelson/numpy,larsmans/numpy,stuarteberg/numpy,Linkid/numpy,felipebetancur/numpy,shoyer/numpy,rhythmsosad/numpy,mathdd/numpy,bertrand-l/numpy,has2k1/numpy,rajathkumarmp/numpy,githubmlai/numpy,ssanderson/numpy,moreati/numpy,felipebetancur/numpy,Dapid/numpy,mattip/numpy,CMartelLML/numpy,sigma-random/numpy,rgommers/numpy,jschueller/numpy,musically-ut/numpy,Srisai85/numpy,gfyoung/numpy,ewmoore/numpy,nguyentu1602/numpy,jankoslavic/numpy,WillieMaddox/numpy,Yusa95/numpy,brandon-rhodes/numpy,MaPePeR/numpy,GrimDerp/numpy,jschueller/numpy,ChristopherHogan/numpy,hainm/numpy,Anwesh43/numpy,MichaelAquilina/numpy,seberg/numpy,cowlicks/numpy,rmcgibbo/numpy,seberg/numpy,ogrisel/numpy,MichaelAquilina/numpy,BabeNovelty/numpy,has2k1/numpy,Eric89GXL/numpy,rajathkumarmp/numpy,BMJHayward/numpy,dwillmer/numpy,sigma-random/numpy,ogrisel/numpy,Linkid/numpy,pbrod/numpy,yiakwy/numpy,pbrod/numpy,naritta/numpy,stuarteberg/numpy,trankmichael/numpy,GaZ3ll3/numpy,cowlicks/numpy,maniteja123/numpy,Yusa95/numpy,dimasad/numpy,mindw/numpy,tdsmith/numpy,jakirkham/numpy,SiccarPoint/numpy,cjermain/numpy,sonnyhu/numpy,matthew-brett/numpy,dimasad/numpy,jakirkham/numpy,musically-ut/numpy,Eric89GXL/numpy,drasmuss/numpy,jankoslavic/numpy,simongibbons/numpy,bertrand-l/numpy,NextThought/pypy-numpy,BMJHayward/numpy,bmorris3/numpy,pdebuyl/numpy,argriffing/numpy,chiffa/numpy,leifdenby/numpy,KaelChen/numpy,dch312/numpy,mindw/numpy,endolith/numpy,rudimeier/numpy,immerrr/numpy,ekalosak/numpy,numpy/numpy-refactor,ContinuumIO/numpy,jorisvandenbossche/numpy,utke1/numpy,seberg/numpy,empeeu/numpy,madphysicist/numpy,githubmlai/numpy,pelson/numpy,WillieMaddox/numpy,WarrenWeckesser/numpy,dwf/numpy,naritta/numpy,simongibbons/numpy,mattip/numpy,charris/numpy,mattip/numpy,mathdd/numpy,MaPePeR/numpy,nguyentu1602/numpy,simongibbons/numpy,dato-code/numpy,rgommers/numpy,utke1/numpy,matthew-brett/numpy,embray/numpy,skymanaditya1/numpy,SunghanKim/numpy,argriffing/numpy,empeeu/numpy,seberg/numpy,pelson/numpy,larsmans/numpy,jorisvandenbossche/numpy,bmorris3/numpy,andsor/numpy,leifdenby/numpy,dwf/numpy,trankmichael/numpy,pyparallel/numpy,ahaldane/numpy,embray/numpy,kiwifb/numpy,mindw/numpy,Anwesh43/numpy,behzadnouri/numpy,numpy/numpy-refactor,numpy/numpy-refactor,jankoslavic/numpy,dwf/numpy,Linkid/numpy,ChristopherHogan/numpy,matthew-brett/numpy,ajdawson/numpy,CMartelLML/numpy,tynn/numpy,andsor/numpy,hainm/numpy,ahaldane/numpy,sinhrks/numpy,mortada/numpy,gfyoung/numpy,groutr/numpy,dch312/numpy,mortada/numpy,KaelChen/numpy,astrofrog/numpy,stefanv/numpy,grlee77/numpy,madphysicist/numpy,ViralLeadership/numpy,bmorris3/numpy,maniteja123/numpy,gmcastil/numpy,bringingheavendown/numpy,drasmuss/numpy,mhvk/numpy,Srisai85/numpy,ddasilva/numpy,GaZ3ll3/numpy,hainm/numpy,ahaldane/numpy,mattip/numpy,numpy/numpy,empeeu/numpy,KaelChen/numpy,rherault-insa/numpy,NextThought/pypy-numpy,dato-code/numpy,endolith/numpy,ContinuumIO/numpy,andsor/numpy,ajdawson/numpy,endolith/numpy,cjermain/numpy,ViralLeadership/numpy,sinhrks/numpy,rajathkumarmp/numpy,stuarteberg/numpy,tynn/numpy,ewmoore/numpy,jakirkham/numpy,pizzathief/numpy,solarjoe/numpy,skwbc/numpy,mingwpy/numpy,rgommers/numpy,ewmoore/numpy,astrofrog/numpy,jorisvandenbossche/numpy,rudimeier/numpy,jschueller/numpy,GrimDerp/numpy,rhythmsosad/numpy,pelson/numpy,ekalosak/numpy,GaZ3ll3/numpy,ewmoore/numpy,tacaswell/numpy,sinhrks/numpy,charris/numpy,gmcastil/numpy,bringingheavendown/numpy,pbrod/numpy,has2k1/numpy,Srisai85/numpy,MSeifert04/numpy,SiccarPoint/numpy,embray/numpy,dwf/numpy,chiffa/numpy,abalkin/numpy,ViralLeadership/numpy,numpy/numpy-refactor,behzadnouri/numpy,mwiebe/numpy,pdebuyl/numpy,rhythmsosad/numpy,dch312/numpy,dwf/numpy,shoyer/numpy,empeeu/numpy,tynn/numpy,ahaldane/numpy,kirillzhuravlev/numpy,abalkin/numpy,solarjoe/numpy,MSeifert04/numpy,jonathanunderwood/numpy,sigma-random/numpy,musically-ut/numpy,Anwesh43/numpy,cjermain/numpy,ESSS/numpy,mathdd/numpy,ChanderG/numpy,argriffing/numpy,b-carter/numpy,numpy/numpy,chatcannon/numpy,b-carter/numpy,sonnyhu/numpy,pdebuyl/numpy,rherault-insa/numpy,mortada/numpy,NextThought/pypy-numpy,rherault-insa/numpy,pizzathief/numpy,MaPePeR/numpy,ssanderson/numpy,anntzer/numpy,ChristopherHogan/numpy,pelson/numpy,brandon-rhodes/numpy,pyparallel/numpy,kirillzhuravlev/numpy,SiccarPoint/numpy,grlee77/numpy,ogrisel/numpy,naritta/numpy,drasmuss/numpy,matthew-brett/numpy,WillieMaddox/numpy,yiakwy/numpy,leifdenby/numpy,joferkington/numpy,ekalosak/numpy,yiakwy/numpy,nbeaver/numpy,immerrr/numpy,mhvk/numpy,sigma-random/numpy,brandon-rhodes/numpy,charris/numpy,skymanaditya1/numpy,MSeifert04/numpy,dwillmer/numpy,jorisvandenbossche/numpy,yiakwy/numpy,dwillmer/numpy,pbrod/numpy,WarrenWeckesser/numpy,abalkin/numpy,bertrand-l/numpy,felipebetancur/numpy,Srisai85/numpy,stefanv/numpy,ddasilva/numpy,WarrenWeckesser/numpy,njase/numpy,utke1/numpy,solarjoe/numpy,njase/numpy,mortada/numpy,BMJHayward/numpy,anntzer/numpy,embray/numpy,kiwifb/numpy,rmcgibbo/numpy,AustereCuriosity/numpy,CMartelLML/numpy,moreati/numpy,Yusa95/numpy,grlee77/numpy,mindw/numpy,mingwpy/numpy,dimasad/numpy,astrofrog/numpy,joferkington/numpy,BMJHayward/numpy,bmorris3/numpy,ogrisel/numpy,jakirkham/numpy,jschueller/numpy,MSeifert04/numpy,grlee77/numpy,rajathkumarmp/numpy,hainm/numpy,sinhrks/numpy,mwiebe/numpy,musically-ut/numpy,grlee77/numpy,shoyer/numpy,ahaldane/numpy,ChristopherHogan/numpy,joferkington/numpy,shoyer/numpy,pbrod/numpy,dwillmer/numpy,sonnyhu/numpy,dch312/numpy,BabeNovelty/numpy,sonnyhu/numpy,Yusa95/numpy,groutr/numpy,gmcastil/numpy,jonathanunderwood/numpy,skwbc/numpy,ssanderson/numpy,Anwesh43/numpy,skwbc/numpy,rudimeier/numpy,ESSS/numpy,numpy/numpy-refactor,stefanv/numpy,mhvk/numpy,dimasad/numpy,gfyoung/numpy,mhvk/numpy,MaPePeR/numpy,pizzathief/numpy,Dapid/numpy,numpy/numpy,jorisvandenbossche/numpy,tdsmith/numpy,MSeifert04/numpy,cowlicks/numpy,cjermain/numpy,larsmans/numpy,astrofrog/numpy,mwiebe/numpy,embray/numpy,dato-code/numpy,anntzer/numpy,rudimeier/numpy,nbeaver/numpy,madphysicist/numpy,matthew-brett/numpy,moreati/numpy,maniteja123/numpy,rmcgibbo/numpy,has2k1/numpy,MichaelAquilina/numpy
--- +++ @@ -22,7 +22,7 @@ def get_flags_linker_so(self): if sys.platform=='darwin': return ['-unsharedf95','-Wl,-bundle,-flat_namespace,-undefined,suppress'] - return ["-Wl,shared"] + return ["-Wl,-shared"] def get_flags_opt(self): return ['-O4'] def get_flags_arch(self):
192c7b01a34c3b9200005744790b63bcd7a7333c
pytablereader/loadermanager/_base.py
pytablereader/loadermanager/_base.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from ..interface import TableLoaderInterface class TableLoaderManager(TableLoaderInterface): def __init__(self, loader): self.__loader = loader @property def format_name(self): return self.__loader.format_name @property def source_type(self): return self.__loader.source_type @property def encoding(self): try: return self.__loader.encoding except AttributeError: return None def load(self): return self.__loader.load() def inc_table_count(self): self.__loader.inc_table_count()
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from ..interface import TableLoaderInterface class TableLoaderManager(TableLoaderInterface): def __init__(self, loader): self.__loader = loader @property def format_name(self): return self.__loader.format_name @property def source_type(self): return self.__loader.source_type @property def encoding(self): try: return self.__loader.encoding except AttributeError: return None @encoding.setter def encoding(self, codec_name): self.__loader.encoding = codec_name def load(self): return self.__loader.load() def inc_table_count(self): self.__loader.inc_table_count()
Add an interface to change loading encoding for File/URL loaders
Add an interface to change loading encoding for File/URL loaders
Python
mit
thombashi/pytablereader,thombashi/pytablereader,thombashi/pytablereader
--- +++ @@ -29,6 +29,10 @@ except AttributeError: return None + @encoding.setter + def encoding(self, codec_name): + self.__loader.encoding = codec_name + def load(self): return self.__loader.load()
8b916c0d4b45427f4820bb63fcccc085375c405a
jsplot/plot.py
jsplot/plot.py
data = [] def plot(x, y, label=None): d = { "data": zip(x, y), } if label: d["label"] = label data.append(d) def show(): from plotserver.runserver import main main() def grid(*args, **kwargs): pass def legend(*args, **kwargs): pass
data = [] def plot(x, y, format=None, label=None, lw=None): d = { "data": zip(x, y), } if label: d["label"] = label data.append(d) def show(): from plotserver.runserver import main main() def grid(*args, **kwargs): pass def legend(*args, **kwargs): pass
Add format and lw kwargs
Add format and lw kwargs
Python
mit
certik/jsplot,certik/jsplot
--- +++ @@ -1,6 +1,6 @@ data = [] -def plot(x, y, label=None): +def plot(x, y, format=None, label=None, lw=None): d = { "data": zip(x, y), }
478eb4908874167c472eed120d7ba49c737114e9
kokekunster/urls.py
kokekunster/urls.py
"""kokekunster URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from semesterpage.views import semester urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^(\w{3,6})/semester/([1-10])/$', semester), ]
"""kokekunster URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from semesterpage.views import semester urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^(\w{3,6})/semester/([1-9]|10)/$', semester), ]
Fix semester url regex bug
Fix semester url regex bug
Python
mit
afriestad/WikiLinks,afriestad/WikiLinks,afriestad/WikiLinks
--- +++ @@ -19,5 +19,5 @@ urlpatterns = [ url(r'^admin/', include(admin.site.urls)), - url(r'^(\w{3,6})/semester/([1-10])/$', semester), + url(r'^(\w{3,6})/semester/([1-9]|10)/$', semester), ]
85db14b8584995da667c92cda6a44e2b3395250e
greenlight/views/__init__.py
greenlight/views/__init__.py
from three import Three from django.core.urlresolvers import reverse from django.http import Http404 from .base import APIView QC_three = Three( endpoint = "http://dev-api.ville.quebec.qc.ca/open311/v2/", format = "json", jurisdiction = "ville.quebec.qc.ca", ) class ServicesView(APIView): def get(self, request): return self.OkAPIResponse(QC_three.services()) class RequestsView(APIView): def get(self, request): return self.OkAPIResponse(QC_three.requests()) def post(self, request): open311_response = QC_three.post(**request.POST)[0] if open311_response.get('code') == 'BadRequest': return self.ErrorAPIResponse(open311_response) request_id = open311_response['service_request_id'] location = reverse('request', args = (request_id,)) response = self.OkAPIResponse({ 'id': request_id, 'location': location }) response['Location'] = location return response class RequestView(APIView): def get(self, request, id): requests = QC_three.request(id) if requests: return self.OkAPIResponse(requests[0]) else: raise Http404
from three import Three from django.core.urlresolvers import reverse from django.http import Http404 from .base import APIView QC_three = Three( endpoint = "http://dev-api.ville.quebec.qc.ca/open311/v2/", format = "json", jurisdiction = "ville.quebec.qc.ca", ) class ServicesView(APIView): def get(self, request): return self.OkAPIResponse(QC_three.services()) class RequestsView(APIView): def get(self, request): return self.OkAPIResponse(QC_three.requests()) def post(self, request): open311_response = QC_three.post(**request.POST)[0] if open311_response.get('code') == 'BadRequest': return self.ErrorAPIResponse((open311_response['code'], open311_response['description'])) request_id = open311_response['service_request_id'] location = reverse('request', args = (request_id,)) response = self.OkAPIResponse({ 'id': request_id, 'location': location }) response['Location'] = location return response class RequestView(APIView): def get(self, request, id): requests = QC_three.request(id) if requests: return self.OkAPIResponse(requests[0]) else: raise Http404
Fix a bug when the open311 API returns an error.
Fix a bug when the open311 API returns an error.
Python
mit
ironweb/lesfeuxverts-backend
--- +++ @@ -28,7 +28,7 @@ open311_response = QC_three.post(**request.POST)[0] if open311_response.get('code') == 'BadRequest': - return self.ErrorAPIResponse(open311_response) + return self.ErrorAPIResponse((open311_response['code'], open311_response['description'])) request_id = open311_response['service_request_id']