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
|
---|---|---|---|---|---|---|---|---|---|---|
0bb36aebdf0766c9244c6e317df89ddda86361b0 | polls/admin.py | polls/admin.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import Question, Choice, Answer
class ChoiceInline(admin.TabularInline):
model = Choice
class QuestionAdmin(admin.ModelAdmin):
inlines = [
ChoiceInline,
]
admin.site.register(Question, QuestionAdmin)
admin.site.register(Answer)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import Question, Choice, Answer
class ChoiceInline(admin.TabularInline):
model = Choice
def copy_question(modeladmin, request, queryset):
for orig in queryset:
q = Question(question_text="Kopie van "+orig.question_text)
q.save()
for orig_choice in orig.choice_set.all():
c = Choice(question=q, choice_text=orig_choice.choice_text)
c.save()
copy_question.short_description = "Kopieer stemmingen"
class QuestionAdmin(admin.ModelAdmin):
inlines = [
ChoiceInline,
]
actions = [copy_question]
admin.site.register(Question, QuestionAdmin)
admin.site.register(Answer)
| Allow Questions to be copied | Allow Questions to be copied
| Python | apache-2.0 | gerard-/votingapp,gerard-/votingapp | ---
+++
@@ -8,10 +8,21 @@
class ChoiceInline(admin.TabularInline):
model = Choice
+def copy_question(modeladmin, request, queryset):
+ for orig in queryset:
+ q = Question(question_text="Kopie van "+orig.question_text)
+ q.save()
+ for orig_choice in orig.choice_set.all():
+ c = Choice(question=q, choice_text=orig_choice.choice_text)
+ c.save()
+
+copy_question.short_description = "Kopieer stemmingen"
+
class QuestionAdmin(admin.ModelAdmin):
inlines = [
ChoiceInline,
]
+ actions = [copy_question]
admin.site.register(Question, QuestionAdmin)
admin.site.register(Answer) |
6ca27fba516ddc63ad6bae98b20e5f9a42b37451 | examples/plotting/file/image.py | examples/plotting/file/image.py |
import numpy as np
from bokeh.plotting import *
from bokeh.objects import Range1d
N = 1000
x = np.linspace(0, 10, N)
y = np.linspace(0, 10, N)
xx, yy = np.meshgrid(x, y)
d = np.sin(xx)*np.cos(yy)
output_file("image.html", title="image.py example")
image(
image=[d], x=[0], y=[0], dw=[10], dh=[10], palette=["Spectral-11"],
x_range=[0, 10], y_range=[0, 10],
tools="pan,wheel_zoom,box_zoom,reset,previewsave", name="image_example"
)
curplot().x_range = [5, 10]
show() # open a browser
|
import numpy as np
from bokeh.plotting import *
N = 1000
x = np.linspace(0, 10, N)
y = np.linspace(0, 10, N)
xx, yy = np.meshgrid(x, y)
d = np.sin(xx)*np.cos(yy)
output_file("image.html", title="image.py example")
image(
image=[d], x=[0], y=[0], dw=[10], dh=[10], palette=["Spectral-11"],
x_range=[0, 10], y_range=[0, 10],
tools="pan,wheel_zoom,box_zoom,reset,previewsave", name="image_example"
)
show() # open a browser
| Fix example and remove extraneous import. | Fix example and remove extraneous import.
| Python | bsd-3-clause | birdsarah/bokeh,srinathv/bokeh,justacec/bokeh,eteq/bokeh,saifrahmed/bokeh,eteq/bokeh,rothnic/bokeh,dennisobrien/bokeh,deeplook/bokeh,draperjames/bokeh,tacaswell/bokeh,daodaoliang/bokeh,abele/bokeh,abele/bokeh,phobson/bokeh,Karel-van-de-Plassche/bokeh,percyfal/bokeh,ericdill/bokeh,timsnyder/bokeh,CrazyGuo/bokeh,ptitjano/bokeh,quasiben/bokeh,rothnic/bokeh,ericmjl/bokeh,rs2/bokeh,philippjfr/bokeh,ericmjl/bokeh,rhiever/bokeh,stonebig/bokeh,timothydmorton/bokeh,rs2/bokeh,azjps/bokeh,roxyboy/bokeh,aiguofer/bokeh,justacec/bokeh,draperjames/bokeh,stuart-knock/bokeh,paultcochrane/bokeh,aiguofer/bokeh,birdsarah/bokeh,awanke/bokeh,ChristosChristofidis/bokeh,roxyboy/bokeh,laurent-george/bokeh,ahmadia/bokeh,saifrahmed/bokeh,birdsarah/bokeh,mutirri/bokeh,jplourenco/bokeh,htygithub/bokeh,laurent-george/bokeh,canavandl/bokeh,daodaoliang/bokeh,bokeh/bokeh,ahmadia/bokeh,schoolie/bokeh,schoolie/bokeh,evidation-health/bokeh,maxalbert/bokeh,dennisobrien/bokeh,ChristosChristofidis/bokeh,saifrahmed/bokeh,roxyboy/bokeh,muku42/bokeh,phobson/bokeh,jakirkham/bokeh,josherick/bokeh,ericmjl/bokeh,eteq/bokeh,ptitjano/bokeh,mutirri/bokeh,muku42/bokeh,timsnyder/bokeh,lukebarnard1/bokeh,DuCorey/bokeh,percyfal/bokeh,phobson/bokeh,laurent-george/bokeh,bokeh/bokeh,draperjames/bokeh,canavandl/bokeh,carlvlewis/bokeh,xguse/bokeh,carlvlewis/bokeh,mutirri/bokeh,DuCorey/bokeh,lukebarnard1/bokeh,muku42/bokeh,Karel-van-de-Plassche/bokeh,ptitjano/bokeh,tacaswell/bokeh,xguse/bokeh,akloster/bokeh,PythonCharmers/bokeh,aavanian/bokeh,roxyboy/bokeh,evidation-health/bokeh,alan-unravel/bokeh,mindriot101/bokeh,aavanian/bokeh,msarahan/bokeh,aiguofer/bokeh,bsipocz/bokeh,caseyclements/bokeh,percyfal/bokeh,tacaswell/bokeh,PythonCharmers/bokeh,ChristosChristofidis/bokeh,ChinaQuants/bokeh,timothydmorton/bokeh,mutirri/bokeh,ericdill/bokeh,timsnyder/bokeh,KasperPRasmussen/bokeh,matbra/bokeh,aavanian/bokeh,KasperPRasmussen/bokeh,satishgoda/bokeh,josherick/bokeh,srinathv/bokeh,ahmadia/bokeh,caseyclements/bokeh,draperjames/bokeh,stonebig/bokeh,clairetang6/bokeh,almarklein/bokeh,carlvlewis/bokeh,almarklein/bokeh,laurent-george/bokeh,satishgoda/bokeh,ericdill/bokeh,srinathv/bokeh,philippjfr/bokeh,deeplook/bokeh,msarahan/bokeh,timsnyder/bokeh,justacec/bokeh,rothnic/bokeh,aiguofer/bokeh,azjps/bokeh,DuCorey/bokeh,azjps/bokeh,PythonCharmers/bokeh,percyfal/bokeh,awanke/bokeh,bsipocz/bokeh,maxalbert/bokeh,almarklein/bokeh,dennisobrien/bokeh,bokeh/bokeh,DuCorey/bokeh,CrazyGuo/bokeh,matbra/bokeh,rs2/bokeh,josherick/bokeh,ericdill/bokeh,dennisobrien/bokeh,ChinaQuants/bokeh,clairetang6/bokeh,muku42/bokeh,stuart-knock/bokeh,Karel-van-de-Plassche/bokeh,bokeh/bokeh,khkaminska/bokeh,paultcochrane/bokeh,khkaminska/bokeh,xguse/bokeh,ChristosChristofidis/bokeh,jplourenco/bokeh,KasperPRasmussen/bokeh,ChinaQuants/bokeh,azjps/bokeh,abele/bokeh,msarahan/bokeh,maxalbert/bokeh,rs2/bokeh,alan-unravel/bokeh,awanke/bokeh,paultcochrane/bokeh,philippjfr/bokeh,timothydmorton/bokeh,htygithub/bokeh,quasiben/bokeh,rhiever/bokeh,evidation-health/bokeh,rhiever/bokeh,ericmjl/bokeh,msarahan/bokeh,timsnyder/bokeh,deeplook/bokeh,saifrahmed/bokeh,philippjfr/bokeh,xguse/bokeh,rhiever/bokeh,KasperPRasmussen/bokeh,tacaswell/bokeh,jplourenco/bokeh,phobson/bokeh,clairetang6/bokeh,ptitjano/bokeh,aavanian/bokeh,matbra/bokeh,Karel-van-de-Plassche/bokeh,bsipocz/bokeh,KasperPRasmussen/bokeh,Karel-van-de-Plassche/bokeh,ericmjl/bokeh,draperjames/bokeh,DuCorey/bokeh,justacec/bokeh,ChinaQuants/bokeh,eteq/bokeh,jakirkham/bokeh,PythonCharmers/bokeh,schoolie/bokeh,akloster/bokeh,htygithub/bokeh,lukebarnard1/bokeh,bsipocz/bokeh,schoolie/bokeh,azjps/bokeh,caseyclements/bokeh,akloster/bokeh,stuart-knock/bokeh,stuart-knock/bokeh,mindriot101/bokeh,CrazyGuo/bokeh,abele/bokeh,khkaminska/bokeh,maxalbert/bokeh,rs2/bokeh,CrazyGuo/bokeh,jakirkham/bokeh,bokeh/bokeh,khkaminska/bokeh,quasiben/bokeh,satishgoda/bokeh,clairetang6/bokeh,canavandl/bokeh,daodaoliang/bokeh,ahmadia/bokeh,gpfreitas/bokeh,josherick/bokeh,philippjfr/bokeh,phobson/bokeh,dennisobrien/bokeh,matbra/bokeh,satishgoda/bokeh,ptitjano/bokeh,akloster/bokeh,percyfal/bokeh,caseyclements/bokeh,htygithub/bokeh,canavandl/bokeh,carlvlewis/bokeh,paultcochrane/bokeh,mindriot101/bokeh,schoolie/bokeh,lukebarnard1/bokeh,gpfreitas/bokeh,gpfreitas/bokeh,alan-unravel/bokeh,evidation-health/bokeh,timothydmorton/bokeh,aavanian/bokeh,gpfreitas/bokeh,jakirkham/bokeh,awanke/bokeh,rothnic/bokeh,aiguofer/bokeh,stonebig/bokeh,jplourenco/bokeh,stonebig/bokeh,deeplook/bokeh,jakirkham/bokeh,alan-unravel/bokeh,mindriot101/bokeh,birdsarah/bokeh,srinathv/bokeh,daodaoliang/bokeh | ---
+++
@@ -1,7 +1,6 @@
import numpy as np
from bokeh.plotting import *
-from bokeh.objects import Range1d
N = 1000
@@ -18,6 +17,4 @@
tools="pan,wheel_zoom,box_zoom,reset,previewsave", name="image_example"
)
-curplot().x_range = [5, 10]
-
show() # open a browser |
ce846bf4eb3eb60c0e91a34d434ae5307e194c3a | axes/apps.py | axes/apps.py | from logging import getLogger
from pkg_resources import get_distribution
from django import apps
log = getLogger(__name__)
class AppConfig(apps.AppConfig):
name = "axes"
initialized = False
@classmethod
def initialize(cls):
"""
Initialize Axes logging and show version information.
This method is re-entrant and can be called multiple times.
It displays version information exactly once at application startup.
"""
if cls.initialized:
return
cls.initialized = True
# Only import settings, checks, and signals one time after Django has been initialized
from axes.conf import settings # noqa
from axes import checks, signals # noqa
# Skip startup log messages if Axes is not set to verbose
if settings.AXES_VERBOSE:
log.info("AXES: BEGIN LOG")
log.info(
"AXES: Using django-axes version %s",
get_distribution("django-axes").version,
)
if settings.AXES_ONLY_USER_FAILURES:
log.info("AXES: blocking by username only.")
elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP:
log.info("AXES: blocking by combination of username and IP.")
elif settings.AXES_LOCK_OUT_BY_USER_OR_IP:
log.info("AXES: blocking by username or IP.")
else:
log.info("AXES: blocking by IP only.")
def ready(self):
self.initialize()
| from logging import getLogger
from pkg_resources import get_distribution
from django import apps
log = getLogger(__name__)
class AppConfig(apps.AppConfig):
name = "axes"
initialized = False
@classmethod
def initialize(cls):
"""
Initialize Axes logging and show version information.
This method is re-entrant and can be called multiple times.
It displays version information exactly once at application startup.
"""
if cls.initialized:
return
cls.initialized = True
# Only import settings, checks, and signals one time after Django has been initialized
from axes.conf import settings # noqa
from axes import checks, signals # noqa
# Skip startup log messages if Axes is not set to verbose
if settings.AXES_VERBOSE:
log.info("AXES: BEGIN LOG")
log.info(
"AXES: Using django-axes version %s",
get_distribution("django-axes").version,
)
if settings.AXES_ONLY_USER_FAILURES:
log.info("AXES: blocking by username only.")
elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP:
log.info("AXES: blocking by combination of username and IP.")
elif settings.AXES_LOCK_OUT_BY_USER_OR_IP:
log.info("AXES: blocking by username or IP.")
else:
log.info("AXES: blocking by IP only.")
def ready(self):
self.initialize()
| Fix GitHub code editor whitespaces | Fix GitHub code editor whitespaces | Python | mit | jazzband/django-axes | ---
+++
@@ -22,7 +22,7 @@
if cls.initialized:
return
cls.initialized = True
-
+
# Only import settings, checks, and signals one time after Django has been initialized
from axes.conf import settings # noqa
from axes import checks, signals # noqa |
5d8b217659fdd4a7248a60b430a24fe909bca805 | test/test_acoustics.py | test/test_acoustics.py | import numpy as np
import pyfds as fds
def test_acoustic_material():
water = fds.AcousticMaterial(1500, 1000)
water.bulk_viscosity = 1e-3
water.shear_viscosity = 1e-3
assert np.isclose(water.absorption_coef, 7e-3 / 3)
| import numpy as np
import pyfds as fds
def test_acoustic_material():
water = fds.AcousticMaterial(1500, 1000)
water.bulk_viscosity = 1e-3
water.shear_viscosity = 1e-3
assert np.isclose(water.absorption_coef, 7e-3 / 3)
def test_acoustic1d_create_matrices():
fld = fds.Acoustic1D(t_delta=1, t_samples=1,
x_delta=1, x_samples=3,
material=fds.AcousticMaterial(700, 0.01, bulk_viscosity=1))
fld.create_matrices()
assert np.allclose(fld.a_p_v.toarray(), [[-4900, 4900, 0], [0, -4900, 4900], [0, 0, -4900]])
assert np.allclose(fld.a_v_p.toarray(), [[100, 0, 0], [-100, 100, 0], [0, -100, 100]])
assert np.allclose(fld.a_v_v.toarray(), [[-200, 100, 0], [100, -200, 100], [0, 100, -200]])
| Add test case for Acoustic1D.create_matrices(). | Add test case for Acoustic1D.create_matrices().
| Python | bsd-3-clause | emtpb/pyfds | ---
+++
@@ -7,3 +7,13 @@
water.bulk_viscosity = 1e-3
water.shear_viscosity = 1e-3
assert np.isclose(water.absorption_coef, 7e-3 / 3)
+
+
+def test_acoustic1d_create_matrices():
+ fld = fds.Acoustic1D(t_delta=1, t_samples=1,
+ x_delta=1, x_samples=3,
+ material=fds.AcousticMaterial(700, 0.01, bulk_viscosity=1))
+ fld.create_matrices()
+ assert np.allclose(fld.a_p_v.toarray(), [[-4900, 4900, 0], [0, -4900, 4900], [0, 0, -4900]])
+ assert np.allclose(fld.a_v_p.toarray(), [[100, 0, 0], [-100, 100, 0], [0, -100, 100]])
+ assert np.allclose(fld.a_v_v.toarray(), [[-200, 100, 0], [100, -200, 100], [0, 100, -200]]) |
ebd9949177db3e2db51b47b74254908e300edc13 | process_test.py | process_test.py | """
Copyright 2016 EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import argparse, time
from pycompss.api.task import task
from pycompss.api.parameter import *
#class process_test:
#
# def __init__(self):
# self.ready = True
@task(x = IN)
def main(x):
print time.time(), x
y = range(1)
#pt = process_test()
map(main, y)
| """
Copyright 2016 EMBL-European Bioinformatics Institute
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 pycompss.api.parameter import *
from pycompss.api.task import task
def main(x):
from pycompss.api.api import compss_wait_on
print "Main process:"
results = []
for i in x:
results.append(print_time(i))
results = compss_wait_on(results)
print results
@task(x = IN, returns = int)
def print_time(x):
import time
x = time.time()
return x
if __name__ == "__main__":
y = range(10)
main(y)
| Test script to work out the method for creating tasks | Test script to work out the method for creating tasks
| Python | apache-2.0 | Multiscale-Genomics/mg-process-fastq,Multiscale-Genomics/mg-process-fastq,Multiscale-Genomics/mg-process-fastq | ---
+++
@@ -14,20 +14,24 @@
limitations under the License.
"""
-import argparse, time
+from pycompss.api.parameter import *
from pycompss.api.task import task
-from pycompss.api.parameter import *
-#class process_test:
-#
-# def __init__(self):
-# self.ready = True
-
-@task(x = IN)
def main(x):
- print time.time(), x
+ from pycompss.api.api import compss_wait_on
+ print "Main process:"
+ results = []
+ for i in x:
+ results.append(print_time(i))
+ results = compss_wait_on(results)
+ print results
-y = range(1)
+@task(x = IN, returns = int)
+def print_time(x):
+ import time
+ x = time.time()
+ return x
-#pt = process_test()
-map(main, y)
+if __name__ == "__main__":
+ y = range(10)
+ main(y) |
8d55ea0cfbafc9f6dc1044ba27c3313c36ea73c6 | pombola/south_africa/templatetags/za_people_display.py | pombola/south_africa/templatetags/za_people_display.py | from django import template
register = template.Library()
NO_PLACE_ORGS = ('parliament', 'national-assembly', )
MEMBER_ORGS = ('parliament', 'national-assembly', )
@register.assignment_tag()
def should_display_place(organisation):
return organisation.slug not in NO_PLACE_ORGS
@register.assignment_tag()
def should_display_position(organisation, position_title):
should_display = True
if organisation.slug in MEMBER_ORGS and unicode(position_title) in (u'Member',):
should_display = False
if 'ncop' == organisation.slug and unicode(position_title) in (u'Delegate',):
should_display = False
return should_display
| from django import template
register = template.Library()
NO_PLACE_ORGS = ('parliament', 'national-assembly', )
MEMBER_ORGS = ('parliament', 'national-assembly', )
@register.assignment_tag()
def should_display_place(organisation):
if not organisation:
return True
return organisation.slug not in NO_PLACE_ORGS
@register.assignment_tag()
def should_display_position(organisation, position_title):
should_display = True
if organisation.slug in MEMBER_ORGS and unicode(position_title) in (u'Member',):
should_display = False
if 'ncop' == organisation.slug and unicode(position_title) in (u'Delegate',):
should_display = False
return should_display
| Fix display of people on constituency office page | [ZA] Fix display of people on constituency office page
This template tag was being called without an organisation, so in
production it was just silently failing, but in development it was
raising an exception.
This adds an extra check so that if there is no organisation then we
just short circuit and return `True`.
| Python | agpl-3.0 | mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola | ---
+++
@@ -8,6 +8,8 @@
@register.assignment_tag()
def should_display_place(organisation):
+ if not organisation:
+ return True
return organisation.slug not in NO_PLACE_ORGS
|
e44dc4d68845845f601803f31e10833a24cdb27c | prosite_app.py | prosite_app.py | #!/bin/env python3
# Prosite regular expressions matcher
# Copyright (c) 2014 Tomasz Truszkowski
# All rights reserved.
import prosite_matcher
if __name__ == '__main__':
print("\n Hi, this is Prosite Matcher! \n")
sequence = input("Sequence: ")
regex = input("Regular expression: ")
prositeMatcher = prosite_matcher.PrositeMatcher()
prositeMatcher.compile(regex)
matches, ranges = prositeMatcher.get_matches(sequence)
print("Found patterns: ", end="")
if (len(matches) > 0):
print(sequence[ 0 : ranges[0][0] ], end="")
for i in range(0, len(matches)):
print("\033[91m", end="")
print(sequence[ ranges[i][0] : ranges[i][1] ], end="")
print("\033[0m", end="")
if (i < len(matches) - 1):
print(sequence[ ranges[i][1] : ranges[i + 1][0] ], end="")
print(sequence[ ranges[len(ranges) - 1][1] : len(sequence)])
else:
print(sequence)
print("")
for elem in list(zip(matches, ranges)):
print(elem[0], end=" ")
print(elem[1])
print("")
| #!/bin/env python3
# Prosite regular expressions matcher
# Copyright (c) 2014 Tomasz Truszkowski
# All rights reserved.
import prosite_matcher
if __name__ == '__main__':
print("\n Hi, this is Prosite Matcher! \n")
sequence = input("Sequence: ")
regex = input("Regular expression: ")
if sequence != None and sequence != "" and regex != None and regex != "":
prositeMatcher = prosite_matcher.PrositeMatcher()
prositeMatcher.compile(regex)
matches, ranges = prositeMatcher.get_matches(sequence)
print("Found patterns: ", end="")
if (len(matches) > 0):
print(sequence[ 0 : ranges[0][0] ], end="")
for i in range(0, len(matches)):
print("\033[91m", end="")
print(sequence[ ranges[i][0] : ranges[i][1] ], end="")
print("\033[0m", end="")
if (i < len(matches) - 1):
print(sequence[ ranges[i][1] : ranges[i + 1][0] ], end="")
print(sequence[ ranges[len(ranges) - 1][1] : len(sequence)])
else:
print(sequence)
print("")
for elem in list(zip(matches, ranges)):
print(elem[0], end=" ")
print(elem[1])
print("")
else:
print("Sequence and regular expression can't be empty.") | Add check for empty sequence or regex. | Add check for empty sequence or regex.
| Python | mit | stack-overflow/py_finite_state | ---
+++
@@ -12,35 +12,41 @@
sequence = input("Sequence: ")
regex = input("Regular expression: ")
- prositeMatcher = prosite_matcher.PrositeMatcher()
- prositeMatcher.compile(regex)
- matches, ranges = prositeMatcher.get_matches(sequence)
+ if sequence != None and sequence != "" and regex != None and regex != "":
- print("Found patterns: ", end="")
+ prositeMatcher = prosite_matcher.PrositeMatcher()
+ prositeMatcher.compile(regex)
+ matches, ranges = prositeMatcher.get_matches(sequence)
- if (len(matches) > 0):
+ print("Found patterns: ", end="")
- print(sequence[ 0 : ranges[0][0] ], end="")
+ if (len(matches) > 0):
- for i in range(0, len(matches)):
+ print(sequence[ 0 : ranges[0][0] ], end="")
- print("\033[91m", end="")
- print(sequence[ ranges[i][0] : ranges[i][1] ], end="")
- print("\033[0m", end="")
+ for i in range(0, len(matches)):
- if (i < len(matches) - 1):
- print(sequence[ ranges[i][1] : ranges[i + 1][0] ], end="")
+ print("\033[91m", end="")
+ print(sequence[ ranges[i][0] : ranges[i][1] ], end="")
+ print("\033[0m", end="")
- print(sequence[ ranges[len(ranges) - 1][1] : len(sequence)])
+ if (i < len(matches) - 1):
+ print(sequence[ ranges[i][1] : ranges[i + 1][0] ], end="")
+
+ print(sequence[ ranges[len(ranges) - 1][1] : len(sequence)])
+
+ else:
+
+ print(sequence)
+
+ print("")
+
+ for elem in list(zip(matches, ranges)):
+ print(elem[0], end=" ")
+ print(elem[1])
+
+ print("")
else:
- print(sequence)
-
- print("")
-
- for elem in list(zip(matches, ranges)):
- print(elem[0], end=" ")
- print(elem[1])
-
- print("")
+ print("Sequence and regular expression can't be empty.") |
017aa00a7b1f7a4a8a95f9c41576d4595d4085af | src/python/SparkSQLTwitter.py | src/python/SparkSQLTwitter.py | # A simple demo for working with SparkSQL and Tweets
from pyspark import SparkContext, SparkConf
from pyspark.sql import HiveContext, Row, IntegerType
import json
import sys
if __name__ == "__main__":
inputFile = sys.argv[1]
conf = SparkConf().setAppName("SparkSQLTwitter")
sc = SparkContext()
hiveCtx = HiveContext(sc)
print "Loading tweets from " + inputFile
input = hiveCtx.jsonFile(inputFile)
input.registerTempTable("tweets")
topTweets = hiveCtx.sql("SELECT text, retweetCount FROM tweets ORDER BY retweetCount LIMIT 10")
print topTweets.collect()
topTweetText = topTweets.map(lambda row : row.text)
print topTweetText.collect()
# Make a happy person row
happyPeopleRDD = sc.parallelize([Row(name="holden", favouriteBeverage="coffee")])
happyPeopleSchemaRDD = hiveCtx.inferSchema(happyPeopleRDD)
happyPeopleSchemaRDD.registerTempTable("happy_people")
# Make a UDF to tell us how long some text is
hiveCtx.registerFunction("strLenPython", lambda x: len(x), IntegerType())
lengthSchemaRDD = hiveCtx.sql("SELECT strLenPython('text') FROM tweets LIMIT 10")
print lengthSchemaRDD.collect()
sc.stop()
| # A simple demo for working with SparkSQL and Tweets
from pyspark import SparkContext, SparkConf
from pyspark.sql import HiveContext, Row
from pyspark.sql.types import IntegerType
import json
import sys
if __name__ == "__main__":
inputFile = sys.argv[1]
conf = SparkConf().setAppName("SparkSQLTwitter")
sc = SparkContext()
hiveCtx = HiveContext(sc)
print "Loading tweets from " + inputFile
input = hiveCtx.jsonFile(inputFile)
input.registerTempTable("tweets")
topTweets = hiveCtx.sql("SELECT text, retweetCount FROM tweets ORDER BY retweetCount LIMIT 10")
print topTweets.collect()
topTweetText = topTweets.map(lambda row : row.text)
print topTweetText.collect()
# Make a happy person row
happyPeopleRDD = sc.parallelize([Row(name="holden", favouriteBeverage="coffee")])
happyPeopleSchemaRDD = hiveCtx.inferSchema(happyPeopleRDD)
happyPeopleSchemaRDD.registerTempTable("happy_people")
# Make a UDF to tell us how long some text is
hiveCtx.registerFunction("strLenPython", lambda x: len(x), IntegerType())
lengthSchemaRDD = hiveCtx.sql("SELECT strLenPython('text') FROM tweets LIMIT 10")
print lengthSchemaRDD.collect()
sc.stop()
| Fix IntegerType import for Spark SQL | Fix IntegerType import for Spark SQL
| Python | mit | DINESHKUMARMURUGAN/learning-spark,mohitsh/learning-spark,shimizust/learning-spark,JerryTseng/learning-spark,databricks/learning-spark,qingkaikong/learning-spark-examples,huixiang/learning-spark,qingkaikong/learning-spark-examples,obinsanni/learning-spark,bhagatsingh/learning-spark,holdenk/learning-spark-examples,NBSW/learning-spark,UsterNes/learning-spark,holdenk/learning-spark-examples,gaoxuesong/learning-spark,noprom/learning-spark,rex1100/learning-spark,kpraveen420/learning-spark,baokunguo/learning-spark-examples,gaoxuesong/learning-spark,shimizust/learning-spark,zaxliu/learning-spark,junwucs/learning-spark,holdenk/learning-spark-examples,noprom/learning-spark,negokaz/learning-spark,ellis429/learning-spark-examples,ellis429/learning-spark,mmirolim/learning-spark,asarraf/learning-spark,junwucs/learning-spark,jindalcastle/learning-spark,SunGuo/learning-spark,gaoxuesong/learning-spark,JerryTseng/learning-spark,bhagatsingh/learning-spark,XiaoqingWang/learning-spark,jaehyuk/learning-spark,huixiang/learning-spark,junwucs/learning-spark,asarraf/learning-spark,ellis429/learning-spark-examples,anjuncc/learning-spark-examples,concerned3rdparty/learning-spark,shimizust/learning-spark,JerryTseng/learning-spark,mmirolim/learning-spark,tengteng/learning-spark,JerryTseng/learning-spark,bhagatsingh/learning-spark,diogoaurelio/learning-spark,ellis429/learning-spark,DINESHKUMARMURUGAN/learning-spark,jaehyuk/learning-spark,anjuncc/learning-spark-examples,dsdinter/learning-spark-examples,jaehyuk/learning-spark,ramyasrigangula/learning-spark,diogoaurelio/learning-spark,holdenk/learning-spark-examples,DINESHKUMARMURUGAN/learning-spark,ellis429/learning-spark-examples,coursera4ashok/learning-spark,kod3r/learning-spark,ramyasrigangula/learning-spark,qingkaikong/learning-spark-examples,negokaz/learning-spark,XiaoqingWang/learning-spark,asarraf/learning-spark,mohitsh/learning-spark,ellis429/learning-spark-examples,anjuncc/learning-spark-examples,jindalcastle/learning-spark,obinsanni/learning-spark,UsterNes/learning-spark,diogoaurelio/learning-spark,jaehyuk/learning-spark,diogoaurelio/learning-spark,GatsbyNewton/learning-spark,ellis429/learning-spark,kod3r/learning-spark,baokunguo/learning-spark-examples,SunGuo/learning-spark,asarraf/learning-spark,ramyasrigangula/learning-spark,noprom/learning-spark,SunGuo/learning-spark,baokunguo/learning-spark-examples,UsterNes/learning-spark,coursera4ashok/learning-spark,kpraveen420/learning-spark,mohitsh/learning-spark,rex1100/learning-spark,jaehyuk/learning-spark,mmirolim/learning-spark,zaxliu/learning-spark,huixiang/learning-spark,mohitsh/learning-spark,NBSW/learning-spark,feynman0825/learning-spark,UsterNes/learning-spark,huydx/learning-spark,mmirolim/learning-spark,SunGuo/learning-spark,jindalcastle/learning-spark,obinsanni/learning-spark,bhagatsingh/learning-spark,dsdinter/learning-spark-examples,XiaoqingWang/learning-spark,concerned3rdparty/learning-spark,shimizust/learning-spark,dsdinter/learning-spark-examples,asarraf/learning-spark,ellis429/learning-spark,coursera4ashok/learning-spark,feynman0825/learning-spark,NBSW/learning-spark,concerned3rdparty/learning-spark,feynman0825/learning-spark,jindalcastle/learning-spark,XiaoqingWang/learning-spark,zaxliu/learning-spark,negokaz/learning-spark,kod3r/learning-spark,negokaz/learning-spark,obinsanni/learning-spark,NBSW/learning-spark,tengteng/learning-spark,qingkaikong/learning-spark-examples,DINESHKUMARMURUGAN/learning-spark,bhagatsingh/learning-spark,feynman0825/learning-spark,kpraveen420/learning-spark,holdenk/learning-spark-examples,huydx/learning-spark,XiaoqingWang/learning-spark,huydx/learning-spark,kod3r/learning-spark,JerryTseng/learning-spark,obinsanni/learning-spark,concerned3rdparty/learning-spark,junwucs/learning-spark,jindalcastle/learning-spark,huydx/learning-spark,concerned3rdparty/learning-spark,SunGuo/learning-spark,coursera4ashok/learning-spark,mmirolim/learning-spark,negokaz/learning-spark,ellis429/learning-spark-examples,GatsbyNewton/learning-spark,huydx/learning-spark,noprom/learning-spark,shimizust/learning-spark,tengteng/learning-spark,diogoaurelio/learning-spark,ellis429/learning-spark,tengteng/learning-spark,GatsbyNewton/learning-spark,NBSW/learning-spark,databricks/learning-spark,kpraveen420/learning-spark,databricks/learning-spark,qingkaikong/learning-spark-examples,anjuncc/learning-spark-examples,huixiang/learning-spark,dsdinter/learning-spark-examples,zaxliu/learning-spark,mohitsh/learning-spark,gaoxuesong/learning-spark,rex1100/learning-spark,databricks/learning-spark,GatsbyNewton/learning-spark,anjuncc/learning-spark-examples,kod3r/learning-spark,noprom/learning-spark,junwucs/learning-spark,kpraveen420/learning-spark,tengteng/learning-spark,databricks/learning-spark,coursera4ashok/learning-spark,feynman0825/learning-spark,huixiang/learning-spark,dsdinter/learning-spark-examples,baokunguo/learning-spark-examples,ramyasrigangula/learning-spark,baokunguo/learning-spark-examples,gaoxuesong/learning-spark,ramyasrigangula/learning-spark,UsterNes/learning-spark,GatsbyNewton/learning-spark,zaxliu/learning-spark,DINESHKUMARMURUGAN/learning-spark | ---
+++
@@ -1,6 +1,7 @@
# A simple demo for working with SparkSQL and Tweets
from pyspark import SparkContext, SparkConf
-from pyspark.sql import HiveContext, Row, IntegerType
+from pyspark.sql import HiveContext, Row
+from pyspark.sql.types import IntegerType
import json
import sys
|
4b172a9b2b9a9a70843bd41ad858d6f3120769b0 | tests/test_funcargs.py | tests/test_funcargs.py | from django.test.client import Client
from pytest_django.client import RequestFactory
pytest_plugins = ['pytester']
def test_params(testdir):
testdir.makeconftest("""
import os, sys
import pytest_django as plugin
sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(plugin.__file__), '../')))
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
pytest_plugins = ['django']
""")
p = testdir.makepyfile("""
import py
@py.test.params([dict(arg1=1, arg2=1), dict(arg1=1, arg2=2)])
def test_myfunc(arg1, arg2):
assert arg1 == arg2
""")
result = testdir.runpytest("-v", p)
assert result.stdout.fnmatch_lines([
"*test_myfunc*0*PASS*",
"*test_myfunc*1*FAIL*",
"*1 failed, 1 passed*"
])
def test_client(client):
assert isinstance(client, Client)
def test_rf(rf):
assert isinstance(rf, RequestFactory)
| from django.test.client import Client
from pytest_django.client import RequestFactory
import py
pytest_plugins = ['pytester']
def test_params(testdir):
# Setting up the path isn't working - plugin.__file__ points to the wrong place
return
testdir.makeconftest("""
import os, sys
import pytest_django as plugin
sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(plugin.__file__), '../')))
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
pytest_plugins = ['django']
""")
p = testdir.makepyfile("""
import py
@py.test.params([dict(arg1=1, arg2=1), dict(arg1=1, arg2=2)])
def test_myfunc(arg1, arg2):
assert arg1 == arg2
""")
result = testdir.runpytest("-v", p)
assert result.stdout.fnmatch_lines([
"*test_myfunc*0*PASS*",
"*test_myfunc*1*FAIL*",
"*1 failed, 1 passed*"
])
def test_client(client):
assert isinstance(client, Client)
def test_rf(rf):
assert isinstance(rf, RequestFactory)
| Disable params test for now | Disable params test for now
| Python | bsd-3-clause | ojake/pytest-django,pelme/pytest-django,hoh/pytest-django,thedrow/pytest-django,pombredanne/pytest_django,felixonmars/pytest-django,ktosiek/pytest-django,RonnyPfannschmidt/pytest_django,aptivate/pytest-django,davidszotten/pytest-django,reincubate/pytest-django,bforchhammer/pytest-django,tomviner/pytest-django,bfirsh/pytest_django | ---
+++
@@ -1,9 +1,13 @@
from django.test.client import Client
from pytest_django.client import RequestFactory
+import py
pytest_plugins = ['pytester']
def test_params(testdir):
+ # Setting up the path isn't working - plugin.__file__ points to the wrong place
+ return
+
testdir.makeconftest("""
import os, sys
import pytest_django as plugin |
849552b1a2afdd89552e7c0395fc7be1786d5cbc | pybossa/auth/user.py | pybossa/auth/user.py | # -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# PyBossa is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyBossa is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with PyBossa. If not, see <http://www.gnu.org/licenses/>.
from flask.ext.login import current_user
def create(user=None):
if current_user.is_authenticated():
if current_user.admin:
return True
else:
return False
else:
return False
def read(user=None):
return True
def update(user):
return create(user)
def delete(user):
return update(user)
| # -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# PyBossa is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyBossa is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with PyBossa. If not, see <http://www.gnu.org/licenses/>.
from flask.ext.login import current_user
def create(user=None): # pragma: no cover
if current_user.is_authenticated():
if current_user.admin:
return True
else:
return False
else:
return False
def read(user=None): # pragma: no cover
return True
def update(user): # pragma: no cover
return create(user)
def delete(user): # pragma: no cover
return update(user)
| Exclude it from coverage as these permissions are not used yet. | Exclude it from coverage as these permissions are not used yet.
| Python | agpl-3.0 | PyBossa/pybossa,PyBossa/pybossa,CulturePlex/pybossa,jean/pybossa,inteligencia-coletiva-lsd/pybossa,harihpr/tweetclickers,stefanhahmann/pybossa,stefanhahmann/pybossa,geotagx/pybossa,geotagx/pybossa,CulturePlex/pybossa,OpenNewsLabs/pybossa,proyectos-analizo-info/pybossa-analizo-info,proyectos-analizo-info/pybossa-analizo-info,Scifabric/pybossa,proyectos-analizo-info/pybossa-analizo-info,jean/pybossa,CulturePlex/pybossa,inteligencia-coletiva-lsd/pybossa,harihpr/tweetclickers,Scifabric/pybossa,OpenNewsLabs/pybossa | ---
+++
@@ -19,7 +19,7 @@
from flask.ext.login import current_user
-def create(user=None):
+def create(user=None): # pragma: no cover
if current_user.is_authenticated():
if current_user.admin:
return True
@@ -29,13 +29,13 @@
return False
-def read(user=None):
+def read(user=None): # pragma: no cover
return True
-def update(user):
+def update(user): # pragma: no cover
return create(user)
-def delete(user):
+def delete(user): # pragma: no cover
return update(user) |
5c9bdb1260562f0623807ce9a5751d33c806374a | pyfr/nputil.py | pyfr/nputil.py | # -*- coding: utf-8 -*-
import numpy as np
_npeval_syms = {'__builtins__': None,
'exp': np.exp, 'log': np.log,
'sin': np.sin, 'asin': np.arcsin,
'cos': np.cos, 'acos': np.arccos,
'tan': np.tan, 'atan': np.arctan, 'atan2': np.arctan2,
'abs': np.abs, 'pow': np.power, 'sqrt': np.sqrt,
'pi': np.pi}
def npeval(expr, locals):
# Allow '^' to be used for exponentiation
expr = expr.replace('^', '**')
return eval(expr, _npeval_syms, locals)
_range_eval_syms = {'__builtins__': None,
'range': lambda s,e,n: list(np.linspace(s, e, n))}
def range_eval(expr):
return [float(t) for t in eval(expr, _range_eval_syms, None)]
_ctype_map = {np.float32: 'float', np.float64: 'double'}
def npdtype_to_ctype(dtype):
return _ctype_map[np.dtype(dtype).type]
| # -*- coding: utf-8 -*-
import numpy as np
def npaligned(shape, dtype, alignb=32):
nbytes = np.prod(shape)*np.dtype(dtype).itemsize
buf = np.zeros(nbytes + alignb, dtype=np.uint8)
off = -buf.ctypes.data % alignb
return buf[off:nbytes + off].view(dtype).reshape(shape)
_npeval_syms = {'__builtins__': None,
'exp': np.exp, 'log': np.log,
'sin': np.sin, 'asin': np.arcsin,
'cos': np.cos, 'acos': np.arccos,
'tan': np.tan, 'atan': np.arctan, 'atan2': np.arctan2,
'abs': np.abs, 'pow': np.power, 'sqrt': np.sqrt,
'pi': np.pi}
def npeval(expr, locals):
# Allow '^' to be used for exponentiation
expr = expr.replace('^', '**')
return eval(expr, _npeval_syms, locals)
_range_eval_syms = {'__builtins__': None,
'range': lambda s,e,n: list(np.linspace(s, e, n))}
def range_eval(expr):
return [float(t) for t in eval(expr, _range_eval_syms, None)]
_ctype_map = {np.float32: 'float', np.float64: 'double'}
def npdtype_to_ctype(dtype):
return _ctype_map[np.dtype(dtype).type]
| Add support for allocating aligned NumPy arrays. | Add support for allocating aligned NumPy arrays.
| Python | bsd-3-clause | tjcorona/PyFR,tjcorona/PyFR,BrianVermeire/PyFR,Aerojspark/PyFR,iyer-arvind/PyFR,tjcorona/PyFR | ---
+++
@@ -1,6 +1,14 @@
# -*- coding: utf-8 -*-
import numpy as np
+
+
+def npaligned(shape, dtype, alignb=32):
+ nbytes = np.prod(shape)*np.dtype(dtype).itemsize
+ buf = np.zeros(nbytes + alignb, dtype=np.uint8)
+ off = -buf.ctypes.data % alignb
+
+ return buf[off:nbytes + off].view(dtype).reshape(shape)
_npeval_syms = {'__builtins__': None, |
b77d078d096bb18cb02b6da0f7f00da33859bd88 | byceps/util/templatefunctions.py | byceps/util/templatefunctions.py | """
byceps.util.templatefunctions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provide and register custom template global functions.
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
import babel
from flask_babel import get_locale, get_timezone
def register(app):
"""Make functions available as global functions in templates."""
functions = [
(_format_date, 'format_date'),
(_format_datetime, 'format_datetime'),
(_format_time, 'format_time'),
(_format_number, 'format_number'),
]
for f, name in functions:
app.add_template_global(f, name)
def _format_date(*args) -> str:
return babel.dates.format_date(*args, locale=get_locale())
def _format_datetime(*args) -> str:
return babel.dates.format_datetime(
*args, locale=get_locale(), tzinfo=get_timezone()
)
def _format_time(*args) -> str:
return babel.dates.format_time(
*args, locale=get_locale(), tzinfo=get_timezone()
)
def _format_number(*args) -> str:
return babel.numbers.format_number(*args, locale=get_locale())
| """
byceps.util.templatefunctions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provide and register custom template global functions.
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
import babel
from flask_babel import get_locale, get_timezone
def register(app):
"""Make functions available as global functions in templates."""
functions = [
(_format_date, 'format_date'),
(_format_datetime, 'format_datetime'),
(_format_time, 'format_time'),
(_format_number, 'format_number'),
]
for f, name in functions:
app.add_template_global(f, name)
def _format_date(*args) -> str:
return babel.dates.format_date(*args, locale=get_locale())
def _format_datetime(*args) -> str:
return babel.dates.format_datetime(
*args, locale=get_locale(), tzinfo=get_timezone()
)
def _format_time(*args) -> str:
return babel.dates.format_time(
*args, locale=get_locale(), tzinfo=get_timezone()
)
def _format_number(*args) -> str:
return babel.numbers.format_decimal(*args, locale=get_locale())
| Use Babel's `format_decimal` instead of deprecated `format_number` | Use Babel's `format_decimal` instead of deprecated `format_number`
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps | ---
+++
@@ -42,4 +42,4 @@
def _format_number(*args) -> str:
- return babel.numbers.format_number(*args, locale=get_locale())
+ return babel.numbers.format_decimal(*args, locale=get_locale()) |
126c58d78360e69c2d16a40f9396a8158844e2b1 | tests/test_creators.py | tests/test_creators.py | """
Test the post methods.
"""
def test_matrix_creation_endpoint(client):
response = client.post('/matrix', {
'bibliography': '12312312',
'fields': 'title,description',
})
print(response.json())
assert response.status_code == 200
| """
Test the post methods.
"""
from condor.models import Bibliography
def test_matrix_creation_endpoint(client, session):
bib = Bibliography(eid='123', description='lorem')
session.add(bib)
session.flush()
response = client.post('/matrix', {
'bibliography': '123',
'fields': 'title,description',
})
response = client.get(f"/matrix/{response.json().get('eid')}")
assert response.status_code == 200
assert response.json().get('bibliography_eid') == '123'
| Create test for matrix post endpoint | Create test for matrix post endpoint
| Python | mit | odarbelaeze/condor-api | ---
+++
@@ -1,12 +1,20 @@
"""
Test the post methods.
"""
+from condor.models import Bibliography
-def test_matrix_creation_endpoint(client):
+def test_matrix_creation_endpoint(client, session):
+ bib = Bibliography(eid='123', description='lorem')
+ session.add(bib)
+ session.flush()
+
response = client.post('/matrix', {
- 'bibliography': '12312312',
+ 'bibliography': '123',
'fields': 'title,description',
})
- print(response.json())
+
+ response = client.get(f"/matrix/{response.json().get('eid')}")
+
assert response.status_code == 200
+ assert response.json().get('bibliography_eid') == '123' |
e94d39bf330312dc46697a689b56f7518ebd501c | footer/magic/images.py | footer/magic/images.py | #import PIL
import cairosvg
from django.template import Template, Context
def make_svg(context):
svg_tmpl = Template("""
<svg xmlns="http://www.w3.org/2000/svg"
width="500" height="600" viewBox="0 0 500 400">
<text x="0" y="0" font-family="Verdana" font-size="10" fill="blue" dy="0">
{{ name }} {{ text }}
{% for k,v in data.items %}
{% if v.items %}
<tspan x="0" dy="1.0em">
{{ k }}:
</tspan>
{% for kk, vv in v.items %}
<tspan x="0" dy="1.0em">
{{ kk }}: {{ vv }}
</tspan>
{% endfor %}
{% else %}
<tspan x="0" dy="1.0em">
{{ k }}: {{ v }}
</tspan>
{% endif %}
{% endfor %}
</text>
</svg>
""".strip())
svg = svg_tmpl.render(Context({'data': context}))
return svg
def write_svg_to_png(svg_raw, outfile):
cairosvg.svg2png(bytestring=svg_raw, write_to=outfile)
return outfile
| #import PIL
import cairosvg
from django.template import Template, Context
def make_svg(context):
svg_tmpl = Template("""
<svg xmlns="http://www.w3.org/2000/svg"
width="500" height="600" viewBox="0 0 500 400">
<text x="0" y="0" font-family="Verdana" font-size="10" fill="blue" dy="0">
{{ name }} {{ text }}
{% for k,v in data.items %}
{% if v.items %}
<tspan x="0" dy="1.0em">
{{ k }}:
</tspan>
{% for kk, vv in v.items %}
<tspan x="0" dy="1.0em">
{{ kk }}: <tspan fill="red" dy="0.0em">{{ vv }}</tspan>
</tspan>
{% endfor %}
{% else %}
<tspan x="0" dy="1.0em">
{{ k }}: <tspan fill="red" dy="0.0em">{{ v }}</tspan>
</tspan>
{% endif %}
{% endfor %}
</text>
</svg>
""".strip())
svg = svg_tmpl.render(Context({'data': context}))
return svg
def write_svg_to_png(svg_raw, outfile):
cairosvg.svg2png(bytestring=svg_raw, write_to=outfile)
return outfile
| Add some color to SVG key/values | Add some color to SVG key/values
| Python | mit | mihow/footer,mihow/footer,mihow/footer,mihow/footer | ---
+++
@@ -19,12 +19,12 @@
</tspan>
{% for kk, vv in v.items %}
<tspan x="0" dy="1.0em">
- {{ kk }}: {{ vv }}
+ {{ kk }}: <tspan fill="red" dy="0.0em">{{ vv }}</tspan>
</tspan>
{% endfor %}
{% else %}
<tspan x="0" dy="1.0em">
- {{ k }}: {{ v }}
+ {{ k }}: <tspan fill="red" dy="0.0em">{{ v }}</tspan>
</tspan>
{% endif %}
{% endfor %} |
ebdafecea8c5b6597a7b2e2822afc98b9c47bb05 | toast/math/__init__.py | toast/math/__init__.py | def lerp(fromValue, toValue, step):
return fromValue + (toValue - fromValue) * step | def lerp(fromValue, toValue, percent):
return fromValue + (toValue - fromValue) * percent | Refactor to lerp param names. | Refactor to lerp param names.
| Python | mit | JoshuaSkelly/Toast,JSkelly/Toast | ---
+++
@@ -1,2 +1,2 @@
-def lerp(fromValue, toValue, step):
- return fromValue + (toValue - fromValue) * step
+def lerp(fromValue, toValue, percent):
+ return fromValue + (toValue - fromValue) * percent |
b2e743a19f13c898b2d95595a7a7175eca4bdb2c | results/urls.py | results/urls.py | __author__ = 'ankesh'
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^(?P<filename>[a-zA-Z0-9]+)/$', views.show_result, name='showResult'),
url(r'^compare/(?P<filename>[a-zA-Z0-9]+)/$', views.compare_result, name='compareResult'),
)
| __author__ = 'ankesh'
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^(?P<filename>[a-zA-Z0-9]+)/$', views.show_result, name='showResult'),
url(r'^compare/(?P<filename>[a-zA-Z0-9]+)/$', views.compare_result, name='compareResult'),
url(r'^recent/$', views.recent_results, name='recentResults'),
)
| Update URLs to include recent results | Update URLs to include recent results
| Python | bsd-2-clause | ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark | ---
+++
@@ -6,5 +6,6 @@
urlpatterns = patterns('',
url(r'^(?P<filename>[a-zA-Z0-9]+)/$', views.show_result, name='showResult'),
url(r'^compare/(?P<filename>[a-zA-Z0-9]+)/$', views.compare_result, name='compareResult'),
+ url(r'^recent/$', views.recent_results, name='recentResults'),
)
|
7e3dfe47598401f4d5b96a377927473bb8adc244 | bush/aws/base.py | bush/aws/base.py | from bush.aws.session import create_session
class AWSBase:
# USAGE = ""
# SUB_COMMANDS = []
def __init__(self, options, resource_name):
self.name = resource_name
self.options = options
self.session = create_session(options)
self.resource = self.session.resource(resource_name)
self.client = self.session.client(resource_name)
| from bush.aws.session import create_session
class AWSBase:
# USAGE = ""
# SUB_COMMANDS = []
def __init__(self, options, resource_name):
self.name = resource_name
self.options = options
self.session = create_session(options)
@property
def resource(self):
if not hasattr(self, '__resource'):
self.__set_resource()
return self.__resource
@property
def client(self):
if not hasattr(self, '__client'):
self.__set_client()
return self.__client
def __set_resource(self):
self.__resource = self.session.resource(self.name)
def __set_client(self):
self.__client = self.session.client(self.name)
| Set resource and client when it is needed | Set resource and client when it is needed
| Python | mit | okamos/bush | ---
+++
@@ -9,5 +9,21 @@
self.name = resource_name
self.options = options
self.session = create_session(options)
- self.resource = self.session.resource(resource_name)
- self.client = self.session.client(resource_name)
+
+ @property
+ def resource(self):
+ if not hasattr(self, '__resource'):
+ self.__set_resource()
+ return self.__resource
+
+ @property
+ def client(self):
+ if not hasattr(self, '__client'):
+ self.__set_client()
+ return self.__client
+
+ def __set_resource(self):
+ self.__resource = self.session.resource(self.name)
+
+ def __set_client(self):
+ self.__client = self.session.client(self.name) |
a014cd2184d4c9634c02d1cac9d1fd41fb3c6c37 | eduid_IdP_html/tests/test_translation.py | eduid_IdP_html/tests/test_translation.py | from unittest import TestCase
import eduid_IdP_html
__author__ = 'ft'
class TestLoad_settings(TestCase):
def test_load_settings(self):
settings = eduid_IdP_html.load_settings()
self.assertTrue(settings['gettext_domain'] is not None) | from unittest import TestCase
import eduid_IdP_html
__author__ = 'ft'
class TestLoad_settings(TestCase):
def test_load_settings(self):
settings = eduid_IdP_html.load_settings()
self.assertTrue(settings['gettext_domain'] is not None)
| Add newline at end of file. | Add newline at end of file.
| Python | bsd-3-clause | SUNET/eduid-IdP-html,SUNET/eduid-IdP-html,SUNET/eduid-IdP-html | |
2425f5a3b0b3f465eec86de9873696611dfda04a | example_project/users/social_pipeline.py | example_project/users/social_pipeline.py | import hashlib
from rest_framework.response import Response
def auto_logout(*args, **kwargs):
"""Do not compare current user with new one"""
return {'user': None}
def save_avatar(strategy, details, user=None, *args, **kwargs):
"""Get user avatar from social provider."""
if user:
backend_name = kwargs['backend'].__class__.__name__.lower()
response = kwargs.get('response', {})
social_thumb = None
if 'facebook' in backend_name:
if 'id' in response:
social_thumb = (
'http://graph.facebook.com/{0}/picture?type=normal'
).format(response['id'])
elif 'twitter' in backend_name and response.get('profile_image_url'):
social_thumb = response['profile_image_url']
elif 'googleoauth2' in backend_name and response.get('image', {}).get('url'):
social_thumb = response['image']['url'].split('?')[0]
else:
social_thumb = 'http://www.gravatar.com/avatar/'
social_thumb += hashlib.md5(user.email.lower().encode('utf8')).hexdigest()
social_thumb += '?size=100'
if social_thumb and user.social_thumb != social_thumb:
user.social_thumb = social_thumb
strategy.storage.user.changed(user)
def check_for_email(backend, uid, user=None, *args, **kwargs):
if not kwargs['details'].get('email'):
return Response({'error': "Email wasn't provided by facebook"}, status=400)
| import hashlib
from rest_framework.response import Response
def auto_logout(*args, **kwargs):
"""Do not compare current user with new one"""
return {'user': None}
def save_avatar(strategy, details, user=None, *args, **kwargs):
"""Get user avatar from social provider."""
if user:
backend_name = kwargs['backend'].__class__.__name__.lower()
response = kwargs.get('response', {})
social_thumb = None
if 'facebook' in backend_name:
if 'id' in response:
social_thumb = (
'http://graph.facebook.com/{0}/picture?type=normal'
).format(response['id'])
elif 'twitter' in backend_name and response.get('profile_image_url'):
social_thumb = response['profile_image_url']
elif 'googleoauth2' in backend_name and response.get('image', {}).get('url'):
social_thumb = response['image']['url'].split('?')[0]
else:
social_thumb = 'http://www.gravatar.com/avatar/'
social_thumb += hashlib.md5(user.email.lower().encode('utf8')).hexdigest()
social_thumb += '?size=100'
if social_thumb and user.social_thumb != social_thumb:
user.social_thumb = social_thumb
strategy.storage.user.changed(user)
def check_for_email(backend, uid, user=None, *args, **kwargs):
if not kwargs['details'].get('email'):
return Response({'error': "Email wasn't provided by oauth provider"}, status=400)
| Fix error message in example project | Fix error message in example project
| Python | mit | st4lk/django-rest-social-auth,st4lk/django-rest-social-auth,st4lk/django-rest-social-auth | ---
+++
@@ -33,4 +33,4 @@
def check_for_email(backend, uid, user=None, *args, **kwargs):
if not kwargs['details'].get('email'):
- return Response({'error': "Email wasn't provided by facebook"}, status=400)
+ return Response({'error': "Email wasn't provided by oauth provider"}, status=400) |
ab83c8a51cb2950226a5ccf341ad4bd9774a6df4 | client.py | client.py | # encoding=utf-8
from __future__ import unicode_literals
import socket
from time import sleep
def mount(s, at, uuid=None, label=None, name=None):
for name, value in ((b'uuid', uuid), (b'label', label), (b'name', name)):
if value is not None:
value = value.encode('utf_8')
at = at.encode('utf_8')
msg = b'5:mount{0}:{1}={2}{3}:at={4}$'.format(
len(name + value) + 1, name, value,
len(b'at' + at) + 1, at)
print repr(msg)
s.sendall(msg[0:9])
sleep(1)
s.sendall(msg[9:])
return
def main():
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect('/tmp/arise.sock')
mount(s, '/mnt/place', label='UFDé')
sleep(1)
if __name__ == '__main__':
main()
| # encoding=utf_8
from __future__ import unicode_literals
import socket
from time import sleep
def mount(s, at, uuid=None, label=None, name=None):
for name, value in ((b'uuid', uuid), (b'label', label), (b'name', name)):
if value is not None:
value = value.encode('utf_8')
at = at.encode('utf_8')
msg = b'5:mount{0}:{1}={2}{3}:at={4}$'.format(
len(name + value) + 1, name, value,
len(b'at' + at) + 1, at)
print repr(msg)
s.sendall(msg[0:9])
sleep(1)
s.sendall(msg[9:])
return
def main():
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect('/tmp/arise.sock')
mount(s, '/mnt/place', label='UFDé')
sleep(1)
if __name__ == '__main__':
main()
| Change encoding name for no reason | Change encoding name for no reason
| Python | mit | drkitty/arise | ---
+++
@@ -1,4 +1,4 @@
-# encoding=utf-8
+# encoding=utf_8
from __future__ import unicode_literals
import socket |
20f6df95d302ea79d11208ada6218a2c99d397e3 | common.py | common.py | import json
from base64 import b64encode
# http://stackoverflow.com/a/4256027/212555
def del_none(o):
"""
Delete keys with the value ``None`` in a dictionary, recursively.
This alters the input so you may wish to ``copy`` the dict first.
"""
if isinstance(o, dict):
d = o
else:
d = o.__dict__
for key, value in list(d.items()):
if value is None:
del d[key]
elif isinstance(value, dict):
del_none(value)
return d
def _to_json_dict(o):
if isinstance(o, bytes):
try:
return o.decode("ASCII")
except UnicodeError:
return b64encode(o)
if isinstance(o, set):
return list(o)
return o.__dict__
def to_json(o):
return json.dumps(del_none(o), default=_to_json_dict, indent=4)
| import json
from base64 import b64encode
# http://stackoverflow.com/a/4256027/212555
def del_none(o):
"""
Delete keys with the value ``None`` in a dictionary, recursively.
This alters the input so you may wish to ``copy`` the dict first.
"""
if isinstance(o, dict):
d = o.copy()
else:
d = o.__dict__.copy()
for key, value in list(d.items()):
if value is None:
del d[key]
elif isinstance(value, dict):
del_none(value)
return d
def _to_json_dict(o):
if isinstance(o, bytes):
try:
return o.decode("ASCII")
except UnicodeError:
return b64encode(o)
if isinstance(o, set):
return list(o)
return o.__dict__
def to_json(o):
return json.dumps(del_none(o), default=_to_json_dict, indent=4)
| Make a copy of dicts before deleting things from them when printing. | Make a copy of dicts before deleting things from them when printing.
| Python | bsd-2-clause | brendanlong/mpeg-ts-inspector,brendanlong/mpeg-ts-inspector | ---
+++
@@ -11,9 +11,9 @@
This alters the input so you may wish to ``copy`` the dict first.
"""
if isinstance(o, dict):
- d = o
+ d = o.copy()
else:
- d = o.__dict__
+ d = o.__dict__.copy()
for key, value in list(d.items()):
if value is None:
del d[key] |
038d33aa57a89d17a075109dd01eb682591e36ff | config.py | config.py | from config_secret import SecretConfig
class Config:
SECRET_KEY = SecretConfig.SECRET_KEY
# MongoDB config
MONGO_DBNAME = SecretConfig.MONGO_DBNAME
MONGO_HOST = SecretConfig.MONGO_HOST
MONGO_PORT = SecretConfig.MONGO_PORT
# Cloning config
CLONE_TMP_DIR = 'tmp'
CLONE_TIMEOUT = 15
| from config_secret import SecretConfig
class Config:
SECRET_KEY = SecretConfig.SECRET_KEY
# MongoDB config
MONGO_DBNAME = SecretConfig.MONGO_DBNAME
MONGO_HOST = SecretConfig.MONGO_HOST
MONGO_PORT = SecretConfig.MONGO_PORT
# Cloning config
CLONE_TMP_DIR = 'tmp'
CLONE_TIMEOUT = 30
| Increase the cloning timeout limit | Increase the cloning timeout limit
| Python | mit | mingrammer/pyreportcard,mingrammer/pyreportcard | ---
+++
@@ -11,4 +11,4 @@
# Cloning config
CLONE_TMP_DIR = 'tmp'
- CLONE_TIMEOUT = 15
+ CLONE_TIMEOUT = 30 |
fd7027ae889d61949998ea02fbb56dbc8e6005a4 | polling_stations/apps/data_importers/management/commands/import_cheltenham.py | polling_stations/apps/data_importers/management/commands/import_cheltenham.py | from data_importers.management.commands import BaseHalaroseCsvImporter
class Command(BaseHalaroseCsvImporter):
council_id = "CHT"
addresses_name = (
"2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv"
)
stations_name = (
"2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv"
)
elections = ["2022-05-05"]
def address_record_to_dict(self, record):
if record.housepostcode in [
"GL50 2RF",
"GL52 6RN",
"GL52 2ES",
"GL53 7AJ",
"GL50 3RB",
"GL53 0HL",
"GL50 2DZ",
]:
return None
return super().address_record_to_dict(record)
| from data_importers.management.commands import BaseHalaroseCsvImporter
class Command(BaseHalaroseCsvImporter):
council_id = "CHT"
addresses_name = (
"2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv"
)
stations_name = (
"2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv"
)
elections = ["2022-05-05"]
def address_record_to_dict(self, record):
if record.housepostcode in [
"GL50 2RF",
"GL52 6RN",
"GL52 2ES",
"GL53 7AJ",
"GL50 3RB",
"GL53 0HL",
"GL50 2DZ",
]:
return None
return super().address_record_to_dict(record)
def station_record_to_dict(self, record):
if record.pollingstationnumber == "191":
record = record._replace(pollingstationaddress_1="")
return super().station_record_to_dict(record)
| Fix to CHT station name | Fix to CHT station name
| Python | bsd-3-clause | DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations | ---
+++
@@ -25,3 +25,8 @@
return None
return super().address_record_to_dict(record)
+
+ def station_record_to_dict(self, record):
+ if record.pollingstationnumber == "191":
+ record = record._replace(pollingstationaddress_1="")
+ return super().station_record_to_dict(record) |
f2cdd8eb42afb9db5465e062544631684cabd24f | wagtail/contrib/wagtailfrontendcache/signal_handlers.py | wagtail/contrib/wagtailfrontendcache/signal_handlers.py | from django.db import models
from django.db.models.signals import post_delete
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.signals import page_published
from wagtail.contrib.wagtailfrontendcache.utils import purge_page_from_cache
def page_published_signal_handler(instance, **kwargs):
purge_page_from_cache(instance)
def post_delete_signal_handler(instance, **kwargs):
purge_page_from_cache(instance)
def register_signal_handlers():
# Get list of models that are page types
indexed_models = [model for model in models.get_models() if issubclass(model, Page)]
# Loop through list and register signal handlers for each one
for model in indexed_models:
page_published.connect(page_published_signal_handler, sender=model)
post_delete.connect(post_delete_signal_handler, sender=model)
| from django.db import models
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.signals import page_published, page_unpublished
from wagtail.contrib.wagtailfrontendcache.utils import purge_page_from_cache
def page_published_signal_handler(instance, **kwargs):
purge_page_from_cache(instance)
def page_unpublished_signal_handler(instance, **kwargs):
purge_page_from_cache(instance)
def register_signal_handlers():
# Get list of models that are page types
indexed_models = [model for model in models.get_models() if issubclass(model, Page)]
# Loop through list and register signal handlers for each one
for model in indexed_models:
page_published.connect(page_published_signal_handler, sender=model)
page_unpublished.connect(page_unpublished_signal_handler, sender=model)
| Use page_unpublished signal in frontend cache invalidator | Use page_unpublished signal in frontend cache invalidator
| Python | bsd-3-clause | Pennebaker/wagtail,chrxr/wagtail,jorge-marques/wagtail,jnns/wagtail,kurtw/wagtail,jorge-marques/wagtail,kaedroho/wagtail,WQuanfeng/wagtail,willcodefortea/wagtail,chimeno/wagtail,JoshBarr/wagtail,nimasmi/wagtail,zerolab/wagtail,torchbox/wagtail,kaedroho/wagtail,nutztherookie/wagtail,jorge-marques/wagtail,Klaudit/wagtail,mjec/wagtail,torchbox/wagtail,kurtrwall/wagtail,dresiu/wagtail,jorge-marques/wagtail,chimeno/wagtail,darith27/wagtail,Toshakins/wagtail,taedori81/wagtail,nealtodd/wagtail,iansprice/wagtail,WQuanfeng/wagtail,willcodefortea/wagtail,quru/wagtail,chrxr/wagtail,jnns/wagtail,gasman/wagtail,darith27/wagtail,takeshineshiro/wagtail,jnns/wagtail,iansprice/wagtail,willcodefortea/wagtail,timorieber/wagtail,Klaudit/wagtail,mikedingjan/wagtail,gogobook/wagtail,inonit/wagtail,Klaudit/wagtail,tangentlabs/wagtail,zerolab/wagtail,zerolab/wagtail,JoshBarr/wagtail,FlipperPA/wagtail,KimGlazebrook/wagtail-experiment,thenewguy/wagtail,nrsimha/wagtail,tangentlabs/wagtail,chrxr/wagtail,stevenewey/wagtail,JoshBarr/wagtail,taedori81/wagtail,rsalmaso/wagtail,WQuanfeng/wagtail,serzans/wagtail,Tivix/wagtail,bjesus/wagtail,Toshakins/wagtail,davecranwell/wagtail,gogobook/wagtail,wagtail/wagtail,mephizzle/wagtail,mixxorz/wagtail,rjsproxy/wagtail,wagtail/wagtail,stevenewey/wagtail,zerolab/wagtail,rsalmaso/wagtail,hanpama/wagtail,taedori81/wagtail,Tivix/wagtail,mjec/wagtail,dresiu/wagtail,hamsterbacke23/wagtail,janusnic/wagtail,nealtodd/wagtail,nilnvoid/wagtail,mixxorz/wagtail,Pennebaker/wagtail,marctc/wagtail,serzans/wagtail,nilnvoid/wagtail,Toshakins/wagtail,thenewguy/wagtail,Pennebaker/wagtail,rv816/wagtail,benjaoming/wagtail,m-sanders/wagtail,nutztherookie/wagtail,jorge-marques/wagtail,chimeno/wagtail,FlipperPA/wagtail,marctc/wagtail,nimasmi/wagtail,torchbox/wagtail,mikedingjan/wagtail,m-sanders/wagtail,m-sanders/wagtail,gogobook/wagtail,dresiu/wagtail,nrsimha/wagtail,nilnvoid/wagtail,kurtrwall/wagtail,hanpama/wagtail,kurtrwall/wagtail,iho/wagtail,timorieber/wagtail,rsalmaso/wagtail,inonit/wagtail,chrxr/wagtail,wagtail/wagtail,jordij/wagtail,thenewguy/wagtail,quru/wagtail,takeflight/wagtail,mephizzle/wagtail,kurtw/wagtail,100Shapes/wagtail,benemery/wagtail,stevenewey/wagtail,takeshineshiro/wagtail,chimeno/wagtail,davecranwell/wagtail,takeflight/wagtail,taedori81/wagtail,zerolab/wagtail,gogobook/wagtail,hamsterbacke23/wagtail,wagtail/wagtail,nutztherookie/wagtail,janusnic/wagtail,mjec/wagtail,mephizzle/wagtail,rjsproxy/wagtail,iansprice/wagtail,jordij/wagtail,kaedroho/wagtail,benjaoming/wagtail,nrsimha/wagtail,benjaoming/wagtail,nrsimha/wagtail,darith27/wagtail,taedori81/wagtail,mayapurmedia/wagtail,benemery/wagtail,benjaoming/wagtail,quru/wagtail,serzans/wagtail,thenewguy/wagtail,mikedingjan/wagtail,JoshBarr/wagtail,Toshakins/wagtail,inonit/wagtail,Tivix/wagtail,kaedroho/wagtail,gasman/wagtail,rsalmaso/wagtail,dresiu/wagtail,chimeno/wagtail,inonit/wagtail,mikedingjan/wagtail,mayapurmedia/wagtail,mephizzle/wagtail,KimGlazebrook/wagtail-experiment,iho/wagtail,hamsterbacke23/wagtail,kaedroho/wagtail,nimasmi/wagtail,rjsproxy/wagtail,iho/wagtail,rjsproxy/wagtail,dresiu/wagtail,mayapurmedia/wagtail,torchbox/wagtail,stevenewey/wagtail,bjesus/wagtail,nealtodd/wagtail,rv816/wagtail,darith27/wagtail,hanpama/wagtail,takeshineshiro/wagtail,bjesus/wagtail,jordij/wagtail,KimGlazebrook/wagtail-experiment,nimasmi/wagtail,nutztherookie/wagtail,KimGlazebrook/wagtail-experiment,marctc/wagtail,jordij/wagtail,takeshineshiro/wagtail,Tivix/wagtail,gasman/wagtail,thenewguy/wagtail,rv816/wagtail,benemery/wagtail,davecranwell/wagtail,nilnvoid/wagtail,janusnic/wagtail,janusnic/wagtail,timorieber/wagtail,iansprice/wagtail,kurtw/wagtail,iho/wagtail,takeflight/wagtail,quru/wagtail,takeflight/wagtail,mixxorz/wagtail,marctc/wagtail,mayapurmedia/wagtail,kurtw/wagtail,Pennebaker/wagtail,gasman/wagtail,mixxorz/wagtail,m-sanders/wagtail,serzans/wagtail,mixxorz/wagtail,WQuanfeng/wagtail,rsalmaso/wagtail,timorieber/wagtail,100Shapes/wagtail,gasman/wagtail,100Shapes/wagtail,jnns/wagtail,hamsterbacke23/wagtail,willcodefortea/wagtail,tangentlabs/wagtail,hanpama/wagtail,tangentlabs/wagtail,nealtodd/wagtail,mjec/wagtail,FlipperPA/wagtail,FlipperPA/wagtail,bjesus/wagtail,davecranwell/wagtail,wagtail/wagtail,rv816/wagtail,benemery/wagtail,Klaudit/wagtail,kurtrwall/wagtail | ---
+++
@@ -1,8 +1,7 @@
from django.db import models
-from django.db.models.signals import post_delete
from wagtail.wagtailcore.models import Page
-from wagtail.wagtailcore.signals import page_published
+from wagtail.wagtailcore.signals import page_published, page_unpublished
from wagtail.contrib.wagtailfrontendcache.utils import purge_page_from_cache
@@ -11,7 +10,7 @@
purge_page_from_cache(instance)
-def post_delete_signal_handler(instance, **kwargs):
+def page_unpublished_signal_handler(instance, **kwargs):
purge_page_from_cache(instance)
@@ -22,4 +21,4 @@
# Loop through list and register signal handlers for each one
for model in indexed_models:
page_published.connect(page_published_signal_handler, sender=model)
- post_delete.connect(post_delete_signal_handler, sender=model)
+ page_unpublished.connect(page_unpublished_signal_handler, sender=model) |
add50f0356756469c1ee1e52f13faee7df85f280 | tests/rest/rest_test_suite.py | tests/rest/rest_test_suite.py | import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
from http_test_suite import HTTPTestSuite
from mozdef_util.utilities.dot_dict import DotDict
import mock
from configlib import OptionParser
class RestTestDict(DotDict):
@property
def __dict__(self):
return self
class RestTestSuite(HTTPTestSuite):
def setup(self):
sample_config = RestTestDict()
sample_config.configfile = os.path.join(os.path.dirname(__file__), 'index.conf')
OptionParser.parse_args = mock.Mock(return_value=(sample_config, {}))
from rest import index
self.application = index.application
super(RestTestSuite, self).setup()
| import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
from http_test_suite import HTTPTestSuite
from mozdef_util.utilities.dot_dict import DotDict
import mock
from configlib import OptionParser
import importlib
class RestTestDict(DotDict):
@property
def __dict__(self):
return self
class RestTestSuite(HTTPTestSuite):
def setup(self):
sample_config = RestTestDict()
sample_config.configfile = os.path.join(os.path.dirname(__file__), 'index.conf')
OptionParser.parse_args = mock.Mock(return_value=(sample_config, {}))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../rest"))
import plugins
importlib.reload(plugins)
from rest import index
self.application = index.application
super(RestTestSuite, self).setup()
| Fix import path for rest plugins | Fix import path for rest plugins
| Python | mpl-2.0 | mozilla/MozDef,mozilla/MozDef,mpurzynski/MozDef,mpurzynski/MozDef,mozilla/MozDef,mpurzynski/MozDef,jeffbryner/MozDef,jeffbryner/MozDef,mozilla/MozDef,mpurzynski/MozDef,jeffbryner/MozDef,jeffbryner/MozDef | ---
+++
@@ -8,6 +8,7 @@
import mock
from configlib import OptionParser
+import importlib
class RestTestDict(DotDict):
@@ -23,6 +24,10 @@
sample_config.configfile = os.path.join(os.path.dirname(__file__), 'index.conf')
OptionParser.parse_args = mock.Mock(return_value=(sample_config, {}))
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../rest"))
+ import plugins
+ importlib.reload(plugins)
from rest import index
+
self.application = index.application
super(RestTestSuite, self).setup() |
5b516cd3e6363c4c995022c358fabeb0cc543115 | tests/test_route_requester.py | tests/test_route_requester.py | import unittest
from pydirections.route_requester import DirectionsRequest
from pydirections.exceptions import InvalidModeError, InvalidAPIKeyError, InvalidAlternativeError
class TestOptionalParameters(unittest.TestCase):
requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA")
def test_invalid_mode(self):
"""
Tests the is_valid_mode function for an invalid input
"""
with self.assertRaises(InvalidModeError):
requester.set_mode("flying")
def test_invalid_alternative(self):
"""
Tests for error handling when an invalid value is provided to
the set_alternative function
"""
with self.assertRaises(InvalidAlternativeError):
requester.set_alternatives('False')
class TestAPIKey(unittest.TestCase):
requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA")
def test_invalid_api_key(self):
invalid_key = 123456
with self.assertRaises(InvalidAPIKeyError):
requester.set_api_key(invalid_key)
if __name__ == '__main__':
unittest.main() | import unittest
from pydirections.route_requester import DirectionsRequest
from pydirections.exceptions import InvalidModeError, InvalidAPIKeyError, InvalidAlternativeError
requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA")
class TestOptionalParameters(unittest.TestCase):
def test_invalid_mode(self):
"""
Tests the is_valid_mode function for an invalid input
"""
with self.assertRaises(InvalidModeError):
requester.set_mode("flying")
def test_invalid_alternative(self):
"""
Tests for error handling when an invalid value is provided to
the set_alternative function
"""
with self.assertRaises(InvalidAlternativeError):
requester.set_alternatives('False')
class TestAPIKey(unittest.TestCase):
def test_invalid_api_key(self):
invalid_key = 123456
with self.assertRaises(InvalidAPIKeyError):
requester.set_api_key(invalid_key)
if __name__ == '__main__':
unittest.main() | Fix bug in unit tests | Fix bug in unit tests
| Python | apache-2.0 | apranav19/pydirections | ---
+++
@@ -2,9 +2,9 @@
from pydirections.route_requester import DirectionsRequest
from pydirections.exceptions import InvalidModeError, InvalidAPIKeyError, InvalidAlternativeError
+requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA")
+
class TestOptionalParameters(unittest.TestCase):
- requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA")
-
def test_invalid_mode(self):
"""
Tests the is_valid_mode function for an invalid input
@@ -22,8 +22,6 @@
class TestAPIKey(unittest.TestCase):
- requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA")
-
def test_invalid_api_key(self):
invalid_key = 123456
with self.assertRaises(InvalidAPIKeyError): |
9b720026722ce92a8c0e05aa041d6e861c5e4e82 | changes/api/jobstep_deallocate.py | changes/api/jobstep_deallocate.py | from __future__ import absolute_import, division, unicode_literals
from changes.api.base import APIView
from changes.constants import Status
from changes.config import db
from changes.jobs.sync_job_step import sync_job_step
from changes.models import JobStep
class JobStepDeallocateAPIView(APIView):
def post(self, step_id):
to_deallocate = JobStep.query.get(step_id)
if to_deallocate is None:
return '', 404
if to_deallocate.status != Status.allocated:
return {
"error": "Only {0} job steps may be deallocated.",
"actual_status": to_deallocate.status.name
}, 400
to_deallocate.status = Status.pending_allocation
to_deallocate.date_started = None
to_deallocate.date_finished = None
db.session.add(to_deallocate)
db.session.commit()
sync_job_step.delay(
step_id=to_deallocate.id.hex,
task_id=to_deallocate.id.hex,
parent_task_id=to_deallocate.job_id.hex,
)
return self.respond(to_deallocate)
| from __future__ import absolute_import, division, unicode_literals
from changes.api.base import APIView
from changes.constants import Status
from changes.config import db
from changes.jobs.sync_job_step import sync_job_step
from changes.models import JobStep
class JobStepDeallocateAPIView(APIView):
def post(self, step_id):
to_deallocate = JobStep.query.get(step_id)
if to_deallocate is None:
return '', 404
if to_deallocate.status not in (Status.in_progress, Status.allocated):
return {
"error": "Only allocated and running job steps may be deallocated.",
"actual_status": to_deallocate.status.name
}, 400
to_deallocate.status = Status.pending_allocation
to_deallocate.date_started = None
to_deallocate.date_finished = None
db.session.add(to_deallocate)
db.session.commit()
sync_job_step.delay(
step_id=to_deallocate.id.hex,
task_id=to_deallocate.id.hex,
parent_task_id=to_deallocate.job_id.hex,
)
return self.respond(to_deallocate)
| Allow running jobsteps to be deallocated | Allow running jobsteps to be deallocated
| Python | apache-2.0 | dropbox/changes,bowlofstew/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes | ---
+++
@@ -15,9 +15,9 @@
if to_deallocate is None:
return '', 404
- if to_deallocate.status != Status.allocated:
+ if to_deallocate.status not in (Status.in_progress, Status.allocated):
return {
- "error": "Only {0} job steps may be deallocated.",
+ "error": "Only allocated and running job steps may be deallocated.",
"actual_status": to_deallocate.status.name
}, 400
|
b0f47f2d9b75ac777c3cf4a45c1930de9a42c6bc | heutagogy/heutagogy.py | heutagogy/heutagogy.py | from heutagogy import app
import heutagogy.persistence
import os
from datetime import timedelta
app.config.from_object(__name__)
app.config.update(dict(
USERS={
'myuser': {'password': 'mypassword'},
'user2': {'password': 'pass2'},
},
JWT_AUTH_URL_RULE='/api/v1/login',
JWT_EXPIRATION_DELTA=timedelta(seconds=2592000), # 1 month
DATABASE=os.path.join(app.root_path, 'heutagogy.sqlite3'),
DEBUG=True))
app.config.from_envvar('HEUTAGOGY_SETTINGS', silent=True)
if not app.config['SECRET_KEY']:
app.config['SECRET_KEY'] = 'super-secret'
@app.cli.command('initdb')
def initdb_command():
"""Creates the database tables."""
heutagogy.persistence.initialize()
| from heutagogy import app
import heutagogy.persistence
import os
from datetime import timedelta
app.config.from_object(__name__)
app.config.update(dict(
USERS={
'myuser': {'password': 'mypassword'},
'user2': {'password': 'pass2'},
},
JWT_AUTH_URL_RULE='/api/v1/login',
JWT_EXPIRATION_DELTA=timedelta(seconds=2592000), # 1 month
DATABASE=os.path.join(app.root_path, 'heutagogy.sqlite3'),
DEBUG=True))
app.config.from_envvar('HEUTAGOGY_SETTINGS', silent=True)
if not app.config['SECRET_KEY']:
app.config['SECRET_KEY'] = 'super-secret'
@app.cli.command('initdb')
def initdb_command():
"""Creates the database tables."""
heutagogy.persistence.initialize()
with app.app_context():
if not os.path.isfile(app.config['DATABASE']):
heutagogy.persistence.initialize()
| Initialize database if it does not exist | Initialize database if it does not exist
| Python | agpl-3.0 | heutagogy/heutagogy-backend,heutagogy/heutagogy-backend | ---
+++
@@ -23,3 +23,8 @@
def initdb_command():
"""Creates the database tables."""
heutagogy.persistence.initialize()
+
+
+with app.app_context():
+ if not os.path.isfile(app.config['DATABASE']):
+ heutagogy.persistence.initialize() |
df739ec121beede945d1bcc43cc239b5e7045c5a | nuxeo-drive-client/nxdrive/tests/test_integration_copy.py | nuxeo-drive-client/nxdrive/tests/test_integration_copy.py | import os
from nxdrive.tests.common import IntegrationTestCase
from nxdrive.client import LocalClient
class TestIntegrationCopy(IntegrationTestCase):
def test_synchronize_remote_copy(self):
# Get local and remote clients
local = LocalClient(os.path.join(self.local_nxdrive_folder_1,
self.workspace_title))
remote = self.remote_document_client_1
# Bind the server and root workspace
self.bind_server(self.ndrive_1, self.user_1, self.nuxeo_url, self.local_nxdrive_folder_1, self.password_1)
#TODO: allow use of self.bind_root(self.ndrive_1, self.workspace, self.local_nxdrive_folder_1)
remote.register_as_root(self.workspace)
# Create a file and a folder in the remote root workspace
remote.make_file('/', 'test.odt', 'Some content.')
remote.make_folder('/', 'Test folder')
# Copy the file to the folder remotely
remote.copy('/test.odt', '/Test folder')
# Launch ndrive, expecting 4 synchronized items
self.ndrive(self.ndrive_1, quit_timeout=300)
self.assertTrue(local.exists('/'))
self.assertTrue(local.exists('/Test folder'))
self.assertTrue(local.exists('/test.odt'))
self.assertTrue(local.exists('/Test folder/test.odt'))
self.assertEquals(local.get_content('/Test folder/test.odt'),
'Some content.')
| import os
from nxdrive.tests.common import IntegrationTestCase
from nxdrive.client import LocalClient
class TestIntegrationCopy(IntegrationTestCase):
def test_synchronize_remote_copy(self):
# Get local and remote clients
local = LocalClient(os.path.join(self.local_nxdrive_folder_1,
self.workspace_title))
remote = self.remote_document_client_1
# Bind the server and root workspace
self.bind_server(self.ndrive_1, self.user_1, self.nuxeo_url, self.local_nxdrive_folder_1, self.password_1)
#TODO: allow use of self.bind_root(self.ndrive_1, self.workspace, self.local_nxdrive_folder_1)
remote.register_as_root(self.workspace)
# Create a file and a folder in the remote root workspace
remote.make_file('/', 'test.odt', 'Some content.')
remote.make_folder('/', 'Test folder')
# Copy the file to the folder remotely
remote.copy('/test.odt', '/Test folder')
# Launch ndrive, expecting 4 synchronized items
self.ndrive(self.ndrive_1)
self.assertTrue(local.exists('/'))
self.assertTrue(local.exists('/Test folder'))
self.assertTrue(local.exists('/test.odt'))
self.assertTrue(local.exists('/Test folder/test.odt'))
self.assertEquals(local.get_content('/Test folder/test.odt'),
'Some content.')
| Remove long timeout to make file blacklisting bug appear, waiting for the fix | NXDRIVE-170: Remove long timeout to make file blacklisting bug appear, waiting for the fix
| Python | lgpl-2.1 | arameshkumar/base-nuxeo-drive,DirkHoffmann/nuxeo-drive,loopingz/nuxeo-drive,ssdi-drive/nuxeo-drive,IsaacYangSLA/nuxeo-drive,arameshkumar/nuxeo-drive,loopingz/nuxeo-drive,rsoumyassdi/nuxeo-drive,arameshkumar/base-nuxeo-drive,DirkHoffmann/nuxeo-drive,DirkHoffmann/nuxeo-drive,IsaacYangSLA/nuxeo-drive,IsaacYangSLA/nuxeo-drive,loopingz/nuxeo-drive,arameshkumar/nuxeo-drive,arameshkumar/base-nuxeo-drive,loopingz/nuxeo-drive,ssdi-drive/nuxeo-drive,arameshkumar/nuxeo-drive,rsoumyassdi/nuxeo-drive,IsaacYangSLA/nuxeo-drive,loopingz/nuxeo-drive,rsoumyassdi/nuxeo-drive,rsoumyassdi/nuxeo-drive,arameshkumar/base-nuxeo-drive,arameshkumar/nuxeo-drive,DirkHoffmann/nuxeo-drive,DirkHoffmann/nuxeo-drive,IsaacYangSLA/nuxeo-drive,ssdi-drive/nuxeo-drive | ---
+++
@@ -25,7 +25,7 @@
remote.copy('/test.odt', '/Test folder')
# Launch ndrive, expecting 4 synchronized items
- self.ndrive(self.ndrive_1, quit_timeout=300)
+ self.ndrive(self.ndrive_1)
self.assertTrue(local.exists('/'))
self.assertTrue(local.exists('/Test folder'))
self.assertTrue(local.exists('/test.odt')) |
e50892a1155b9bd35e7b7cbf90646bac1b1724f6 | importkit/languages.py | importkit/languages.py | ##
# Copyright (c) 2013 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
# Import languages to register them
from metamagic.utils.lang import yaml, python, javascript
| ##
# Copyright (c) 2013 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
# Import languages to register them
from metamagic.utils.lang import yaml, python, javascript, jplus
| Switch class system to use JPlus types machinery | utils.lang.js: Switch class system to use JPlus types machinery
| Python | mit | sprymix/importkit | ---
+++
@@ -7,4 +7,4 @@
# Import languages to register them
-from metamagic.utils.lang import yaml, python, javascript
+from metamagic.utils.lang import yaml, python, javascript, jplus |
64cd71fd171cd1b76b111aedc94423006176f811 | src/tldt/cli.py | src/tldt/cli.py | import argparse
import tldt
def main():
parser = argparse.ArgumentParser(description="cacat")
parser.add_argument("head_repo")
parser.add_argument("head_sha")
parser.add_argument("base_repo")
parser.add_argument("base_sha")
args = parser.parse_args()
tldt.main(head_repo=args.head_repo,
head_sha=args.head_sha,
base_repo=args.base_repo,
base_sha=args.base_sha)
if __name__ == '__main__':
main()
| import argparse
import os.path
import tldt
def main():
user_home = os.path.expanduser("~")
parser = argparse.ArgumentParser(description="cacat")
parser.add_argument("head_repo")
parser.add_argument("head_sha")
parser.add_argument("base_repo")
parser.add_argument("base_sha")
parser.add_argument("--configuration", default=os.path.join(user_home, "tldt.ini"))
args = parser.parse_args()
tldt.main(head_repo=args.head_repo,
head_sha=args.head_sha,
base_repo=args.base_repo,
base_sha=args.base_sha,
configuration_path=args.configuration)
if __name__ == '__main__':
main()
| Add configuration file option with default to ~/tldt.ini | Add configuration file option with default to ~/tldt.ini
| Python | unlicense | rciorba/tldt,rciorba/tldt | ---
+++
@@ -1,20 +1,23 @@
import argparse
+import os.path
import tldt
def main():
+ user_home = os.path.expanduser("~")
parser = argparse.ArgumentParser(description="cacat")
parser.add_argument("head_repo")
parser.add_argument("head_sha")
parser.add_argument("base_repo")
parser.add_argument("base_sha")
+ parser.add_argument("--configuration", default=os.path.join(user_home, "tldt.ini"))
args = parser.parse_args()
tldt.main(head_repo=args.head_repo,
- head_sha=args.head_sha,
- base_repo=args.base_repo,
- base_sha=args.base_sha)
-
+ head_sha=args.head_sha,
+ base_repo=args.base_repo,
+ base_sha=args.base_sha,
+ configuration_path=args.configuration)
if __name__ == '__main__':
main() |
2c825d111125a630a96f0ee739d091a531547be5 | sbc_compassion/model/country_compassion.py | sbc_compassion/model/country_compassion.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emmanuel Mathier <[email protected]>
#
# The licence is in the file __openerp__.py
#
##############################################################################
from openerp import fields, models
class ResCountry(models.Model):
""" This class upgrade the countries to add spoken languages
to match Compassion needs.
"""
_inherit = 'compassion.country'
##########################################################################
# FIELDS #
##########################################################################
spoken_langs_ids = fields.Many2many('res.lang.compassion')
| # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emmanuel Mathier <[email protected]>
#
# The licence is in the file __openerp__.py
#
##############################################################################
from openerp import fields, models
class CompassionCountry(models.Model):
""" This class upgrade the countries to add spoken languages
to match Compassion needs.
"""
_inherit = 'compassion.country'
##########################################################################
# FIELDS #
##########################################################################
spoken_langs_ids = fields.Many2many('res.lang.compassion')
| Rename ResCountry class to CompassionCountry | Rename ResCountry class to CompassionCountry
| Python | agpl-3.0 | Secheron/compassion-modules,Secheron/compassion-modules,Secheron/compassion-modules | ---
+++
@@ -12,7 +12,7 @@
from openerp import fields, models
-class ResCountry(models.Model):
+class CompassionCountry(models.Model):
""" This class upgrade the countries to add spoken languages
to match Compassion needs. |
775aecd0a39e5112a704ec30657d3e46e3621bdd | django_auth_kerberos/backends.py | django_auth_kerberos/backends.py | import kerberos
import logging
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
logger = logging.getLogger(__name__)
class KrbBackend(ModelBackend):
"""
Django Authentication backend using Kerberos for password checking.
"""
def authenticate(self, username=None, password=None):
UserModel = get_user_model()
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
if not self.check_password(username, password):
return None
UserModel = get_user_model()
user, created = UserModel.objects.get_or_create(**{
UserModel.USERNAME_FIELD: username
})
return user
def check_password(self, username, password):
"""The actual password checking logic. Separated from the authenticate code from Django for easier updating"""
try:
kerberos.checkPassword(username.lower(), password, settings.KRB5_SERVICE, settings.KRB5_REALM)
return True
except kerberos.BasicAuthError:
if getattr(settings, "KRB5_DEBUG", False):
logger.exception("Failure during authentication")
return False
| import kerberos
import logging
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
logger = logging.getLogger(__name__)
class KrbBackend(ModelBackend):
"""
Django Authentication backend using Kerberos for password checking.
"""
def authenticate(self, username=None, password=None):
UserModel = get_user_model()
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
if not self.check_password(username, password):
return None
UserModel = get_user_model()
user, created = UserModel.objects.get_or_create(**{
UserModel.USERNAME_FIELD+"__iexact": username,
defaults: { UserModel.USERNAME_FIELD: username }
})
return user
def check_password(self, username, password):
"""The actual password checking logic. Separated from the authenticate code from Django for easier updating"""
try:
kerberos.checkPassword(username.lower(), password, settings.KRB5_SERVICE, settings.KRB5_REALM)
return True
except kerberos.BasicAuthError:
if getattr(settings, "KRB5_DEBUG", False):
logger.exception("Failure during authentication")
return False
| Make user query case insensitive | Make user query case insensitive | Python | mit | 02strich/django-auth-kerberos,mkesper/django-auth-kerberos | ---
+++
@@ -23,7 +23,8 @@
UserModel = get_user_model()
user, created = UserModel.objects.get_or_create(**{
- UserModel.USERNAME_FIELD: username
+ UserModel.USERNAME_FIELD+"__iexact": username,
+ defaults: { UserModel.USERNAME_FIELD: username }
})
return user
|
45e04697303eb85330bd61f1b386e483fc42f49b | src/oscar/templatetags/currency_filters.py | src/oscar/templatetags/currency_filters.py | from decimal import Decimal as D
from decimal import InvalidOperation
from babel.numbers import format_currency
from django import template
from django.conf import settings
from django.utils.translation import get_language, to_locale
register = template.Library()
@register.filter(name='currency')
def currency(value, currency=None):
"""
Format decimal value as currency
"""
try:
value = D(value)
except (TypeError, InvalidOperation):
return ""
# Using Babel's currency formatting
# http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency
OSCAR_CURRENCY_FORMAT = getattr(settings, 'OSCAR_CURRENCY_FORMAT', None)
kwargs = {
'currency': currency or settings.OSCAR_DEFAULT_CURRENCY,
'locale': to_locale(get_language() or settings.LANGUAGE_CODE)
}
if isinstance(OSCAR_CURRENCY_FORMAT, dict):
kwargs.update(OSCAR_CURRENCY_FORMAT.get(currency, {}))
else:
kwargs['format'] = OSCAR_CURRENCY_FORMAT
return format_currency(value, **kwargs)
| from decimal import Decimal as D
from decimal import InvalidOperation
from babel.numbers import format_currency
from django import template
from django.conf import settings
from django.utils.translation import get_language, to_locale
register = template.Library()
@register.filter(name='currency')
def currency(value, currency=None):
"""
Format decimal value as currency
"""
if currency is None:
currency = settings.OSCAR_DEFAULT_CURRENCY
try:
value = D(value)
except (TypeError, InvalidOperation):
return ""
# Using Babel's currency formatting
# http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency
OSCAR_CURRENCY_FORMAT = getattr(settings, 'OSCAR_CURRENCY_FORMAT', None)
kwargs = {
'currency': currency,
'locale': to_locale(get_language() or settings.LANGUAGE_CODE)
}
if isinstance(OSCAR_CURRENCY_FORMAT, dict):
kwargs.update(OSCAR_CURRENCY_FORMAT.get(currency, {}))
else:
kwargs['format'] = OSCAR_CURRENCY_FORMAT
return format_currency(value, **kwargs)
| Fix for missing default in currency filter | Fix for missing default in currency filter
| Python | bsd-3-clause | solarissmoke/django-oscar,solarissmoke/django-oscar,django-oscar/django-oscar,solarissmoke/django-oscar,solarissmoke/django-oscar,django-oscar/django-oscar,django-oscar/django-oscar,django-oscar/django-oscar | ---
+++
@@ -14,6 +14,9 @@
"""
Format decimal value as currency
"""
+ if currency is None:
+ currency = settings.OSCAR_DEFAULT_CURRENCY
+
try:
value = D(value)
except (TypeError, InvalidOperation):
@@ -22,7 +25,7 @@
# http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency
OSCAR_CURRENCY_FORMAT = getattr(settings, 'OSCAR_CURRENCY_FORMAT', None)
kwargs = {
- 'currency': currency or settings.OSCAR_DEFAULT_CURRENCY,
+ 'currency': currency,
'locale': to_locale(get_language() or settings.LANGUAGE_CODE)
}
if isinstance(OSCAR_CURRENCY_FORMAT, dict): |
6cf42d661facf1c11de545959b91c073709eac8e | webapp_tests.py | webapp_tests.py | #!/usr/bin/env python
import os
import webapp
import unittest
class WebappTestExtractingServiceDomainsFromLinks(unittest.TestCase):
#def setUp(self):
# self.app = webapp.app.test_client()
def test_extract_service_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link('https://foo.service.gov.uk/blah')
assert True == status
assert "foo.service.gov.uk" == domain
def test_extract_nonservice_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link('https://foo.foo.gov.uk/blah')
assert False == status
if __name__ == '__main__':
unittest.main()
| #!/usr/bin/env python
import os
import webapp
import unittest
class WebappTestExtractingServiceDomainsFromLinks(unittest.TestCase):
#def setUp(self):
# self.app = webapp.app.test_client()
def test_extract_service_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link('https://foo.service.gov.uk/blah')
assert True == status
assert "foo.service.gov.uk" == domain
def test_extract_nonservice_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link('https://foo.foo.gov.uk/blah')
assert False == status
class WebappTestExtractingServiceLinkFromSlug(unittest.TestCase):
def test_find_link_from_slug(self):
status, link = webapp.find_link_from_slug('/lasting-power-of-attorney')
assert True == status
assert "https://lastingpowerofattorney.service.gov.uk/" == link
def test_fail_to_find_link_from_slug(self):
status, link = webapp.find_link_from_slug('/bank-holidays')
assert False == status
if __name__ == '__main__':
unittest.main()
| Add a test for extracting service domain from a link | Add a test for extracting service domain from a link
| Python | mit | alphagov/service-domain-checker | ---
+++
@@ -13,9 +13,23 @@
assert True == status
assert "foo.service.gov.uk" == domain
+
def test_extract_nonservice_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link('https://foo.foo.gov.uk/blah')
assert False == status
+
+class WebappTestExtractingServiceLinkFromSlug(unittest.TestCase):
+
+ def test_find_link_from_slug(self):
+ status, link = webapp.find_link_from_slug('/lasting-power-of-attorney')
+ assert True == status
+ assert "https://lastingpowerofattorney.service.gov.uk/" == link
+
+ def test_fail_to_find_link_from_slug(self):
+ status, link = webapp.find_link_from_slug('/bank-holidays')
+ assert False == status
+
+
if __name__ == '__main__':
unittest.main() |
2f6dc1d43bd402152c7807e905cc808899a640d2 | mail/views.py | mail/views.py | import logging
from django.core.mail import EmailMessage
from django.http import JsonResponse
from django.middleware import csrf
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import redirect
from rest_framework.decorators import api_view
@csrf_exempt
@api_view(['POST', 'GET'])
def send_contact_message(request):
if request.method == 'POST':
from_name = request.POST.get("from_name", "")
from_address = request.POST.get("from_address", "")
from_string = '{} <{}>'.format(from_name, from_address)
subject = request.POST.get("subject", "")
message_body = request.POST.get("message_body", "")
# Add subject: to_address to this dict to add a new email address.
# Subject will map to the email being sent to to prevent misuse of our email server.
emails = {
'Bulk Order': '[email protected]',
}
try:
to_address = emails[subject].split(',')
email = EmailMessage(subject,
message_body,
'[email protected]',
to_address,
reply_to=[from_string])
email.send()
except KeyError:
logging.error("EMAIL FAILED TO SEND: subject:{}")
return redirect('/confirmation?contact')
# if this is not posting a message, let's send the csfr token back
else:
csrf_token = csrf.get_token(request)
data = {'csrf_token': csrf_token}
return JsonResponse(data)
| import logging
from django.core.mail import EmailMessage
from django.http import JsonResponse
from django.middleware import csrf
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import redirect
from rest_framework.decorators import api_view
@csrf_exempt
@api_view(['POST', 'GET'])
def send_contact_message(request):
if request.method == 'POST':
from_name = request.POST.get("from_name", "")
from_address = request.POST.get("from_address", "")
from_string = '{} <{}>'.format(from_name, from_address)
subject = request.POST.get("subject", "")
message_body = request.POST.get("message_body", "")
# Add subject: to_address to this dict to add a new email address.
# Subject will map to the email being sent to to prevent misuse of our email server.
emails = {
'Bulk Order': '[email protected]',
}
try:
to_address = emails[subject].split(',')
email = EmailMessage(subject,
message_body,
'[email protected]',
to_address,
reply_to=[from_string])
email.send()
except KeyError:
logging.error("EMAIL FAILED TO SEND: subject:{}")
return redirect('/confirmation?contact')
# if this is not posting a message, let's send the csfr token back
else:
csrf_token = csrf.get_token(request)
data = {'csrf_token': csrf_token}
return JsonResponse(data)
| Change bulk order email address to Tory | Change bulk order email address to Tory
| Python | agpl-3.0 | openstax/openstax-cms,openstax/openstax-cms,Connexions/openstax-cms,openstax/openstax-cms,Connexions/openstax-cms,openstax/openstax-cms | ---
+++
@@ -21,7 +21,7 @@
# Add subject: to_address to this dict to add a new email address.
# Subject will map to the email being sent to to prevent misuse of our email server.
emails = {
- 'Bulk Order': '[email protected]',
+ 'Bulk Order': '[email protected]',
}
try: |
c12a1b53166c34c074e018fcc149a0aa2db56b43 | helpscout/models/folder.py | helpscout/models/folder.py | # -*- coding: utf-8 -*-
# Copyright 2017-TODAY LasLabs Inc.
# License MIT (https://opensource.org/licenses/MIT).
import properties
from .. import BaseModel
class Folder(BaseModel):
name = properties.String(
'Folder name',
required=True,
)
type = properties.StringChoice(
'The type of folder.',
choices=['needsattention',
'drafts',
'assigned',
'open',
'closed',
'spam',
'mine',
],
default='drafts',
required=True,
)
user_id = properties.Integer(
'If the folder type is ``MyTickets``, this represents the Help Scout '
'user to which this folder belongs. Otherwise it is empty.',
)
total_count = properties.Integer(
'Total number of conversations in this folder.',
)
active_count = properties.Integer(
'Total number of conversations in this folder that are in an active '
'state (vs pending).',
)
modified_at = properties.DateTime(
'UTC time when this folder was modified.',
)
| # -*- coding: utf-8 -*-
# Copyright 2017-TODAY LasLabs Inc.
# License MIT (https://opensource.org/licenses/MIT).
import properties
from .. import BaseModel
class Folder(BaseModel):
name = properties.String(
'Folder name',
required=True,
)
type = properties.StringChoice(
'The type of folder.',
choices=['needsattention',
'drafts',
'assigned',
'open',
'closed',
'spam',
'mine',
'team',
],
default='drafts',
required=True,
)
user_id = properties.Integer(
'If the folder type is ``MyTickets``, this represents the Help Scout '
'user to which this folder belongs. Otherwise it is empty.',
)
total_count = properties.Integer(
'Total number of conversations in this folder.',
)
active_count = properties.Integer(
'Total number of conversations in this folder that are in an active '
'state (vs pending).',
)
modified_at = properties.DateTime(
'UTC time when this folder was modified.',
)
| Add 'team' to Folder type options | [ADD] Add 'team' to Folder type options
| Python | mit | LasLabs/python-helpscout | ---
+++
@@ -22,6 +22,7 @@
'closed',
'spam',
'mine',
+ 'team',
],
default='drafts',
required=True, |
bccfc6d3c0035e2a5668607ebb7dd6047ee1942f | kokki/cookbooks/mdadm/recipes/default.py | kokki/cookbooks/mdadm/recipes/default.py |
from kokki import *
if env.config.mdadm.arrays:
Package("mdadm")
Execute("mdadm-update-conf",
action = "nothing",
command = ("("
"echo DEVICE partitions > /etc/mdadm/mdadm.conf"
"; mdadm --detail --scan >> /etc/mdadm/mdadm.conf"
")"
))
for array in env.config.mdadm.arrays:
env.cookbooks.mdadm.Array(**array)
if array.get('fstype'):
if array['fstype'] == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=array['fstype'], device=array['name']),
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % dict(device=array['name']))
if array.get('mount_point'):
Mount(array['mount_point'],
device = array['name'],
fstype = array['fstype'],
options = array['fsoptions'] if array.get('fsoptions') is not None else ["noatime"],
action = ["mount", "enable"])
|
from kokki import *
if env.config.mdadm.arrays:
Package("mdadm")
Execute("mdadm-update-conf",
action = "nothing",
command = ("("
"echo DEVICE partitions > /etc/mdadm/mdadm.conf"
"; mdadm --detail --scan >> /etc/mdadm/mdadm.conf"
")"
))
for array in env.config.mdadm.arrays:
fstype = array.pop('fstype', None)
fsoptions = array.pop('fsoptions', None)
mount_point = array.pop('mount_point', None)
env.cookbooks.mdadm.Array(**array)
if fstype:
if fstype == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=fstype, device=array['name']),
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % dict(device=array['name']))
if mount_point:
Mount(mount_point,
device = array['name'],
fstype = fstype,
options = fsoptions if fsoptions is not None else ["noatime"],
action = ["mount", "enable"])
| Fix to mounting mdadm raid arrays | Fix to mounting mdadm raid arrays
| Python | bsd-3-clause | samuel/kokki | ---
+++
@@ -13,17 +13,21 @@
))
for array in env.config.mdadm.arrays:
+ fstype = array.pop('fstype', None)
+ fsoptions = array.pop('fsoptions', None)
+ mount_point = array.pop('mount_point', None)
+
env.cookbooks.mdadm.Array(**array)
- if array.get('fstype'):
- if array['fstype'] == "xfs":
+ if fstype:
+ if fstype == "xfs":
Package("xfsprogs")
- Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=array['fstype'], device=array['name']),
+ Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=fstype, device=array['name']),
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % dict(device=array['name']))
- if array.get('mount_point'):
- Mount(array['mount_point'],
+ if mount_point:
+ Mount(mount_point,
device = array['name'],
- fstype = array['fstype'],
- options = array['fsoptions'] if array.get('fsoptions') is not None else ["noatime"],
+ fstype = fstype,
+ options = fsoptions if fsoptions is not None else ["noatime"],
action = ["mount", "enable"]) |
4f2e23fe260e5f061d7d57821908492f14a2c56a | withtool/subprocess.py | withtool/subprocess.py | import subprocess
def run(command):
try:
subprocess.check_call(command, shell=True)
except:
pass
| import subprocess
def run(command):
try:
subprocess.check_call(command, shell=True)
except Exception:
pass
| Set expected exception class in "except" block | Set expected exception class in "except" block
Fix issue E722 of flake8
| Python | mit | renanivo/with | ---
+++
@@ -4,5 +4,5 @@
def run(command):
try:
subprocess.check_call(command, shell=True)
- except:
+ except Exception:
pass |
ff308a17c79fe2c27dcb2a1f888ee1332f6fdc11 | events.py | events.py | # encoding: utf-8
import Natural.util as util
import sublime, sublime_plugin
class PerformEventListener(sublime_plugin.EventListener):
"""Suggest subroutine completions for the perform statement."""
def on_query_completions(self, view, prefix, points):
if not util.is_natural_file(view):
return None
texts = util.text_preceding_points(view, points)
if all([text.strip().endswith('perform') for text in texts]):
subroutines = util.find_text_by_selector(view,
'entity.name.function.natural')
if not subroutines:
return None
subroutines.sort()
completions = [[sub, sub] for sub in subroutines]
return (completions, sublime.INHIBIT_WORD_COMPLETIONS)
| # encoding: utf-8
import Natural.util as util
import sublime, sublime_plugin
class PerformEventListener(sublime_plugin.EventListener):
"""Suggest subroutine completions for the perform statement."""
def on_query_completions(self, view, prefix, points):
if not util.is_natural_file(view):
return None
texts = util.text_preceding_points(view, points)
if all([text.strip().endswith('perform') for text in texts]):
subroutines = util.find_text_by_selector(view,
'entity.name.function.natural')
if not subroutines:
return None
subroutines.sort()
completions = [[sub, sub] for sub in subroutines]
return (completions, sublime.INHIBIT_WORD_COMPLETIONS)
class AddRulerToColumn72Listener(sublime_plugin.EventListener):
"""Add a ruler to column 72 when a Natural file is opened. If the user has
other rulers, they're not messed with."""
def on_load(self, view):
if not util.is_natural_file(view):
return
rulers = view.settings().get('rulers')
if 72 not in rulers:
rulers.append(72)
rulers.sort()
view.settings().set('rulers', rulers)
| Add a ruler to column 72 | Add a ruler to column 72
| Python | mit | andref/Unnatural-Sublime-Package | ---
+++
@@ -19,3 +19,17 @@
subroutines.sort()
completions = [[sub, sub] for sub in subroutines]
return (completions, sublime.INHIBIT_WORD_COMPLETIONS)
+
+
+class AddRulerToColumn72Listener(sublime_plugin.EventListener):
+ """Add a ruler to column 72 when a Natural file is opened. If the user has
+ other rulers, they're not messed with."""
+
+ def on_load(self, view):
+ if not util.is_natural_file(view):
+ return
+ rulers = view.settings().get('rulers')
+ if 72 not in rulers:
+ rulers.append(72)
+ rulers.sort()
+ view.settings().set('rulers', rulers) |
5a2f848badcdf9bf968e23cfb55f53eb023d18a4 | tests/helper.py | tests/helper.py | import unittest
import os
import yaml
from functools import wraps
from cmd import init_db, seed_db
from models import db
from scuevals_api import create_app
class TestCase(unittest.TestCase):
def setUp(self):
app = create_app()
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['TEST_DATABASE_URL']
app.testing = True
self.appx = app
self.app = app.test_client()
with app.app_context():
init_db(app, db)
seed_db(db)
def tearDown(self):
with self.appx.app_context():
db.session.remove()
db.drop_all()
def use_data(file):
def use_data_decorator(f):
@wraps(f)
def wrapper(*args):
with open(os.path.join('fixtures/data', file), 'r') as stream:
data = yaml.load(stream)
args = args + (data, )
return f(*args)
return wrapper
return use_data_decorator
| import unittest
import os
import yaml
from functools import wraps
from flask_jwt_simple import create_jwt
from cmd import init_db, seed_db
from models import db, Student
from scuevals_api import create_app
class TestCase(unittest.TestCase):
def setUp(self):
app = create_app()
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['TEST_DATABASE_URL']
app.testing = True
self.appx = app
self.app = app.test_client()
student = Student(
id=0,
email='[email protected]',
first_name='John',
last_name='Doe',
university_id=1
)
ident = {
'id': student.id,
'email': student.email,
'first_name': student.first_name,
'last_name': student.last_name
}
with app.app_context():
db.drop_all()
init_db(app, db)
seed_db(db)
db.session.add(student)
db.session.commit()
self.jwt = create_jwt(identity=ident)
def tearDown(self):
with self.appx.app_context():
db.session.remove()
db.drop_all()
def use_data(file):
def use_data_decorator(f):
@wraps(f)
def wrapper(*args):
with open(os.path.join('fixtures/data', file), 'r') as stream:
data = yaml.load(stream)
args = args + (data, )
return f(*args)
return wrapper
return use_data_decorator
| Add authentication to base TestCase | Add authentication to base TestCase
| Python | agpl-3.0 | SCUEvals/scuevals-api,SCUEvals/scuevals-api | ---
+++
@@ -2,8 +2,9 @@
import os
import yaml
from functools import wraps
+from flask_jwt_simple import create_jwt
from cmd import init_db, seed_db
-from models import db
+from models import db, Student
from scuevals_api import create_app
@@ -15,9 +16,30 @@
self.appx = app
self.app = app.test_client()
+ student = Student(
+ id=0,
+ email='[email protected]',
+ first_name='John',
+ last_name='Doe',
+ university_id=1
+ )
+
+ ident = {
+ 'id': student.id,
+ 'email': student.email,
+ 'first_name': student.first_name,
+ 'last_name': student.last_name
+ }
+
with app.app_context():
+ db.drop_all()
init_db(app, db)
seed_db(db)
+
+ db.session.add(student)
+ db.session.commit()
+
+ self.jwt = create_jwt(identity=ident)
def tearDown(self):
with self.appx.app_context(): |
ee3aac7a285cf5b80e8c836b9f825173bad2eb59 | doc/development/source/orange-demo/setup.py | doc/development/source/orange-demo/setup.py | from setuptools import setup
setup(name="Demo",
packages=["orangedemo"],
package_data={"orangedemo": ["icons/*.svg"]},
classifiers=["Example :: Invalid"],
# Declare orangedemo package to contain widgets for the "Demo" category
entry_points={"orange.widgets": ("Demo = orangedemo")},
) | from setuptools import setup
setup(name="Demo",
packages=["orangedemo"],
package_data={"orangedemo": ["icons/*.svg"]},
classifiers=["Example :: Invalid"],
# Declare orangedemo package to contain widgets for the "Demo" category
entry_points={"orange.widgets": "Demo = orangedemo"},
)
| Remove tuple, since string is sufficient here | Remove tuple, since string is sufficient here
As discovered in [discussion around issue #1184](https://github.com/biolab/orange3/issues/1184#issuecomment-214215811), the tuple is not necessary here. Only a single string is necessary, as is documented in the setuptools official [entry_points example](https://pythonhosted.org/setuptools/setuptools.html#dynamic-discovery-of-services-and-plugins). | Python | bsd-2-clause | cheral/orange3,qPCR4vir/orange3,qPCR4vir/orange3,cheral/orange3,qPCR4vir/orange3,cheral/orange3,qPCR4vir/orange3,cheral/orange3,cheral/orange3,qPCR4vir/orange3,qPCR4vir/orange3,cheral/orange3 | ---
+++
@@ -5,5 +5,5 @@
package_data={"orangedemo": ["icons/*.svg"]},
classifiers=["Example :: Invalid"],
# Declare orangedemo package to contain widgets for the "Demo" category
- entry_points={"orange.widgets": ("Demo = orangedemo")},
+ entry_points={"orange.widgets": "Demo = orangedemo"},
) |
9ed0848a869fc3a4e16890af609259d18b622056 | ideascaly/utils.py | ideascaly/utils.py | # IdeaScaly
# Copyright 2015 Jorge Saldivar
# See LICENSE for details.
import six
import dateutil.parser
from datetime import datetime
def parse_datetime(str_date):
date_is = dateutil.parser.parse(str_date)
return date_is
def parse_html_value(html):
return html[html.find('>')+1:html.rfind('<')]
def parse_a_href(atag):
start = atag.find('"') + 1
end = atag.find('"', start)
return atag[start:end]
def convert_to_utf8_str(arg):
# written by Michael Norton (http://docondev.blogspot.com/)
if isinstance(arg, six.text_type):
arg = arg.encode('utf-8')
elif not isinstance(arg, bytes):
arg = six.text_type(arg).encode('utf-8')
return arg
def import_simplejson():
try:
import simplejson as json
except ImportError:
try:
import json # Python 2.6+
except ImportError:
raise ImportError("Can't load a json library")
return json | # IdeaScaly
# Copyright 2015 Jorge Saldivar
# See LICENSE for details.
import six
import dateutil.parser
from datetime import datetime
def parse_datetime(str_date):
try:
date_is = dateutil.parser.parse(str_date)
return date_is
except:
print("Invalid date: %s" % str_date)
return None
def parse_html_value(html):
return html[html.find('>')+1:html.rfind('<')]
def parse_a_href(atag):
start = atag.find('"') + 1
end = atag.find('"', start)
return atag[start:end]
def convert_to_utf8_str(arg):
# written by Michael Norton (http://docondev.blogspot.com/)
if isinstance(arg, six.text_type):
arg = arg.encode('utf-8')
elif not isinstance(arg, bytes):
arg = six.text_type(arg).encode('utf-8')
return arg
def import_simplejson():
try:
import simplejson as json
except ImportError:
try:
import json # Python 2.6+
except ImportError:
raise ImportError("Can't load a json library")
return json | Add try except to the method that parse idea datetime | Add try except to the method that parse idea datetime
| Python | mit | joausaga/ideascaly | ---
+++
@@ -9,9 +9,12 @@
def parse_datetime(str_date):
- date_is = dateutil.parser.parse(str_date)
- return date_is
-
+ try:
+ date_is = dateutil.parser.parse(str_date)
+ return date_is
+ except:
+ print("Invalid date: %s" % str_date)
+ return None
def parse_html_value(html):
return html[html.find('>')+1:html.rfind('<')] |
811421407379dedc217795000f6f2cbe54510f96 | kolibri/core/utils/urls.py | kolibri/core/utils/urls.py | from django.urls import reverse
from six.moves.urllib.parse import urljoin
from kolibri.utils.conf import OPTIONS
def reverse_remote(
baseurl, viewname, urlconf=None, args=None, kwargs=None, current_app=None
):
# Get the reversed URL
reversed_url = reverse(
viewname, urlconf=urlconf, args=args, kwargs=kwargs, current_app=current_app
)
# Remove any configured URL prefix from the URL that is specific to this deployment
reversed_url = reversed_url.replace(OPTIONS["Deployment"]["URL_PATH_PREFIX"], "")
# Join the URL to baseurl, but remove any leading "/" to ensure that if there is a path prefix on baseurl
# it doesn't get ignored by the urljoin (which it would if the reversed_url had a leading '/',
# as it would be read as an absolute path)
return urljoin(baseurl, reversed_url.lstrip("/"))
| from django.urls import reverse
from six.moves.urllib.parse import urljoin
from kolibri.utils.conf import OPTIONS
def reverse_remote(
baseurl, viewname, urlconf=None, args=None, kwargs=None, current_app=None
):
# Get the reversed URL
reversed_url = reverse(
viewname, urlconf=urlconf, args=args, kwargs=kwargs, current_app=current_app
)
# Remove any configured URL prefix from the URL that is specific to this deployment
prefix_length = len(OPTIONS["Deployment"]["URL_PATH_PREFIX"])
reversed_url = reversed_url[prefix_length:]
# Join the URL to baseurl, but remove any leading "/" to ensure that if there is a path prefix on baseurl
# it doesn't get ignored by the urljoin (which it would if the reversed_url had a leading '/',
# as it would be read as an absolute path)
return urljoin(baseurl, reversed_url.lstrip("/"))
| Truncate rather than replace to prevent erroneous substitutions. | Truncate rather than replace to prevent erroneous substitutions.
| Python | mit | learningequality/kolibri,learningequality/kolibri,learningequality/kolibri,learningequality/kolibri | ---
+++
@@ -12,7 +12,8 @@
viewname, urlconf=urlconf, args=args, kwargs=kwargs, current_app=current_app
)
# Remove any configured URL prefix from the URL that is specific to this deployment
- reversed_url = reversed_url.replace(OPTIONS["Deployment"]["URL_PATH_PREFIX"], "")
+ prefix_length = len(OPTIONS["Deployment"]["URL_PATH_PREFIX"])
+ reversed_url = reversed_url[prefix_length:]
# Join the URL to baseurl, but remove any leading "/" to ensure that if there is a path prefix on baseurl
# it doesn't get ignored by the urljoin (which it would if the reversed_url had a leading '/',
# as it would be read as an absolute path) |
fe873844448d4123520e9bd6afe3231d4c952850 | job_runner/wsgi.py | job_runner/wsgi.py | """
WSGI config for job_runner project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "job_runner.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
| """
WSGI config for job_runner project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault(
"DJANGO_SETTINGS_MODULE", "job_runner.settings.env.development")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
| Update default settings to development. | Update default settings to development.
| Python | bsd-3-clause | spilgames/job-runner,spilgames/job-runner | ---
+++
@@ -15,7 +15,8 @@
"""
import os
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "job_runner.settings")
+os.environ.setdefault(
+ "DJANGO_SETTINGS_MODULE", "job_runner.settings.env.development")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION |
741133b4fa502fc585c771abef96b6213d3f5214 | pyheufybot/modules/nickservidentify.py | pyheufybot/modules/nickservidentify.py | from module_interface import Module, ModuleType
from message import IRCResponse, ResponseType
from pyheufybot import globalvars
class NickServIdentify(Module):
def __init__(self):
self.moduleType = ModuleType.PASSIVE
self.messageTypes = ["USER"]
self.helpText = "Attempts to log into NickServ with the password in the config"
def execute(self, message, serverInfo):
config = globalvars.botHandler.factories[serverInfo.name].config
passwordType = config.getSettingWithDefault("passwordType", None)
password = config.getSettingWithDefault("password", "")
if passwordType == "NickServ":
return [ IRCResponse("NickServ", password, responseType.MESSAGE) ]
else:
return []
| from pyheufybot.module_interface import Module, ModuleType
from pyheufybot.message import IRCResponse, ResponseType
from pyheufybot import globalvars
class NickServIdentify(Module):
def __init__(self):
self.moduleType = ModuleType.PASSIVE
self.messageTypes = ["USER"]
self.helpText = "Attempts to log into NickServ with the password in the config"
def execute(self, message, serverInfo):
config = globalvars.botHandler.factories[serverInfo.name].config
passwordType = config.getSettingWithDefault("passwordType", None)
password = config.getSettingWithDefault("password", "")
if passwordType == "NickServ":
return [ IRCResponse("NickServ", "IDENTIFY " + password, responseType.MESSAGE) ]
else:
return []
| Fix the syntax for NickServ logins | Fix the syntax for NickServ logins
| Python | mit | Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot | ---
+++
@@ -1,5 +1,5 @@
-from module_interface import Module, ModuleType
-from message import IRCResponse, ResponseType
+from pyheufybot.module_interface import Module, ModuleType
+from pyheufybot.message import IRCResponse, ResponseType
from pyheufybot import globalvars
class NickServIdentify(Module):
@@ -14,6 +14,6 @@
password = config.getSettingWithDefault("password", "")
if passwordType == "NickServ":
- return [ IRCResponse("NickServ", password, responseType.MESSAGE) ]
+ return [ IRCResponse("NickServ", "IDENTIFY " + password, responseType.MESSAGE) ]
else:
return [] |
34bd55b33e865c65386f934c7ac0b89f3cc76485 | edgedb/lang/common/shell/reqs.py | edgedb/lang/common/shell/reqs.py | ##
# Copyright (c) 2010 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
from metamagic import app
from metamagic.exceptions import MetamagicError
class UnsatisfiedRequirementError(MetamagicError):
pass
class CommandRequirement:
pass
class ValidApplication(CommandRequirement):
def __init__(self, args):
if not app.Application.active:
raise UnsatisfiedRequirementError('need active Application')
| ##
# Copyright (c) 2010 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
from metamagic.exceptions import MetamagicError
class UnsatisfiedRequirementError(MetamagicError):
pass
class CommandRequirement:
pass
| Drop 'metamagic.app' package. Long live Node. | app: Drop 'metamagic.app' package. Long live Node.
| Python | apache-2.0 | edgedb/edgedb,edgedb/edgedb,edgedb/edgedb | ---
+++
@@ -6,7 +6,6 @@
##
-from metamagic import app
from metamagic.exceptions import MetamagicError
@@ -16,9 +15,3 @@
class CommandRequirement:
pass
-
-
-class ValidApplication(CommandRequirement):
- def __init__(self, args):
- if not app.Application.active:
- raise UnsatisfiedRequirementError('need active Application') |
63a7b11d3ae51a944bf2e70637dea503e455c2f5 | fontdump/cli.py | fontdump/cli.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-#
from collections import OrderedDict
import requests
import cssutils
USER_AGENTS = OrderedDict()
USER_AGENTS['woff'] = 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome
USER_AGENTS['ttf'] = 'Mozilla/5.0 (Linux; U; Android 2.1-update1;)', #Andord 2
USER_AGENTS['eot'] = 'Mozilla/4.0 (compatible; MSIE 6.0;)', # IE6
USER_AGENTS['woff'] = 'Mozilla/4.0 (iPad; CPU OS 4_0_1 ) AppleWebKit', #iOS<4.2
def main():
font_url = 'http://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800|Dosis:300,400'
sheets={}
for (format, ua) in USER_AGENTS.items():
headers = {
'User-Agent': ua,
}
r =requests.get(font_url, headers=headers)
sheets[format] = cssutils.parseString(r.content)
if __name__ == '__main__':
main() | #!/usr/bin/env python
# -*- coding: utf-8 -*-#
import requests
import cssutils
USER_AGENTS = {
'woff': 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome
'eot': 'Mozilla/4.0 (compatible; MSIE 6.0;)', # IE6
'ttf': 'Mozilla/5.0 (Linux; U; Android 2.1-update1;)', #Andord 2
'svg': 'Mozilla/4.0 (iPad; CPU OS 4_0_1 ) AppleWebKit', #iOS<4.2
}
def main():
font_url = 'http://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800|Dosis:300,400'
sheets={}
for (format, ua) in USER_AGENTS.items():
headers = {
'User-Agent': ua,
}
r =requests.get(font_url, headers=headers)
sheets[format] = cssutils.parseString(r.content)
if __name__ == '__main__':
main() | Revert "The order of the formats matters. Use OrderedDict instead of dict" | Revert "The order of the formats matters. Use OrderedDict instead of dict"
I can't rely on the order of dict. The control flow is more complex.
This reverts commit 3389ed71971ddacd185bbbf8fe667a8651108c70.
| Python | mit | glasslion/fontdump | ---
+++
@@ -1,16 +1,14 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-#
-from collections import OrderedDict
-
import requests
import cssutils
-USER_AGENTS = OrderedDict()
-USER_AGENTS['woff'] = 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome
-USER_AGENTS['ttf'] = 'Mozilla/5.0 (Linux; U; Android 2.1-update1;)', #Andord 2
-USER_AGENTS['eot'] = 'Mozilla/4.0 (compatible; MSIE 6.0;)', # IE6
-USER_AGENTS['woff'] = 'Mozilla/4.0 (iPad; CPU OS 4_0_1 ) AppleWebKit', #iOS<4.2
-
+USER_AGENTS = {
+ 'woff': 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome
+ 'eot': 'Mozilla/4.0 (compatible; MSIE 6.0;)', # IE6
+ 'ttf': 'Mozilla/5.0 (Linux; U; Android 2.1-update1;)', #Andord 2
+ 'svg': 'Mozilla/4.0 (iPad; CPU OS 4_0_1 ) AppleWebKit', #iOS<4.2
+}
def main():
font_url = 'http://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800|Dosis:300,400' |
ff9d613897774f3125f2b28905528962b1761deb | core/timeline.py | core/timeline.py | from collections import Counter
from matplotlib import pyplot as plt
import datetime
def create_timeline( data ):
if len(data) == 0:
print "Dataset empty."
return
dates = map( lambda d: d['date'], data )
timeline_data = Counter( dates )
x_axis = sorted( timeline_data )
y_axis = []
for date in x_axis:
y_axis.append( timeline_data[date] )
plt.plot_date( x = x_axis, y = y_axis, fmt = "r-" )
ymin, ymax = plt.ylim()
plt.ylim( 0, ymax + 1 )
| from collections import Counter
from matplotlib import pyplot as plt
import datetime
import data_loader
def create_timeline( data ):
if len(data) == 0:
print "Dataset empty."
return
dates = map( lambda d: d['date'], data )
timeline_data = Counter( dates )
x_axis = sorted( timeline_data )
y_axis = []
for date in x_axis:
y_axis.append( timeline_data[date] )
plt.plot_date( x = x_axis, y = y_axis, fmt = "r-" )
ymin, ymax = plt.ylim()
plt.ylim( 0, ymax + 1 )
if __name__ == '__main__':
data = data_loader.load_facebook()
create_timeline(data)
plt.show()
| Add standalone method for using from command line | Add standalone method for using from command line
| Python | mit | HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core | ---
+++
@@ -1,6 +1,7 @@
from collections import Counter
from matplotlib import pyplot as plt
import datetime
+import data_loader
def create_timeline( data ):
if len(data) == 0:
@@ -18,3 +19,8 @@
plt.plot_date( x = x_axis, y = y_axis, fmt = "r-" )
ymin, ymax = plt.ylim()
plt.ylim( 0, ymax + 1 )
+
+if __name__ == '__main__':
+ data = data_loader.load_facebook()
+ create_timeline(data)
+ plt.show() |
18b89f719fd8d870448a5914e82b0364c5b9a1f5 | docs/tutorials/polls/mysite/settings.py | docs/tutorials/polls/mysite/settings.py | from lino.projects.std.settings import *
class Site(Site):
title = "Cool Polls"
def get_installed_apps(self):
yield super(Site, self).get_installed_apps()
yield 'polls'
def setup_menu(self, profile, main):
m = main.add_menu("polls", "Polls")
m.add_action('polls.Questions')
m.add_action('polls.Choices')
super(Site, self).setup_menu(profile, main)
SITE = Site(globals())
# your local settings here
DEBUG = True
| from lino.projects.std.settings import *
class Site(Site):
title = "Cool Polls"
demo_fixtures = ['demo', 'demo1']
def get_installed_apps(self):
yield super(Site, self).get_installed_apps()
yield 'polls'
def setup_menu(self, profile, main):
m = main.add_menu("polls", "Polls")
m.add_action('polls.Questions')
m.add_action('polls.Choices')
super(Site, self).setup_menu(profile, main)
SITE = Site(globals())
# your local settings here
DEBUG = True
| Use the available fixtures for demo_fixtures. | Use the available fixtures for demo_fixtures.
| Python | unknown | khchine5/book,khchine5/book,lino-framework/book,khchine5/book,lsaffre/lino_book,lsaffre/lino_book,lsaffre/lino_book,lino-framework/book,lino-framework/book,lino-framework/book | ---
+++
@@ -4,6 +4,8 @@
class Site(Site):
title = "Cool Polls"
+
+ demo_fixtures = ['demo', 'demo1']
def get_installed_apps(self):
yield super(Site, self).get_installed_apps() |
62f9608d50898d0a82e013d54454ed1edb004cff | fab_deploy/joyent/setup.py | fab_deploy/joyent/setup.py | from fabric.api import run, sudo
from fabric.contrib.files import append
from fab_deploy.base import setup as base_setup
class JoyentMixin(object):
def _set_profile(self):
append('/etc/profile', 'CC="gcc -m64"; export CC', use_sudo=True)
append('/etc/profile', 'LDSHARED="gcc -m64 -G"; export LDSHARED', use_sudo=True)
def _ssh_restart(self):
run('svcadm restart ssh')
class AppMixin(JoyentMixin):
packages = ['python27', 'py27-psycopg2', 'py27-setuptools',
'py27-imaging', 'py27-expat']
def _install_packages(self):
for package in self.packages:
sudo('pkg_add %s' % package)
sudo('easy_install-2.7 pip')
self._install_venv()
class LBSetup(JoyentMixin, base_setup.LBSetup):
pass
class AppSetup(AppMixin, base_setup.AppSetup):
pass
class DBSetup(JoyentMixin, base_setup.DBSetup):
pass
class SlaveSetup(JoyentMixin, base_setup.SlaveSetup):
pass
class DevSetup(AppMixin, base_setup.DevSetup):
pass
app_server = AppSetup()
lb_server = LBSetup()
dev_server = DevSetup()
db_server = DBSetup()
slave_db = SlaveSetup()
| from fabric.api import run, sudo
from fabric.contrib.files import append
from fab_deploy.base import setup as base_setup
class JoyentMixin(object):
def _set_profile(self):
append('/etc/profile', 'CC="gcc -m64"; export CC', use_sudo=True)
append('/etc/profile', 'LDSHARED="gcc -m64 -G"; export LDSHARED', use_sudo=True)
def _ssh_restart(self):
run('svcadm restart ssh')
class AppMixin(JoyentMixin):
packages = ['python27', 'py27-psycopg2', 'py27-setuptools',
'py27-imaging', 'py27-expat']
def _set_profile(self):
JoyentMixin._set_profile(self)
base_setup.AppSetup._set_profile(self)
def _install_packages(self):
for package in self.packages:
sudo('pkg_add %s' % package)
sudo('easy_install-2.7 pip')
self._install_venv()
class LBSetup(JoyentMixin, base_setup.LBSetup):
pass
class AppSetup(AppMixin, base_setup.AppSetup):
pass
class DBSetup(JoyentMixin, base_setup.DBSetup):
pass
class SlaveSetup(JoyentMixin, base_setup.SlaveSetup):
pass
class DevSetup(AppMixin, base_setup.DevSetup):
pass
app_server = AppSetup()
lb_server = LBSetup()
dev_server = DevSetup()
db_server = DBSetup()
slave_db = SlaveSetup()
| Add environ vars for joyent | Add environ vars for joyent | Python | mit | ff0000/red-fab-deploy2,ff0000/red-fab-deploy2,ff0000/red-fab-deploy2 | ---
+++
@@ -16,6 +16,10 @@
class AppMixin(JoyentMixin):
packages = ['python27', 'py27-psycopg2', 'py27-setuptools',
'py27-imaging', 'py27-expat']
+
+ def _set_profile(self):
+ JoyentMixin._set_profile(self)
+ base_setup.AppSetup._set_profile(self)
def _install_packages(self):
for package in self.packages: |
678054b5c890456b903eb43b08855091288d12cc | osfoffline/settings/defaults.py | osfoffline/settings/defaults.py | # Just to insure requirement
import colorlog # noqa
# Development mode: use a local OSF dev version and more granular logging
DEV_MODE = False # TODO (abought): auto-set flag when using `inv start_for_tests`
# General settings
PROJECT_NAME = 'osf-offline'
PROJECT_AUTHOR = 'cos'
APPLICATION_SCOPES = 'osf.full_write'
# Base URL for API server; used to fetch data
API_BASE = 'https://api.osf.io'
FILE_BASE = 'https://files.osf.io'
# Interval (in seconds) to poll the OSF for server-side file changes
# YEARS * DAYS * HOURS * MIN * SECONDS
POLL_DELAY = 20 * 365 * 24 * 60 * 60 # 20 years in seconds
# Time to keep alert messages on screen (in milliseconds); may not be configurable on all platforms
ALERT_TIME = 1000 # ms
LOG_LEVEL = 'INFO'
# Logging configuration
CONSOLE_FORMATTER = {
'()': 'colorlog.ColoredFormatter',
'format': '%(cyan)s[%(asctime)s]%(log_color)s[%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(reset)s%(message)s'
}
FILE_FORMATTER = '[%(asctime)s][%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(message)s'
| # Just to insure requirement
import colorlog # noqa
# Development mode: use a local OSF dev version and more granular logging
DEV_MODE = False # TODO (abought): auto-set flag when using `inv start_for_tests`
# General settings
PROJECT_NAME = 'osf-offline'
PROJECT_AUTHOR = 'cos'
APPLICATION_SCOPES = 'osf.full_write'
# Base URL for API server; used to fetch data
API_BASE = 'https://api.osf.io'
FILE_BASE = 'https://files.osf.io'
# Interval (in seconds) to poll the OSF for server-side file changes
POLL_DELAY = 24 * 60 * 60 # Once per day
# Time to keep alert messages on screen (in milliseconds); may not be configurable on all platforms
ALERT_TIME = 1000 # ms
LOG_LEVEL = 'INFO'
# Logging configuration
CONSOLE_FORMATTER = {
'()': 'colorlog.ColoredFormatter',
'format': '%(cyan)s[%(asctime)s]%(log_color)s[%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(reset)s%(message)s'
}
FILE_FORMATTER = '[%(asctime)s][%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(message)s'
| Use max poll delay to avoid OSErrors | Use max poll delay to avoid OSErrors
| Python | apache-2.0 | chennan47/OSF-Offline,chennan47/OSF-Offline | ---
+++
@@ -14,8 +14,7 @@
FILE_BASE = 'https://files.osf.io'
# Interval (in seconds) to poll the OSF for server-side file changes
-# YEARS * DAYS * HOURS * MIN * SECONDS
-POLL_DELAY = 20 * 365 * 24 * 60 * 60 # 20 years in seconds
+POLL_DELAY = 24 * 60 * 60 # Once per day
# Time to keep alert messages on screen (in milliseconds); may not be configurable on all platforms
ALERT_TIME = 1000 # ms |
fc3cf6966f66f0929c48b1f24bede295fb3aec35 | Wahji-dev/setup/removeWahji.py | Wahji-dev/setup/removeWahji.py | #deletes wahji content
import os, shutil, platform
def rem(loc):
os.chdir(loc)
print "deleting content"
"""delete them folder and its contents"""
shutil.rmtree("themes")
"""delete .wahji file"""
os.remove(".wahji")
"""delete 4040.html file"""
os.remove("404.html")
"""delete content folder"""
shutil.rmtree("content")
| #deletes wahji content
import os, shutil, platform
def rem(loc):
os.chdir(loc)
site = raw_input("Input site folder: ")
print "Are you sure you want to delete", site, "Y/N: "
confirm = raw_input()
if confirm == "Y" or confirm == "y":
"""delete site folder"""
shutil.rmtree(site)
print "Deleting site"
elif confirm == "N" or confirm == "n":
print "Site folder was not deleted"
| Remove now asks for site file to be deleted | Remove now asks for site file to be deleted
| Python | mit | mborn319/Wahji,mborn319/Wahji,mborn319/Wahji | ---
+++
@@ -5,17 +5,16 @@
os.chdir(loc)
- print "deleting content"
-
- """delete them folder and its contents"""
- shutil.rmtree("themes")
+ site = raw_input("Input site folder: ")
- """delete .wahji file"""
- os.remove(".wahji")
+ print "Are you sure you want to delete", site, "Y/N: "
+ confirm = raw_input()
+
+ if confirm == "Y" or confirm == "y":
+ """delete site folder"""
+ shutil.rmtree(site)
+ print "Deleting site"
- """delete 4040.html file"""
- os.remove("404.html")
+ elif confirm == "N" or confirm == "n":
+ print "Site folder was not deleted"
- """delete content folder"""
- shutil.rmtree("content")
- |
bff72be24e44cec1d819de630afb91868fadeaa5 | luminoso_api/compat.py | luminoso_api/compat.py | import sys
# Detect Python 3
PY3 = (sys.hexversion >= 0x03000000)
if PY3:
types_not_to_encode = (int, str)
string_type = str
from urllib.parse import urlparse
else:
types_not_to_encode = (int, long, basestring)
string_type = basestring
from urllib2 import urlparse
| import sys
# Detect Python 3
PY3 = (sys.hexversion >= 0x03000000)
if PY3:
types_not_to_encode = (int, str)
string_type = str
from urllib.parse import urlparse
else:
types_not_to_encode = (int, long, basestring)
string_type = basestring
from urlparse import urlparse
| Fix the urlparse import in Python 2. (This is used for saving/loading tokens in files.) The urlparse that you can import from urllib2 is actually the urlparse module, but what we want is the urlparse function inside that module. | Fix the urlparse import in Python 2. (This is used for saving/loading tokens in files.) The urlparse that you can import from urllib2 is actually the urlparse module, but what we want is the urlparse function inside that module.
| Python | mit | LuminosoInsight/luminoso-api-client-python | ---
+++
@@ -10,4 +10,4 @@
else:
types_not_to_encode = (int, long, basestring)
string_type = basestring
- from urllib2 import urlparse
+ from urlparse import urlparse |
6b55f079d595700cd84d12d4f351e52614d291c5 | openacademy/model/openacademy_session.py | openacademy/model/openacademy_session.py | # -*- coding: utf-8 -*-
from openerp import fields,models
class Session(models.Model):
_name = 'openacademy.session'
name = fields.Char(required=True)
start_date = fields.Date()
duration = fields.Float(digits=(6,2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
instructor_id = fields.Many2one('res.partner', string="Instructor")
course_id = fields.Many2one('openacademy.course',
ondelete='cascade', string="Course", required=True)
attendee_ids = fields.Many2many('res.partner', string='Attendees')
| # -*- coding: utf-8 -*-
from openerp import fields,models
class Session(models.Model):
_name = 'openacademy.session'
name = fields.Char(required=True)
start_date = fields.Date()
duration = fields.Float(digits=(6,2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
instructor_id = fields.Many2one('res.partner', string="Instructor",
domain = ['|',
('instructor', '=', True),
('category_id.name', 'ilike', "Teacher")])
course_id = fields.Many2one('openacademy.course',
ondelete='cascade', string="Course", required=True)
attendee_ids = fields.Many2many('res.partner', string='Attendees')
| Add domain ir and ilike | [REF] openacademy: Add domain ir and ilike
| Python | apache-2.0 | arogel/openacademy-project | ---
+++
@@ -8,7 +8,11 @@
start_date = fields.Date()
duration = fields.Float(digits=(6,2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
- instructor_id = fields.Many2one('res.partner', string="Instructor")
+
+ instructor_id = fields.Many2one('res.partner', string="Instructor",
+ domain = ['|',
+ ('instructor', '=', True),
+ ('category_id.name', 'ilike', "Teacher")])
course_id = fields.Many2one('openacademy.course',
ondelete='cascade', string="Course", required=True)
attendee_ids = fields.Many2many('res.partner', string='Attendees') |
429716ef6d15e0c7e49174409b8195eb8ef14b26 | back-end/BAA/settings/prod.py | back-end/BAA/settings/prod.py | from .common import *
import dj_database_url
# Settings for production environment
DEBUG = False
# Update database configuration with $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
ALLOWED_HOSTS = ['floating-castle-71814.herokuapp.com'] # apparently you need to have this
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'ERROR'),
},
},
}
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = os.getenv('SENDGRID_USERNAME')
EMAIL_HOST_PASSWORD = os.getenv('SENDGRID_PASSWORD')
EMAIL_PORT = 587
EMAIL_USE_TLS = True
FROM_EMAIL = '[email protected]'
DOMAIN = 'http://floating-castle-71814.herokuapp.com/'
| from .common import *
import dj_database_url
# Settings for production environment
DEBUG = False
# Update database configuration with $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
ALLOWED_HOSTS = ['floating-castle-71814.herokuapp.com'] # apparently you need to have this
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'ERROR'),
},
},
}
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = os.getenv('SENDGRID_USERNAME')
EMAIL_HOST_PASSWORD = os.getenv('SENDGRID_PASSWORD')
EMAIL_PORT = 587
EMAIL_USE_TLS = True
FROM_EMAIL = '[email protected]'
DOMAIN = 'http://floating-castle-71814.herokuapp.com/'
SECRET_KEY = os.getenv('DJANGO_SECRETKEY') | Change to a secret secret key | Change to a secret secret key
| Python | mit | jumbocodespring2017/bostonathleticsassociation,jumbocodespring2017/bostonathleticsassociation,jumbocodespring2017/bostonathleticsassociation | ---
+++
@@ -39,3 +39,5 @@
EMAIL_USE_TLS = True
FROM_EMAIL = '[email protected]'
DOMAIN = 'http://floating-castle-71814.herokuapp.com/'
+
+SECRET_KEY = os.getenv('DJANGO_SECRETKEY') |
91d104a25db499ccef54878dcbfce42dbb4aa932 | taskin/task.py | taskin/task.py | import abc
def do_flow(flow, result=None):
for item in flow:
print(item, result)
result = item(result)
return result
class MapTask(object):
def __init__(self, args, task):
self.args = args
self.task = task
self.pool = Pool(cpu_count())
def iter_input(self, input):
for args in self.args:
if not isinstance(args, (tuple, list)):
args = [args]
yield tuple([input] + args)
def __call__(self, input):
return self.pool.map(self.task, self.iter_input(input))
class IfTask(object):
def __init__(self, check, a, b):
self.check = check
self.a = a
self.b = b
def __call__(self, input):
if check(input):
return do_flow(self.a, input)
return do_flow(self.b, input)
| from multiprocessing import Pool as ProcessPool
from multiprocessing.dummy import Pool as ThreadPool
from multiprocessing import cpu_count
def do_flow(flow, result=None):
for item in flow:
print(item, result)
result = item(result)
return result
class PoolAPI(object):
def map(self, *args, **kw):
return self.pool.map(*args, **kw)
class ThreadPool(PoolAPI):
def __init__(self, size=20):
self.size = size
self.pool = ThreadPool(self.size)
class ProcessPool(PoolAPI):
def __init__(self, size=None):
self.size = size or cpu_count()
self.pool = ProcessPool(self.size)
class MapTask(object):
pool_types = [
'thread', 'process'
]
def __init__(self, args, task, pool):
self.args = args
self.task = task
self.pool = pool
def iter_input(self, input):
for args in self.args:
if not isinstance(args, (tuple, list)):
args = [args]
yield tuple([input] + args)
def __call__(self, input):
return self.pool.map(self.task, self.iter_input(input))
class IfTask(object):
def __init__(self, check, a, b):
self.check = check
self.a = a
self.b = b
def __call__(self, input):
if check(input):
return do_flow(self.a, input)
return do_flow(self.b, input)
| Add totally untested pools ;) | Add totally untested pools ;)
| Python | bsd-3-clause | ionrock/taskin | ---
+++
@@ -1,4 +1,6 @@
-import abc
+from multiprocessing import Pool as ProcessPool
+from multiprocessing.dummy import Pool as ThreadPool
+from multiprocessing import cpu_count
def do_flow(flow, result=None):
@@ -8,19 +10,41 @@
return result
+class PoolAPI(object):
+ def map(self, *args, **kw):
+ return self.pool.map(*args, **kw)
+
+
+class ThreadPool(PoolAPI):
+
+ def __init__(self, size=20):
+ self.size = size
+ self.pool = ThreadPool(self.size)
+
+
+class ProcessPool(PoolAPI):
+
+ def __init__(self, size=None):
+ self.size = size or cpu_count()
+ self.pool = ProcessPool(self.size)
+
+
class MapTask(object):
- def __init__(self, args, task):
+ pool_types = [
+ 'thread', 'process'
+ ]
+
+ def __init__(self, args, task, pool):
self.args = args
self.task = task
- self.pool = Pool(cpu_count())
+ self.pool = pool
def iter_input(self, input):
for args in self.args:
if not isinstance(args, (tuple, list)):
args = [args]
yield tuple([input] + args)
-
def __call__(self, input):
return self.pool.map(self.task, self.iter_input(input)) |
247c4dcaf3e1c1f9c069ab8a2fc06cfcd75f8ea9 | UM/Util.py | UM/Util.py | # Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
## Convert a value to a boolean
#
# \param \type{bool|str|int} any value.
# \return \type{bool}
def parseBool(value):
return value in [True, "True", "true", 1]
| # Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
## Convert a value to a boolean
#
# \param \type{bool|str|int} any value.
# \return \type{bool}
def parseBool(value):
return value in [True, "True", "true", "Yes", "yes", 1]
| Add "Yes" as an option for parsing bools | Add "Yes" as an option for parsing bools
CURA-2204
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | ---
+++
@@ -6,4 +6,4 @@
# \param \type{bool|str|int} any value.
# \return \type{bool}
def parseBool(value):
- return value in [True, "True", "true", 1]
+ return value in [True, "True", "true", "Yes", "yes", 1] |
6e3ddfc47487a8841a79d6265c96ba63005fccec | bnw_handlers/command_onoff.py | bnw_handlers/command_onoff.py | # -*- coding: utf-8 -*-
#from twisted.words.xish import domish
from base import *
import random
import bnw_core.bnw_objects as objs
@require_auth
@defer.inlineCallbacks
def cmd_on(request):
""" Включение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':False}},safe=True)
if request.user['off']:
defer.returnValue(
dict(ok=True,desc='Welcome back!')
)
else:
defer.returnValue(
dict(ok=True,desc='Welcoooome baaaack, I said.')
)
@require_auth
@defer.inlineCallbacks
def cmd_off(request):
""" Выключение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':True}},safe=True)
if request.user['off']:
defer.returnValue(
dict(ok=True,desc='See you later.')
)
else:
defer.returnValue(
dict(ok=True,desc='C u l8r!')
)
| # -*- coding: utf-8 -*-
#from twisted.words.xish import domish
from base import *
import random
import bnw_core.bnw_objects as objs
@require_auth
@defer.inlineCallbacks
def cmd_on(request):
""" Включение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':False}},safe=True)
if request.user.get('off',False):
defer.returnValue(
dict(ok=True,desc='Welcome back!')
)
else:
defer.returnValue(
dict(ok=True,desc='Welcoooome baaaack, I said.')
)
@require_auth
@defer.inlineCallbacks
def cmd_off(request):
""" Выключение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':True}},safe=True)
if request.user.get('off',False):
defer.returnValue(
dict(ok=True,desc='See you later.')
)
else:
defer.returnValue(
dict(ok=True,desc='C u l8r!')
)
| Fix on/off if there is no 'off' field. | Fix on/off if there is no 'off' field.
| Python | bsd-2-clause | un-def/bnw,stiletto/bnw,un-def/bnw,stiletto/bnw,ojab/bnw,ojab/bnw,stiletto/bnw,un-def/bnw,ojab/bnw,stiletto/bnw,un-def/bnw,ojab/bnw | ---
+++
@@ -11,7 +11,7 @@
def cmd_on(request):
""" Включение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':False}},safe=True)
- if request.user['off']:
+ if request.user.get('off',False):
defer.returnValue(
dict(ok=True,desc='Welcome back!')
)
@@ -25,7 +25,7 @@
def cmd_off(request):
""" Выключение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':True}},safe=True)
- if request.user['off']:
+ if request.user.get('off',False):
defer.returnValue(
dict(ok=True,desc='See you later.')
) |
bbef6c5f235fc3320c9c748a32cb3af04d3903d1 | list_all_users_in_group.py | list_all_users_in_group.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import grp
import pwd
import inspect
import argparse
def list_all_users_in_group(groupname):
"""Get list of all users of group.
Get sorted list of all users of group GROUP,
including users with main group GROUP.
Origin in https://github.com/vazhnov/list_all_users_in_group
"""
try:
group = grp.getgrnam(groupname)
# On error "KeyError: 'getgrnam(): name not found: GROUP'"
except (KeyError):
return None
group_all_users_set = set(group.gr_mem)
for user in pwd.getpwall():
if user.pw_gid == group.gr_gid:
group_all_users_set.add(user.pw_name)
return sorted(group_all_users_set)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=inspect.getdoc(list_all_users_in_group),
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-d', '--delimiter', default='\n', help='Use DELIMITER instead of newline for users delimiter')
parser.add_argument('groupname', help='Group name')
args = parser.parse_args()
result = list_all_users_in_group(args.groupname)
if result:
print (args.delimiter.join(result))
| #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import grp
import pwd
import inspect
import argparse
def list_all_users_in_group(groupname):
"""Get list of all users of group.
Get sorted list of all users of group GROUP,
including users with main group GROUP.
Origin in https://github.com/vazhnov/list_all_users_in_group
"""
try:
group = grp.getgrnam(groupname)
# On error "KeyError: 'getgrnam(): name not found: GROUP'"
except KeyError:
return None
group_all_users_set = set(group.gr_mem)
for user in pwd.getpwall():
if user.pw_gid == group.gr_gid:
group_all_users_set.add(user.pw_name)
return sorted(group_all_users_set)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=inspect.getdoc(list_all_users_in_group),
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-d', '--delimiter', default='\n', help='Use DELIMITER instead of newline for users delimiter')
parser.add_argument('groupname', help='Group name')
args = parser.parse_args()
result = list_all_users_in_group(args.groupname)
if result:
print (args.delimiter.join(result))
| Fix pylint: Unnecessary parens after u'print' keyword (superfluous-parens) | Fix pylint: Unnecessary parens after u'print' keyword (superfluous-parens)
| Python | cc0-1.0 | vazhnov/list_all_users_in_group | ---
+++
@@ -1,6 +1,7 @@
#! /usr/bin/env python
# -*- coding: utf-8 -*-
+from __future__ import print_function
import grp
import pwd
import inspect
@@ -18,7 +19,7 @@
try:
group = grp.getgrnam(groupname)
# On error "KeyError: 'getgrnam(): name not found: GROUP'"
- except (KeyError):
+ except KeyError:
return None
group_all_users_set = set(group.gr_mem)
for user in pwd.getpwall(): |
82e82805eae5b070aec49816977d2f50ff274d30 | controllers/api/api_match_controller.py | controllers/api/api_match_controller.py | import json
import webapp2
from controllers.api.api_base_controller import ApiBaseController
from helpers.model_to_dict import ModelToDict
from models.match import Match
class ApiMatchControllerBase(ApiBaseController):
CACHE_KEY_FORMAT = "apiv2_match_controller_{}" # (match_key)
CACHE_VERSION = 2
CACHE_HEADER_LENGTH = 60 * 60
def __init__(self, *args, **kw):
super(ApiMatchControllerBase, self).__init__(*args, **kw)
self.match_key = self.request.route_kwargs["match_key"]
self._partial_cache_key = self.CACHE_KEY_FORMAT.format(self.match_key)
@property
def _validators(self):
return [("match_id_validator", self.match_key)]
def _set_match(self, match_key):
self.match = Match.get_by_id(match_key)
if self.match is None:
self._errors = json.dumps({"404": "%s match not found" % self.match_key})
self.abort(404)
class ApiMatchController(ApiMatchControllerBase):
def _track_call(self, match_key):
self._track_call_defer('match', match_key)
def _render(self, match_key):
self._set_match(match_key)
match_dict = ModelToDict.matchConverter(self.match)
return json.dumps(match_dict, ensure_ascii=True)
| import json
import webapp2
from controllers.api.api_base_controller import ApiBaseController
from helpers.model_to_dict import ModelToDict
from models.match import Match
class ApiMatchControllerBase(ApiBaseController):
def __init__(self, *args, **kw):
super(ApiMatchControllerBase, self).__init__(*args, **kw)
self.match_key = self.request.route_kwargs["match_key"]
@property
def _validators(self):
return [("match_id_validator", self.match_key)]
def _set_match(self, match_key):
self.match = Match.get_by_id(match_key)
if self.match is None:
self._errors = json.dumps({"404": "%s match not found" % self.match_key})
self.abort(404)
class ApiMatchController(ApiMatchControllerBase):
CACHE_KEY_FORMAT = "apiv2_match_controller_{}" # (match_key)
CACHE_VERSION = 2
CACHE_HEADER_LENGTH = 60 * 60
def __init__(self, *args, **kw):
super(ApiMatchController, self).__init__(*args, **kw)
self._partial_cache_key = self.CACHE_KEY_FORMAT.format(self.match_key)
def _track_call(self, match_key):
self._track_call_defer('match', match_key)
def _render(self, match_key):
self._set_match(match_key)
match_dict = ModelToDict.matchConverter(self.match)
return json.dumps(match_dict, ensure_ascii=True)
| Move cache key out of base class | Move cache key out of base class
| Python | mit | josephbisch/the-blue-alliance,bvisness/the-blue-alliance,bdaroz/the-blue-alliance,bvisness/the-blue-alliance,fangeugene/the-blue-alliance,1fish2/the-blue-alliance,phil-lopreiato/the-blue-alliance,synth3tk/the-blue-alliance,jaredhasenklein/the-blue-alliance,tsteward/the-blue-alliance,nwalters512/the-blue-alliance,phil-lopreiato/the-blue-alliance,the-blue-alliance/the-blue-alliance,1fish2/the-blue-alliance,jaredhasenklein/the-blue-alliance,tsteward/the-blue-alliance,verycumbersome/the-blue-alliance,tsteward/the-blue-alliance,jaredhasenklein/the-blue-alliance,jaredhasenklein/the-blue-alliance,the-blue-alliance/the-blue-alliance,phil-lopreiato/the-blue-alliance,bdaroz/the-blue-alliance,bvisness/the-blue-alliance,the-blue-alliance/the-blue-alliance,phil-lopreiato/the-blue-alliance,tsteward/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,bdaroz/the-blue-alliance,josephbisch/the-blue-alliance,fangeugene/the-blue-alliance,bdaroz/the-blue-alliance,synth3tk/the-blue-alliance,fangeugene/the-blue-alliance,nwalters512/the-blue-alliance,bvisness/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,josephbisch/the-blue-alliance,nwalters512/the-blue-alliance,bvisness/the-blue-alliance,synth3tk/the-blue-alliance,the-blue-alliance/the-blue-alliance,bdaroz/the-blue-alliance,nwalters512/the-blue-alliance,the-blue-alliance/the-blue-alliance,the-blue-alliance/the-blue-alliance,bvisness/the-blue-alliance,tsteward/the-blue-alliance,tsteward/the-blue-alliance,josephbisch/the-blue-alliance,jaredhasenklein/the-blue-alliance,1fish2/the-blue-alliance,1fish2/the-blue-alliance,1fish2/the-blue-alliance,josephbisch/the-blue-alliance,synth3tk/the-blue-alliance,nwalters512/the-blue-alliance,synth3tk/the-blue-alliance,josephbisch/the-blue-alliance,fangeugene/the-blue-alliance,phil-lopreiato/the-blue-alliance,1fish2/the-blue-alliance,verycumbersome/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,synth3tk/the-blue-alliance,verycumbersome/the-blue-alliance,nwalters512/the-blue-alliance,phil-lopreiato/the-blue-alliance,bdaroz/the-blue-alliance | ---
+++
@@ -10,14 +10,9 @@
class ApiMatchControllerBase(ApiBaseController):
- CACHE_KEY_FORMAT = "apiv2_match_controller_{}" # (match_key)
- CACHE_VERSION = 2
- CACHE_HEADER_LENGTH = 60 * 60
-
def __init__(self, *args, **kw):
super(ApiMatchControllerBase, self).__init__(*args, **kw)
self.match_key = self.request.route_kwargs["match_key"]
- self._partial_cache_key = self.CACHE_KEY_FORMAT.format(self.match_key)
@property
def _validators(self):
@@ -32,6 +27,14 @@
class ApiMatchController(ApiMatchControllerBase):
+ CACHE_KEY_FORMAT = "apiv2_match_controller_{}" # (match_key)
+ CACHE_VERSION = 2
+ CACHE_HEADER_LENGTH = 60 * 60
+
+ def __init__(self, *args, **kw):
+ super(ApiMatchController, self).__init__(*args, **kw)
+ self._partial_cache_key = self.CACHE_KEY_FORMAT.format(self.match_key)
+
def _track_call(self, match_key):
self._track_call_defer('match', match_key)
|
b2771e6b33bd889c971b77e1b30c1cc5a0b9eb24 | platform.py | platform.py | # Copyright 2014-present PlatformIO <[email protected]>
#
# 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 platformio.managers.platform import PlatformBase
class Ststm32Platform(PlatformBase):
def configure_default_packages(self, variables, targets):
board = variables.get("board")
if "mbed" in variables.get("pioframework",
[]) or board == "mxchip_az3166":
self.packages['toolchain-gccarmnoneeabi'][
'version'] = ">=1.60301.0"
if board == "mxchip_az3166":
self.frameworks['arduino'][
'script'] = "builder/frameworks/arduino/mxchip.py"
self.packages['tool-openocd']['type'] = "uploader"
return PlatformBase.configure_default_packages(self, variables,
targets)
| # Copyright 2014-present PlatformIO <[email protected]>
#
# 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 platformio.managers.platform import PlatformBase
class Ststm32Platform(PlatformBase):
def configure_default_packages(self, variables, targets):
board = variables.get("board")
if "mbed" in variables.get("pioframework",
[]) or board == "mxchip_az3166":
self.packages['toolchain-gccarmnoneeabi'][
'version'] = ">=1.60301.0"
if board == "mxchip_az3166":
self.frameworks['arduino'][
'package'] = "framework-arduinostm32mxchip"
self.frameworks['arduino'][
'script'] = "builder/frameworks/arduino/mxchip.py"
self.packages['tool-openocd']['type'] = "uploader"
return PlatformBase.configure_default_packages(self, variables,
targets)
| Use appropriate package for mxchip_az3166 | Use appropriate package for mxchip_az3166
| Python | apache-2.0 | platformio/platform-ststm32,platformio/platform-ststm32 | ---
+++
@@ -26,6 +26,8 @@
if board == "mxchip_az3166":
self.frameworks['arduino'][
+ 'package'] = "framework-arduinostm32mxchip"
+ self.frameworks['arduino'][
'script'] = "builder/frameworks/arduino/mxchip.py"
self.packages['tool-openocd']['type'] = "uploader" |
1096d0f13ebbc5900c21626a5caf6276b36229d8 | Lib/test/test_coding.py | Lib/test/test_coding.py |
import test.test_support, unittest
import os
class CodingTest(unittest.TestCase):
def test_bad_coding(self):
module_name = 'bad_coding'
self.verify_bad_module(module_name)
def test_bad_coding2(self):
module_name = 'bad_coding2'
self.verify_bad_module(module_name)
def verify_bad_module(self, module_name):
self.assertRaises(SyntaxError, __import__, 'test.' + module_name)
path = os.path.dirname(__file__)
filename = os.path.join(path, module_name + '.py')
fp = open(filename)
text = fp.read()
fp.close()
self.assertRaises(SyntaxError, compile, text, filename, 'exec')
def test_exec_valid_coding(self):
d = {}
exec('# coding: cp949\na = 5\n', d)
self.assertEqual(d['a'], 5)
def test_main():
test.test_support.run_unittest(CodingTest)
if __name__ == "__main__":
test_main()
|
import test.test_support, unittest
import os
class CodingTest(unittest.TestCase):
def test_bad_coding(self):
module_name = 'bad_coding'
self.verify_bad_module(module_name)
def test_bad_coding2(self):
module_name = 'bad_coding2'
self.verify_bad_module(module_name)
def verify_bad_module(self, module_name):
self.assertRaises(SyntaxError, __import__, 'test.' + module_name)
path = os.path.dirname(__file__)
filename = os.path.join(path, module_name + '.py')
fp = open(filename, encoding='utf-8')
text = fp.read()
fp.close()
self.assertRaises(SyntaxError, compile, text, filename, 'exec')
def test_exec_valid_coding(self):
d = {}
exec('# coding: cp949\na = 5\n', d)
self.assertEqual(d['a'], 5)
def test_main():
test.test_support.run_unittest(CodingTest)
if __name__ == "__main__":
test_main()
| Fix a test failure on non-UTF-8 locales: bad_coding2.py is encoded in utf-8. | Fix a test failure on non-UTF-8 locales: bad_coding2.py is encoded
in utf-8.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -16,7 +16,7 @@
path = os.path.dirname(__file__)
filename = os.path.join(path, module_name + '.py')
- fp = open(filename)
+ fp = open(filename, encoding='utf-8')
text = fp.read()
fp.close()
self.assertRaises(SyntaxError, compile, text, filename, 'exec') |
37588d466928e9f25b55d627772120f16df095ec | model_presenter.py | model_presenter.py | import matplotlib
# Do not use X for plotting
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from matplotlib.ticker import FormatStrFormatter
from tempfile import NamedTemporaryFile
def plot_to_file(symbol, timestamp, close, score):
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(timestamp, close, color='r', marker='.', label="close")
ax2.plot(timestamp, score, color='b', marker='.', label="score")
plt.title("%s: score %0.2f" % (symbol, score[-1]))
fig.autofmt_xdate()
ax1.xaxis.set_major_formatter(DateFormatter("%H:%M"))
ax1.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
ax1.legend(h1 + h2, l1 + l2)
png_file = NamedTemporaryFile(delete=False, suffix='.png')
png_file.close()
fig.set_dpi(100)
fig.set_size_inches(10, 4)
fig.set_tight_layout(True)
fig.savefig(png_file.name)
plt.close(fig)
return png_file.name
| import matplotlib
# Do not use X for plotting
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from matplotlib.ticker import FormatStrFormatter
from tempfile import NamedTemporaryFile
def plot_to_file(symbol, timestamp, close, score):
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(timestamp, close, color='r', marker='.', label="close")
ax2.plot(timestamp, score, color='b', marker='.', label="score")
plt.title("%s: score %0.2f" % (symbol, score[-1]))
fig.autofmt_xdate()
ax1.xaxis.set_major_formatter(DateFormatter("%H:%M"))
ax1.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
ax1.legend(h1 + h2, l1 + l2)
jpg_file = NamedTemporaryFile(delete=False, suffix='.jpg')
jpg_file.close()
fig.set_dpi(100)
fig.set_size_inches(10, 4)
fig.set_tight_layout(True)
fig.savefig(jpg_file.name, quality=50)
plt.close(fig)
return jpg_file.name
| Compress the images to be sent | Compress the images to be sent
| Python | mit | cjluo/money-monkey | ---
+++
@@ -23,13 +23,13 @@
h2, l2 = ax2.get_legend_handles_labels()
ax1.legend(h1 + h2, l1 + l2)
- png_file = NamedTemporaryFile(delete=False, suffix='.png')
- png_file.close()
+ jpg_file = NamedTemporaryFile(delete=False, suffix='.jpg')
+ jpg_file.close()
fig.set_dpi(100)
fig.set_size_inches(10, 4)
fig.set_tight_layout(True)
- fig.savefig(png_file.name)
+ fig.savefig(jpg_file.name, quality=50)
plt.close(fig)
- return png_file.name
+ return jpg_file.name |
9901044b2b3218714a3c807e982db518aa97a446 | djangoautoconf/features/bae_settings.py | djangoautoconf/features/bae_settings.py | ##################################
# Added for BAE
##################################
try:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': const.CACHE_ADDR,
'TIMEOUT': 60,
}
}
except:
pass
try:
from bae.core import const
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': bae_secrets.database_name,
'USER': const.MYSQL_USER,
'PASSWORD': const.MYSQL_PASS,
'HOST': const.MYSQL_HOST,
'PORT': const.MYSQL_PORT,
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
###Or
#SESSION_ENGINE = 'django.contrib.sessions.backends.db'
##################################
except:
pass
EMAIL_BACKEND = 'django.core.mail.backends.bcms.EmailBackend'
try:
from objsys.baidu_mail import EmailBackend
EMAIL_BACKEND = 'objsys.baidu_mail.EmailBackend'
except:
EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
| ##################################
# Added for BAE
##################################
try:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': const.CACHE_ADDR,
'TIMEOUT': 60,
}
}
except:
pass
try:
from bae.core import const
import bae_secrets
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': bae_secrets.database_name,
'USER': const.MYSQL_USER,
'PASSWORD': const.MYSQL_PASS,
'HOST': const.MYSQL_HOST,
'PORT': const.MYSQL_PORT,
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
###Or
#SESSION_ENGINE = 'django.contrib.sessions.backends.db'
##################################
except:
pass
EMAIL_BACKEND = 'django.core.mail.backends.bcms.EmailBackend'
try:
from objsys.baidu_mail import EmailBackend
EMAIL_BACKEND = 'objsys.baidu_mail.EmailBackend'
except:
EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
| Move BAE secret into try catch block | Move BAE secret into try catch block
| Python | bsd-3-clause | weijia/djangoautoconf,weijia/djangoautoconf | ---
+++
@@ -1,6 +1,7 @@
##################################
# Added for BAE
##################################
+
try:
CACHES = {
@@ -14,6 +15,7 @@
pass
try:
from bae.core import const
+ import bae_secrets
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', |
3ed807b44289c00d6a82b0c253f7ff8072336fdd | changes/jobs/cleanup_tasks.py | changes/jobs/cleanup_tasks.py | from __future__ import absolute_import
from datetime import datetime, timedelta
from changes.config import queue
from changes.constants import Status
from changes.models.task import Task
from changes.queue.task import TrackedTask
CHECK_TIME = timedelta(minutes=60)
EXPIRE_TIME = timedelta(days=7)
# NOTE: This isn't itself a TrackedTask, but probably should be.
def cleanup_tasks():
"""
Find any tasks which haven't checked in within a reasonable time period and
requeue them if necessary.
Additionally remove any old Task entries which are completed.
"""
now = datetime.utcnow()
pending_tasks = Task.query.filter(
Task.status != Status.finished,
Task.date_modified < now - CHECK_TIME,
)
for task in pending_tasks:
task_func = TrackedTask(queue.get_task(task.task_name))
task_func.delay(
task_id=task.task_id.hex,
parent_task_id=task.parent_id.hex if task.parent_id else None,
**task.data['kwargs']
)
Task.query.filter(
Task.status == Status.finished,
Task.date_modified < now - EXPIRE_TIME,
).delete()
| from __future__ import absolute_import
from datetime import datetime, timedelta
from changes.config import queue, statsreporter
from changes.constants import Status
from changes.models.task import Task
from changes.queue.task import TrackedTask
CHECK_TIME = timedelta(minutes=60)
EXPIRE_TIME = timedelta(days=7)
# NOTE: This isn't itself a TrackedTask, but probably should be.
@statsreporter.timer('task_duration_cleanup_task')
def cleanup_tasks():
"""
Find any tasks which haven't checked in within a reasonable time period and
requeue them if necessary.
Additionally remove any old Task entries which are completed.
"""
now = datetime.utcnow()
pending_tasks = Task.query.filter(
Task.status != Status.finished,
Task.date_modified < now - CHECK_TIME,
)
for task in pending_tasks:
task_func = TrackedTask(queue.get_task(task.task_name))
task_func.delay(
task_id=task.task_id.hex,
parent_task_id=task.parent_id.hex if task.parent_id else None,
**task.data['kwargs']
)
deleted = Task.query.filter(
Task.status == Status.finished,
Task.date_modified < now - EXPIRE_TIME,
# Filtering by date_created isn't necessary, but it allows us to filter using an index on
# a value that doesn't update, which makes our deletion more efficient.
Task.date_created < now - EXPIRE_TIME,
).delete(synchronize_session=False)
statsreporter.stats().incr('tasks_deleted', deleted)
| Make periodic expired task deletion more efficient | Make periodic expired task deletion more efficient
Summary: Also adds tracking for the number of tasks deleted at each run.
Test Plan: None
Reviewers: paulruan
Reviewed By: paulruan
Subscribers: changesbot, anupc
Differential Revision: https://tails.corp.dropbox.com/D232735
| Python | apache-2.0 | dropbox/changes,dropbox/changes,dropbox/changes,dropbox/changes | ---
+++
@@ -2,7 +2,7 @@
from datetime import datetime, timedelta
-from changes.config import queue
+from changes.config import queue, statsreporter
from changes.constants import Status
from changes.models.task import Task
from changes.queue.task import TrackedTask
@@ -12,6 +12,7 @@
# NOTE: This isn't itself a TrackedTask, but probably should be.
[email protected]('task_duration_cleanup_task')
def cleanup_tasks():
"""
Find any tasks which haven't checked in within a reasonable time period and
@@ -34,7 +35,11 @@
**task.data['kwargs']
)
- Task.query.filter(
+ deleted = Task.query.filter(
Task.status == Status.finished,
Task.date_modified < now - EXPIRE_TIME,
- ).delete()
+ # Filtering by date_created isn't necessary, but it allows us to filter using an index on
+ # a value that doesn't update, which makes our deletion more efficient.
+ Task.date_created < now - EXPIRE_TIME,
+ ).delete(synchronize_session=False)
+ statsreporter.stats().incr('tasks_deleted', deleted) |
dd8c85a49a31693f43e6f6877a0657d63cbc1b01 | auth0/v2/device_credentials.py | auth0/v2/device_credentials.py | from .rest import RestClient
class DeviceCredentials(object):
"""Auth0 connection endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
jwt_token (str): An API token created with your account's global
keys. You can create one by using the token generator in the
API Explorer: https://auth0.com/docs/api/v2
"""
def __init__(self, domain, jwt_token):
self.domain = domain
self.client = RestClient(jwt=jwt_token)
def _url(self, id=None):
url = 'https://%s/api/v2/device-credentials' % self.domain
if id is not None:
return url + '/' + id
return url
def get(self, user_id=None, client_id=None, type=None,
fields=[], include_fields=True):
params = {
'fields': ','.join(fields) or None,
'include_fields': str(include_fields).lower(),
'user_id': user_id,
'client_id': client_id,
'type': type,
}
return self.client.get(self._url(), params=params)
def create(self, body):
return self.client.post(self._url(), data=body)
def delete(self, id):
return self.client.delete(self._url(id))
| from .rest import RestClient
class DeviceCredentials(object):
"""Auth0 connection endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
jwt_token (str): An API token created with your account's global
keys. You can create one by using the token generator in the
API Explorer: https://auth0.com/docs/api/v2
"""
def __init__(self, domain, jwt_token):
self.domain = domain
self.client = RestClient(jwt=jwt_token)
def _url(self, id=None):
url = 'https://%s/api/v2/device-credentials' % self.domain
if id is not None:
return url + '/' + id
return url
def get(self, user_id, client_id, type, fields=[], include_fields=True):
params = {
'fields': ','.join(fields) or None,
'include_fields': str(include_fields).lower(),
'user_id': user_id,
'client_id': client_id,
'type': type,
}
return self.client.get(self._url(), params=params)
def create(self, body):
return self.client.post(self._url(), data=body)
def delete(self, id):
return self.client.delete(self._url(id))
| Remove default arguments for user_id, client_id and type | Remove default arguments for user_id, client_id and type
| Python | mit | auth0/auth0-python,auth0/auth0-python | ---
+++
@@ -23,8 +23,7 @@
return url + '/' + id
return url
- def get(self, user_id=None, client_id=None, type=None,
- fields=[], include_fields=True):
+ def get(self, user_id, client_id, type, fields=[], include_fields=True):
params = {
'fields': ','.join(fields) or None,
'include_fields': str(include_fields).lower(), |
24ea32f71faab214a6f350d2d48b2f5715d8262d | manage.py | manage.py | from flask_restful import Api
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from app import app
from app import db
from app.auth import Register, Login
from app.bucketlist_api import BucketList, BucketListEntry
from app.bucketlist_items import BucketListItems, BucketListItemSingle
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
api = Api(app)
api.add_resource(Register, '/auth/register')
api.add_resource(Login, '/auth/login')
api.add_resource(BucketList, '/bucketlists')
api.add_resource(BucketListEntry, '/bucketlists/<int:bucketlist_id>')
api.add_resource(BucketListItems, '/bucketlists/<int:bucketlist_id>/items')
api.add_resource(BucketListItemSingle,
'/bucketlists/<int:bucketlist_id>/items/<int:item_id>')
if __name__ == '__main__':
manager.run()
| from flask_restful import Api
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from app import app, db
from app.auth import Register, Login
from app.bucketlist_api import BucketLists, BucketListSingle
from app.bucketlist_items import BucketListItems, BucketListItemSingle
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
api = Api(app)
api.add_resource(Register, '/auth/register')
api.add_resource(Login, '/auth/login')
api.add_resource(BucketLists, '/bucketlists')
api.add_resource(BucketListSingle, '/bucketlists/<int:bucketlist_id>')
api.add_resource(BucketListItems, '/bucketlists/<int:bucketlist_id>/items')
api.add_resource(BucketListItemSingle,
'/bucketlists/<int:bucketlist_id>/items/<int:item_id>')
if __name__ == '__main__':
manager.run()
| Set urls for bucketlist items endpoints | Set urls for bucketlist items endpoints
| Python | mit | andela-bmwenda/cp2-bucketlist-api | ---
+++
@@ -1,10 +1,9 @@
from flask_restful import Api
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
-from app import app
-from app import db
+from app import app, db
from app.auth import Register, Login
-from app.bucketlist_api import BucketList, BucketListEntry
+from app.bucketlist_api import BucketLists, BucketListSingle
from app.bucketlist_items import BucketListItems, BucketListItemSingle
migrate = Migrate(app, db)
@@ -16,8 +15,8 @@
api.add_resource(Register, '/auth/register')
api.add_resource(Login, '/auth/login')
-api.add_resource(BucketList, '/bucketlists')
-api.add_resource(BucketListEntry, '/bucketlists/<int:bucketlist_id>')
+api.add_resource(BucketLists, '/bucketlists')
+api.add_resource(BucketListSingle, '/bucketlists/<int:bucketlist_id>')
api.add_resource(BucketListItems, '/bucketlists/<int:bucketlist_id>/items')
api.add_resource(BucketListItemSingle,
'/bucketlists/<int:bucketlist_id>/items/<int:item_id>') |
8a6c678c18bb112caf89b7b7c9968215e9e0eff5 | begotemp/models/watercourse.py | begotemp/models/watercourse.py | # -*- coding: utf-8 -*-
""" ``SQLAlchemy`` model definition for the watercourses."""
from geoalchemy import GeometryColumn, GeometryDDL, LineString
from sqlalchemy import Column, Unicode, Integer
from anuket.models import Base
class Watercourse(Base):
""" Table for the watercourses - LINESTRINGS - Lambert93."""
__tablename__ = 'watercourse'
watercourse_id = Column(Integer, primary_key=True)
watercourse_name = Column(Unicode, unique=True)
geo_polygon = GeometryColumn(LineString(2, srid=2154, spatial_index=False))
GeometryDDL(Watercourse.__table__)
| # -*- coding: utf-8 -*-
""" ``SQLAlchemy`` model definition for the watercourses."""
from geoalchemy import GeometryColumn, GeometryDDL, LineString
from sqlalchemy import Column, Unicode, Integer
from anuket.models import Base
class Watercourse(Base):
""" Table for the watercourses - LINESTRINGS - Lambert93."""
__tablename__ = 'watercourse'
watercourse_id = Column(Integer, primary_key=True)
watercourse_name = Column(Unicode, unique=True)
geo_linestring = GeometryColumn(LineString(2, srid=2154, spatial_index=False))
GeometryDDL(Watercourse.__table__)
| Correct the geographic field name | Correct the geographic field name | Python | mit | miniwark/begotemp | ---
+++
@@ -12,7 +12,7 @@
watercourse_id = Column(Integer, primary_key=True)
watercourse_name = Column(Unicode, unique=True)
- geo_polygon = GeometryColumn(LineString(2, srid=2154, spatial_index=False))
+ geo_linestring = GeometryColumn(LineString(2, srid=2154, spatial_index=False))
GeometryDDL(Watercourse.__table__) |
b6e57269b8bd57420fb856daba75452dbf37cfa2 | tests/scoring_engine/engine/checks/test_https.py | tests/scoring_engine/engine/checks/test_https.py | from tests.scoring_engine.engine.checks.check_test import CheckTest
class TestHTTPSCheck(CheckTest):
check_name = 'HTTPSCheck'
required_properties = ['useragent', 'vhost', 'uri']
properties = {
'useragent': 'testagent',
'vhost': 'www.example.com',
'uri': '/index.html'
}
cmd = "curl -s -S -4 -v -L -k --ssl-reqd -A 'testagent' 'https://www.example.com:100/index.html'" | from tests.scoring_engine.engine.checks.check_test import CheckTest
class TestHTTPSCheck(CheckTest):
check_name = 'HTTPSCheck'
required_properties = ['useragent', 'vhost', 'uri']
properties = {
'useragent': 'testagent',
'vhost': 'www.example.com',
'uri': '/index.html'
}
cmd = "curl -s -S -4 -v -L -k --ssl-reqd -A 'testagent' 'https://www.example.com:100/index.html'"
| Fix pep8 new line in test https check | Fix pep8 new line in test https check
Signed-off-by: Brandon Myers <[email protected]>
| Python | mit | pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine | |
638a1c434ef8202774675581c3659511fa9d1cd3 | vehicles/management/commands/import_edinburgh.py | vehicles/management/commands/import_edinburgh.py | from django.contrib.gis.geos import Point
from busstops.models import Service
from ...models import Vehicle, VehicleLocation, VehicleJourney
from ..import_live_vehicles import ImportLiveVehiclesCommand
class Command(ImportLiveVehiclesCommand):
url = 'http://tfeapp.com/live/vehicles.php'
source_name = 'TfE'
services = Service.objects.filter(operator__in=('LOTH', 'EDTR', 'ECBU', 'NELB'), current=True)
def get_journey(self, item):
journey = VehicleJourney(
code=item['journey_id'],
destination=item['destination']
)
vehicle_defaults = {}
try:
journey.service = self.services.get(line_name=item['service_name'])
vehicle_defaults['operator'] = journey.service.operator.first()
except (Service.DoesNotExist, Service.MultipleObjectsReturned) as e:
if item['service_name'] not in {'ET1', 'MA1', '3BBT'}:
print(e, item['service_name'])
vehicle_code = item['vehicle_id']
if vehicle_code.isdigit():
vehicle_defaults['fleet_number'] = vehicle_code
journey.vehicle, vehicle_created = Vehicle.objects.update_or_create(
vehicle_defaults,
source=self.source,
code=vehicle_code
)
return journey, vehicle_created
def create_vehicle_location(self, item):
return VehicleLocation(
latlong=Point(item['longitude'], item['latitude']),
heading=item['heading']
)
| from django.contrib.gis.geos import Point
from busstops.models import Service
from ...models import Vehicle, VehicleLocation, VehicleJourney
from ..import_live_vehicles import ImportLiveVehiclesCommand
class Command(ImportLiveVehiclesCommand):
url = 'http://tfeapp.com/live/vehicles.php'
source_name = 'TfE'
services = Service.objects.filter(operator__in=('LOTH', 'EDTR', 'ECBU', 'NELB'), current=True)
def get_journey(self, item):
journey = VehicleJourney(
code=item['journey_id'] or '',
destination=item['destination'] or ''
)
vehicle_defaults = {}
try:
journey.service = self.services.get(line_name=item['service_name'])
vehicle_defaults['operator'] = journey.service.operator.first()
except (Service.DoesNotExist, Service.MultipleObjectsReturned) as e:
if item['service_name'] not in {'ET1', 'MA1', '3BBT'}:
print(e, item['service_name'])
vehicle_code = item['vehicle_id']
if vehicle_code.isdigit():
vehicle_defaults['fleet_number'] = vehicle_code
journey.vehicle, vehicle_created = Vehicle.objects.update_or_create(
vehicle_defaults,
source=self.source,
code=vehicle_code
)
return journey, vehicle_created
def create_vehicle_location(self, item):
return VehicleLocation(
latlong=Point(item['longitude'], item['latitude']),
heading=item['heading']
)
| Fix null Edinburgh journey code or destination | Fix null Edinburgh journey code or destination
| Python | mpl-2.0 | jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk | ---
+++
@@ -11,8 +11,8 @@
def get_journey(self, item):
journey = VehicleJourney(
- code=item['journey_id'],
- destination=item['destination']
+ code=item['journey_id'] or '',
+ destination=item['destination'] or ''
)
vehicle_defaults = {} |
8523576286a45318f654ad5ab462e9a6f65b69e2 | canary/app.py | canary/app.py | import os
import uuid
import time
import json
from flask import Flask
app = Flask(__name__)
app.debug = True
def check(endpoint):
def actual_check(function):
start_time = time.time()
ret = function()
total_time = time.time() - start_time
return json.dumps({
'status': ret,
'time': total_time
})
return app.route(endpoint)(actual_check)
@check('/nfs/home')
def nfs_home_check():
content = str(uuid.uuid4())
path = os.path.join('/data/project/canary/nfs-test/', content)
try:
with open(path, 'w') as f:
f.write(content)
with open(path) as f:
actual_content = f.read()
if actual_content == content:
return True
return False
finally:
os.remove(path)
| import os
import uuid
import time
import json
from flask import Flask
app = Flask(__name__)
app.debug = True
def check(endpoint):
def actual_decorator(func):
def actual_check():
start_time = time.time()
try:
ret = func()
except:
# FIXME: log this error somewhere
ret = False
total_time = time.time() - start_time
return json.dumps({
'status': ret,
'time': total_time
})
return app.route(endpoint)(actual_check)
return actual_decorator
@check('/nfs/home')
def nfs_home_check():
content = str(uuid.uuid4())
path = os.path.join('/data/project/canary/nfs-test/', content)
try:
with open(path, 'w') as f:
f.write(content)
with open(path) as f:
actual_content = f.read()
if actual_content == content:
return True
return False
finally:
os.remove(path)
| Use a decorator to wrap the actual checks | Use a decorator to wrap the actual checks
| Python | mit | yuvipanda/tools-canary | ---
+++
@@ -8,16 +8,23 @@
app = Flask(__name__)
app.debug = True
+
def check(endpoint):
- def actual_check(function):
- start_time = time.time()
- ret = function()
- total_time = time.time() - start_time
- return json.dumps({
- 'status': ret,
- 'time': total_time
- })
- return app.route(endpoint)(actual_check)
+ def actual_decorator(func):
+ def actual_check():
+ start_time = time.time()
+ try:
+ ret = func()
+ except:
+ # FIXME: log this error somewhere
+ ret = False
+ total_time = time.time() - start_time
+ return json.dumps({
+ 'status': ret,
+ 'time': total_time
+ })
+ return app.route(endpoint)(actual_check)
+ return actual_decorator
@check('/nfs/home') |
c9da64ac1c90abdee8fc72488a4bef58a95aa7c6 | biwako/bin/fields/compounds.py | biwako/bin/fields/compounds.py | import io
from .base import Field, DynamicValue, FullyDecoded
class SubStructure(Field):
def __init__(self, structure, *args, **kwargs):
self.structure = structure
super(SubStructure, self).__init__(*args, **kwargs)
def read(self, file):
value = self.structure(file)
value_bytes = b''
# Force the evaluation of the entire structure in
# order to make sure other fields work properly
for field in self.structure._fields:
getattr(value, field.name)
value_bytes += value._raw_values[field.name]
raise FullyDecoded(value_bytes, value)
def encode(self, obj, value):
output = io.BytesIO()
value.save(output)
return output.getvalue()
class List(Field):
def __init__(self, field, *args, **kwargs):
super(List, self).__init__(*args, **kwargs)
self.field = field
def read(self, file):
value_bytes = b''
values = []
if self.instance:
instance_field = field.for_instance(self.instance)
for i in range(self.size):
bytes, value = instance_field.read_value(file)
value_bytes += bytes
values.append(value)
return values
def encode(self, obj, values):
encoded_values = []
for value in values:
encoded_values.append(self.field.encode(obj, value))
return b''.join(encoded_values)
| import io
from .base import Field, DynamicValue, FullyDecoded
class SubStructure(Field):
def __init__(self, structure, *args, **kwargs):
self.structure = structure
super(SubStructure, self).__init__(*args, **kwargs)
def read(self, file):
value = self.structure(file)
value_bytes = b''
# Force the evaluation of the entire structure in
# order to make sure other fields work properly
for field in self.structure._fields:
getattr(value, field.name)
value_bytes += value._raw_values[field.name]
raise FullyDecoded(value_bytes, value)
def encode(self, obj, value):
output = io.BytesIO()
value.save(output)
return output.getvalue()
class List(Field):
def __init__(self, field, *args, **kwargs):
super(List, self).__init__(*args, **kwargs)
self.field = field
def read(self, file):
value_bytes = b''
values = []
if self.instance:
instance_field = self.field.for_instance(self.instance)
for i in range(self.size):
bytes, value = instance_field.read_value(file)
value_bytes += bytes
values.append(value)
raise FullyDecoded(value_bytes, values)
def encode(self, obj, values):
encoded_values = []
for value in values:
encoded_values.append(self.field.encode(obj, value))
return b''.join(encoded_values)
| Fix List to use the new decoding system | Fix List to use the new decoding system
| Python | bsd-3-clause | gulopine/steel | ---
+++
@@ -34,13 +34,13 @@
value_bytes = b''
values = []
if self.instance:
- instance_field = field.for_instance(self.instance)
+ instance_field = self.field.for_instance(self.instance)
for i in range(self.size):
bytes, value = instance_field.read_value(file)
value_bytes += bytes
values.append(value)
- return values
+ raise FullyDecoded(value_bytes, values)
def encode(self, obj, values):
encoded_values = [] |
b8eb19e56682bc7546ad4ba12db46cd4fa48dfa1 | etc/ci/check_dynamic_symbols.py | etc/ci/check_dynamic_symbols.py | # Copyright 2013 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except according to those terms.
import sys
import re
import subprocess
symbol_regex = re.compile("D \*UND\*\t(.*) (.*)$")
allowed_symbols = frozenset(['unshare', 'malloc_usable_size'])
actual_symbols = set()
objdump_output = subprocess.check_output([
'arm-linux-androideabi-objdump',
'-T',
'target/arm-linux-androideabi/debug/libservo.so']
).split('\n')
for line in objdump_output:
m = symbol_regex.search(line)
if m is not None:
actual_symbols.add(m.group(2))
difference = actual_symbols - allowed_symbols
if len(difference) > 0:
human_readable_difference = ", ".join(str(s) for s in difference)
print("Unexpected dynamic symbols in binary: {0}".format(human_readable_difference))
sys.exit(-1)
| # Copyright 2013 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except according to those terms.
import sys
import re
import subprocess
symbol_regex = re.compile(b"D \*UND\*\t(.*) (.*)$")
allowed_symbols = frozenset([b'unshare', b'malloc_usable_size'])
actual_symbols = set()
objdump_output = subprocess.check_output([
'arm-linux-androideabi-objdump',
'-T',
'target/arm-linux-androideabi/debug/libservo.so']
).split(b'\n')
for line in objdump_output:
m = symbol_regex.search(line)
if m is not None:
actual_symbols.add(m.group(2))
difference = actual_symbols - allowed_symbols
if len(difference) > 0:
human_readable_difference = ", ".join(str(s) for s in difference)
print("Unexpected dynamic symbols in binary: {0}".format(human_readable_difference))
sys.exit(-1)
| Add Python 3 compatibility to Android symbol checker | Add Python 3 compatibility to Android symbol checker
Make the script that checks for undefined Android symbols compatible
with both Python 2 and Python 3, to allow for future updates to the
default system Python on our build machines.
I'd like to land this before https://github.com/servo/saltfs/pull/249.
We currently use Ubuntu 14.04 (an LTS release); Ubuntu is aiming for
Python 3 as the default Python in the next LTS release, 16.04, and
I'd like to have any scripts be ready for the transition.
| Python | mpl-2.0 | dsandeephegde/servo,thiagopnts/servo,notriddle/servo,dati91/servo,splav/servo,szeged/servo,mbrubeck/servo,splav/servo,dati91/servo,mattnenterprise/servo,mbrubeck/servo,eddyb/servo,avadacatavra/servo,ConnorGBrewster/servo,avadacatavra/servo,paulrouget/servo,cbrewster/servo,szeged/servo,larsbergstrom/servo,emilio/servo,paulrouget/servo,KiChjang/servo,ConnorGBrewster/servo,saneyuki/servo,nnethercote/servo,sadmansk/servo,szeged/servo,larsbergstrom/servo,splav/servo,steveklabnik/servo,dati91/servo,peterjoel/servo,sadmansk/servo,CJ8664/servo,emilio/servo,anthgur/servo,mattnenterprise/servo,CJ8664/servo,pyfisch/servo,peterjoel/servo,cbrewster/servo,peterjoel/servo,anthgur/servo,jimberlage/servo,mattnenterprise/servo,pyfisch/servo,pyfisch/servo,upsuper/servo,thiagopnts/servo,rnestler/servo,DominoTree/servo,peterjoel/servo,sadmansk/servo,peterjoel/servo,larsbergstrom/servo,ConnorGBrewster/servo,nnethercote/servo,SimonSapin/servo,mbrubeck/servo,cbrewster/servo,saneyuki/servo,eddyb/servo,paulrouget/servo,emilio/servo,DominoTree/servo,paulrouget/servo,KiChjang/servo,canaltinova/servo,canaltinova/servo,dsandeephegde/servo,ConnorGBrewster/servo,paulrouget/servo,peterjoel/servo,nnethercote/servo,anthgur/servo,fiji-flo/servo,SimonSapin/servo,notriddle/servo,rnestler/servo,upsuper/servo,pyfisch/servo,saneyuki/servo,anthgur/servo,splav/servo,szeged/servo,jimberlage/servo,eddyb/servo,peterjoel/servo,paulrouget/servo,SimonSapin/servo,szeged/servo,saneyuki/servo,cbrewster/servo,ConnorGBrewster/servo,szeged/servo,szeged/servo,splav/servo,fiji-flo/servo,canaltinova/servo,mattnenterprise/servo,rnestler/servo,nrc/servo,dsandeephegde/servo,dsandeephegde/servo,canaltinova/servo,jimberlage/servo,mattnenterprise/servo,fiji-flo/servo,paulrouget/servo,CJ8664/servo,CJ8664/servo,splav/servo,avadacatavra/servo,emilio/servo,steveklabnik/servo,sadmansk/servo,mbrubeck/servo,DominoTree/servo,nrc/servo,jimberlage/servo,DominoTree/servo,mbrubeck/servo,rnestler/servo,avadacatavra/servo,dati91/servo,KiChjang/servo,larsbergstrom/servo,rnestler/servo,szeged/servo,dati91/servo,pyfisch/servo,notriddle/servo,peterjoel/servo,jimberlage/servo,thiagopnts/servo,mbrubeck/servo,anthgur/servo,SimonSapin/servo,dati91/servo,DominoTree/servo,cbrewster/servo,SimonSapin/servo,nnethercote/servo,splav/servo,steveklabnik/servo,larsbergstrom/servo,thiagopnts/servo,steveklabnik/servo,fiji-flo/servo,steveklabnik/servo,larsbergstrom/servo,eddyb/servo,CJ8664/servo,canaltinova/servo,cbrewster/servo,saneyuki/servo,nnethercote/servo,emilio/servo,KiChjang/servo,upsuper/servo,SimonSapin/servo,eddyb/servo,SimonSapin/servo,nrc/servo,peterjoel/servo,nnethercote/servo,dsandeephegde/servo,notriddle/servo,CJ8664/servo,dsandeephegde/servo,canaltinova/servo,DominoTree/servo,anthgur/servo,avadacatavra/servo,notriddle/servo,sadmansk/servo,upsuper/servo,saneyuki/servo,sadmansk/servo,fiji-flo/servo,dsandeephegde/servo,SimonSapin/servo,saneyuki/servo,notriddle/servo,splav/servo,avadacatavra/servo,splav/servo,jimberlage/servo,cbrewster/servo,KiChjang/servo,dsandeephegde/servo,paulrouget/servo,thiagopnts/servo,mattnenterprise/servo,splav/servo,nrc/servo,canaltinova/servo,jimberlage/servo,anthgur/servo,jimberlage/servo,larsbergstrom/servo,upsuper/servo,nrc/servo,nnethercote/servo,emilio/servo,dati91/servo,KiChjang/servo,szeged/servo,ConnorGBrewster/servo,upsuper/servo,pyfisch/servo,steveklabnik/servo,saneyuki/servo,sadmansk/servo,eddyb/servo,KiChjang/servo,canaltinova/servo,nnethercote/servo,pyfisch/servo,jimberlage/servo,thiagopnts/servo,DominoTree/servo,paulrouget/servo,eddyb/servo,CJ8664/servo,notriddle/servo,szeged/servo,mattnenterprise/servo,pyfisch/servo,CJ8664/servo,emilio/servo,rnestler/servo,larsbergstrom/servo,notriddle/servo,anthgur/servo,pyfisch/servo,eddyb/servo,upsuper/servo,cbrewster/servo,fiji-flo/servo,notriddle/servo,thiagopnts/servo,nrc/servo,steveklabnik/servo,DominoTree/servo,rnestler/servo,mbrubeck/servo,mbrubeck/servo,saneyuki/servo,thiagopnts/servo,sadmansk/servo,emilio/servo,larsbergstrom/servo,nnethercote/servo,fiji-flo/servo,DominoTree/servo,emilio/servo,emilio/servo,rnestler/servo,saneyuki/servo,notriddle/servo,KiChjang/servo,nnethercote/servo,mattnenterprise/servo,larsbergstrom/servo,KiChjang/servo,avadacatavra/servo,KiChjang/servo,peterjoel/servo,nrc/servo,avadacatavra/servo,dati91/servo,ConnorGBrewster/servo,fiji-flo/servo,upsuper/servo,DominoTree/servo,paulrouget/servo,ConnorGBrewster/servo,pyfisch/servo | ---
+++
@@ -11,15 +11,15 @@
import re
import subprocess
-symbol_regex = re.compile("D \*UND\*\t(.*) (.*)$")
-allowed_symbols = frozenset(['unshare', 'malloc_usable_size'])
+symbol_regex = re.compile(b"D \*UND\*\t(.*) (.*)$")
+allowed_symbols = frozenset([b'unshare', b'malloc_usable_size'])
actual_symbols = set()
objdump_output = subprocess.check_output([
'arm-linux-androideabi-objdump',
'-T',
'target/arm-linux-androideabi/debug/libservo.so']
-).split('\n')
+).split(b'\n')
for line in objdump_output:
m = symbol_regex.search(line) |
1f8b19d3baa2970adc008d5b7903730b51edad58 | example_site/settings/travis.py | example_site/settings/travis.py | from .base import *
DEBUG = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.abspath(os.path.join(
BASE_DIR, '..', 'data', 'db.sqlite3')),
}
}
ALLOWED_HOSTS = [
'127.0.0.1'
]
# email settings
EMAIL_HOST = 'localhost'
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_REPLY_TO = 'donotreply@'
# Logging
LOG_ENV = 'travis'
EXAMPLES_LOG_FILE = '{}/{}-examples.log'.format(LOG_DIR, LOG_ENV)
DCOLUMNS_LOG_FILE = '{}/{}-dcolumn.log'.format(LOG_DIR, LOG_ENV)
LOGGING.get('handlers', {}).get(
'examples_file', {})['filename'] = EXAMPLES_LOG_FILE
LOGGING.get('handlers', {}).get(
'dcolumns_file', {})['filename'] = DCOLUMNS_LOG_FILE
LOGGING.get('loggers', {}).get('django.request', {})['level'] = 'DEBUG'
LOGGING.get('loggers', {}).get('examples', {})['level'] = 'DEBUG'
LOGGING.get('loggers', {}).get('dcolumns', {})['level'] = 'DEBUG'
| from .base import *
DEBUG = False
# Make data dir
DATA_DIR = os.path.abspath(os.path.join(BASE_DIR, '..', 'data'))
not os.path.isdir(DATA_DIR) and os.mkdir(DATA_DIR, 0o0775)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.abspath(os.path.join(
BASE_DIR, '..', 'data', 'db.sqlite3')),
}
}
ALLOWED_HOSTS = [
'127.0.0.1'
]
# email settings
EMAIL_HOST = 'localhost'
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_REPLY_TO = 'donotreply@'
# Logging
LOG_ENV = 'travis'
EXAMPLES_LOG_FILE = '{}/{}-examples.log'.format(LOG_DIR, LOG_ENV)
DCOLUMNS_LOG_FILE = '{}/{}-dcolumn.log'.format(LOG_DIR, LOG_ENV)
LOGGING.get('handlers', {}).get(
'examples_file', {})['filename'] = EXAMPLES_LOG_FILE
LOGGING.get('handlers', {}).get(
'dcolumns_file', {})['filename'] = DCOLUMNS_LOG_FILE
LOGGING.get('loggers', {}).get('django.request', {})['level'] = 'DEBUG'
LOGGING.get('loggers', {}).get('examples', {})['level'] = 'DEBUG'
LOGGING.get('loggers', {}).get('dcolumns', {})['level'] = 'DEBUG'
| Add the creation of the data dir for the sqlite file. | Add the creation of the data dir for the sqlite file.
| Python | mit | cnobile2012/dcolumn,cnobile2012/dcolumn,cnobile2012/dcolumn,cnobile2012/dcolumn | ---
+++
@@ -1,6 +1,10 @@
from .base import *
DEBUG = False
+
+# Make data dir
+DATA_DIR = os.path.abspath(os.path.join(BASE_DIR, '..', 'data'))
+not os.path.isdir(DATA_DIR) and os.mkdir(DATA_DIR, 0o0775)
DATABASES = {
'default': { |
1e5e2a236277dc9ba11f9fe4aff3279f692da3f7 | ploy/tests/conftest.py | ploy/tests/conftest.py | from mock import patch
import pytest
import os
import shutil
import tempfile
class Directory:
def __init__(self, directory):
self.directory = directory
def __getitem__(self, name):
path = os.path.join(self.directory, name)
assert not os.path.relpath(path, self.directory).startswith('..')
return File(path)
class File:
def __init__(self, path):
self.directory = os.path.dirname(path)
self.path = path
def fill(self, content):
if not os.path.exists(self.directory):
os.makedirs(self.directory)
with open(self.path, 'w') as f:
if isinstance(content, (list, tuple)):
content = '\n'.join(content)
f.write(content)
@pytest.yield_fixture
def tempdir():
""" Returns an object for easy use of a temporary directory which is
cleaned up afterwards.
Use tempdir[filepath] to access files.
Use .fill(lines) on the returned object to write content to the file.
"""
directory = tempfile.mkdtemp()
yield Directory(directory)
shutil.rmtree(directory)
@pytest.yield_fixture
def ployconf(tempdir):
""" Returns a Configfile object which manages ploy.conf.
"""
yield tempdir['etc/ploy.conf']
@pytest.yield_fixture
def os_execvp_mock():
with patch("os.execvp") as os_execvp_mock:
yield os_execvp_mock
| from mock import patch
import pytest
import os
import shutil
import tempfile
class Directory:
def __init__(self, directory):
self.directory = directory
def __getitem__(self, name):
path = os.path.join(self.directory, name)
assert not os.path.relpath(path, self.directory).startswith('..')
return File(path)
class File:
def __init__(self, path):
self.directory = os.path.dirname(path)
self.path = path
def fill(self, content):
if not os.path.exists(self.directory):
os.makedirs(self.directory)
with open(self.path, 'w') as f:
if isinstance(content, (list, tuple)):
content = '\n'.join(content)
f.write(content)
def content(self):
with open(self.path) as f:
return f.read()
@pytest.yield_fixture
def tempdir():
""" Returns an object for easy use of a temporary directory which is
cleaned up afterwards.
Use tempdir[filepath] to access files.
Use .fill(lines) on the returned object to write content to the file.
"""
directory = tempfile.mkdtemp()
yield Directory(directory)
shutil.rmtree(directory)
@pytest.yield_fixture
def ployconf(tempdir):
""" Returns a Configfile object which manages ploy.conf.
"""
yield tempdir['etc/ploy.conf']
@pytest.yield_fixture
def os_execvp_mock():
with patch("os.execvp") as os_execvp_mock:
yield os_execvp_mock
| Add convenience function to read tempdir files. | Add convenience function to read tempdir files.
| Python | bsd-3-clause | fschulze/ploy,ployground/ploy | ---
+++
@@ -28,6 +28,10 @@
content = '\n'.join(content)
f.write(content)
+ def content(self):
+ with open(self.path) as f:
+ return f.read()
+
@pytest.yield_fixture
def tempdir(): |
1965b1db79758a53eb45f81bb25e83c4d09b95af | pupa/scrape/helpers.py | pupa/scrape/helpers.py | """ these are helper classes for object creation during the scrape """
from pupa.models.person import Person
from pupa.models.organization import Organization
from pupa.models.membership import Membership
class Legislator(Person):
_is_legislator = True
__slots__ = ('post_id', 'party', 'chamber', '_contact_details')
def __init__(self, name, post_id, party=None, chamber=None, **kwargs):
super(Legislator, self).__init__(name, **kwargs)
self.post_id = post_id
self.party = party
self.chamber = chamber
self._contact_details = []
def add_contact(self, type, value, note):
self._contact_details.append({'type': type, 'value': value,
'note': note})
def add_committee_membership(self, com_name, role='member'):
org = Organization(com_name, classification='committee')
self.add_membership(org, role=role)
org.sources = self.sources
self._related.append(org)
class Committee(Organization):
def __init__(self, *args, **kwargs):
super(Committee, self).__init__(*args, **kwargs)
def add_member(self, name, role='member', **kwargs):
membership = Membership(None, self._id, role=role,
unmatched_legislator={'name': name},
**kwargs)
self._related.append(membership)
| """ these are helper classes for object creation during the scrape """
from pupa.models.person import Person
from pupa.models.organization import Organization
from pupa.models.membership import Membership
class Legislator(Person):
_is_legislator = True
__slots__ = ('post_id', 'party', 'chamber', '_contact_details', 'role')
def __init__(self, name, post_id, party=None, chamber=None, **kwargs):
super(Legislator, self).__init__(name, **kwargs)
self.post_id = post_id
self.party = party
self.chamber = chamber
self._contact_details = []
def add_contact(self, type, value, note):
self._contact_details.append({'type': type, 'value': value,
'note': note})
def add_committee_membership(self, com_name, role='member'):
org = Organization(com_name, classification='committee')
self.add_membership(org, role=role)
org.sources = self.sources
self._related.append(org)
class Committee(Organization):
def __init__(self, *args, **kwargs):
super(Committee, self).__init__(*args, **kwargs)
def add_member(self, name, role='member', **kwargs):
membership = Membership(None, self._id, role=role,
unmatched_legislator={'name': name},
**kwargs)
self._related.append(membership)
| Add a slot for legislator role | Add a slot for legislator role
| Python | bsd-3-clause | rshorey/pupa,rshorey/pupa,influence-usa/pupa,influence-usa/pupa,mileswwatkins/pupa,datamade/pupa,opencivicdata/pupa,mileswwatkins/pupa,datamade/pupa,opencivicdata/pupa | ---
+++
@@ -6,7 +6,7 @@
class Legislator(Person):
_is_legislator = True
- __slots__ = ('post_id', 'party', 'chamber', '_contact_details')
+ __slots__ = ('post_id', 'party', 'chamber', '_contact_details', 'role')
def __init__(self, name, post_id, party=None, chamber=None, **kwargs):
super(Legislator, self).__init__(name, **kwargs) |
854709e1c2f5351c8e7af49e238fe54632f23ff5 | takeyourmeds/settings/defaults/apps.py | takeyourmeds/settings/defaults/apps.py | INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'allauth',
'allauth.account',
'djcelery',
'rest_framework',
'takeyourmeds.api',
'takeyourmeds.reminder',
'takeyourmeds.static',
'takeyourmeds.telephony',
'takeyourmeds.utils',
)
| INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.sites',
'django.contrib.staticfiles',
'allauth',
'allauth.account',
'djcelery',
'rest_framework',
'takeyourmeds.api',
'takeyourmeds.reminder',
'takeyourmeds.static',
'takeyourmeds.telephony',
'takeyourmeds.utils',
)
| Return .sites to INSTALLED_APPS until we drop allauth | Return .sites to INSTALLED_APPS until we drop allauth
| Python | mit | takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web | ---
+++
@@ -3,6 +3,7 @@
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
+ 'django.contrib.sites',
'django.contrib.staticfiles',
'allauth', |
bf142af653dec7eb781faf6a45385a411bdfeee2 | scripts/lib/paths.py | scripts/lib/paths.py | details_source = './source/details/'
xml_source = './source/raw_xml/'
course_dest = './source/courses/'
info_path = './courses/info.json'
term_dest = './courses/terms/'
mappings_path = './related-data/generated/'
handmade_path = './related-data/handmade/'
def find_details_subdir(clbid):
str_clbid = str(clbid).zfill(10)
n_thousand = int(int(clbid) / 1000)
thousands_subdir = (n_thousand * 1000)
return str(thousands_subdir).zfill(5) + '/' + str_clbid
def make_course_path(clbid):
clbid = str(clbid).zfill(10)
return course_dest + find_details_subdir(clbid) + '.json'
def make_html_path(clbid):
clbid = str(clbid).zfill(10)
return details_source + find_details_subdir(clbid) + '.html'
def make_xml_term_path(term):
return xml_source + str(term) + '.xml'
def make_json_term_path(term):
return term_dest + str(term) + '.json'
| details_source = './source/details/'
xml_source = './source/raw_xml/'
course_dest = './source/courses/'
info_path = './build/info.json'
term_dest = './build/terms/'
mappings_path = './related-data/generated/'
handmade_path = './related-data/handmade/'
def find_details_subdir(clbid):
str_clbid = str(clbid).zfill(10)
n_thousand = int(int(clbid) / 1000)
thousands_subdir = (n_thousand * 1000)
return str(thousands_subdir).zfill(5) + '/' + str_clbid
def make_course_path(clbid):
clbid = str(clbid).zfill(10)
return course_dest + find_details_subdir(clbid) + '.json'
def make_html_path(clbid):
clbid = str(clbid).zfill(10)
return details_source + find_details_subdir(clbid) + '.html'
def make_xml_term_path(term):
return xml_source + str(term) + '.xml'
def make_json_term_path(term):
return term_dest + str(term) + '.json'
| Put the build stuff back in /build | Put the build stuff back in /build
| Python | mit | StoDevX/course-data-tools,StoDevX/course-data-tools | ---
+++
@@ -1,8 +1,8 @@
details_source = './source/details/'
xml_source = './source/raw_xml/'
course_dest = './source/courses/'
-info_path = './courses/info.json'
-term_dest = './courses/terms/'
+info_path = './build/info.json'
+term_dest = './build/terms/'
mappings_path = './related-data/generated/'
handmade_path = './related-data/handmade/'
|
a1cf7353917bbcee569cb8b6bb0d6277ee41face | dependency_injector/__init__.py | dependency_injector/__init__.py | """Dependency injector."""
from .catalog import AbstractCatalog
from .catalog import override
from .providers import Provider
from .providers import Delegate
from .providers import Factory
from .providers import Singleton
from .providers import ExternalDependency
from .providers import Class
from .providers import Object
from .providers import Function
from .providers import Value
from .providers import Callable
from .providers import Config
from .injections import Injection
from .injections import KwArg
from .injections import Attribute
from .injections import Method
from .injections import inject
from .utils import is_provider
from .utils import ensure_is_provider
from .utils import is_injection
from .utils import ensure_is_injection
from .utils import is_kwarg_injection
from .utils import is_attribute_injection
from .utils import is_method_injection
from .errors import Error
__all__ = (
# Catalogs
'AbstractCatalog',
'override',
# Providers
'Provider',
'Delegate',
'Factory',
'Singleton',
'ExternalDependency',
'Class',
'Object',
'Function',
'Value',
'Callable',
'Config',
# Injections
'KwArg',
'Attribute',
'Method',
'inject',
# Utils
'is_provider',
'ensure_is_provider',
'is_injection',
'ensure_is_injection',
'is_kwarg_injection',
'is_attribute_injection',
'is_method_injection',
# Errors
'Error',
)
| """Dependency injector."""
from .catalog import AbstractCatalog
from .catalog import override
from .providers import Provider
from .providers import Delegate
from .providers import Factory
from .providers import Singleton
from .providers import ExternalDependency
from .providers import Class
from .providers import Object
from .providers import Function
from .providers import Value
from .providers import Callable
from .providers import Config
from .injections import Injection
from .injections import KwArg
from .injections import Attribute
from .injections import Method
from .injections import inject
from .utils import is_provider
from .utils import ensure_is_provider
from .utils import is_injection
from .utils import ensure_is_injection
from .utils import is_kwarg_injection
from .utils import is_attribute_injection
from .utils import is_method_injection
from .errors import Error
__all__ = (
# Catalogs
'AbstractCatalog',
'override',
# Providers
'Provider',
'Delegate',
'Factory',
'Singleton',
'ExternalDependency',
'Class',
'Object',
'Function',
'Value',
'Callable',
'Config',
# Injections
'Injection',
'KwArg',
'Attribute',
'Method',
'inject',
# Utils
'is_provider',
'ensure_is_provider',
'is_injection',
'ensure_is_injection',
'is_kwarg_injection',
'is_attribute_injection',
'is_method_injection',
# Errors
'Error',
)
| Add Injection into __all__ list of top level package | Add Injection into __all__ list of top level package
| Python | bsd-3-clause | rmk135/dependency_injector,ets-labs/dependency_injector,rmk135/objects,ets-labs/python-dependency-injector | ---
+++
@@ -51,6 +51,7 @@
'Config',
# Injections
+ 'Injection',
'KwArg',
'Attribute',
'Method', |
6a8295baf32c80ea447d92fd3c7a01a2ad2e0df8 | openquake/risklib/__init__.py | openquake/risklib/__init__.py | # coding=utf-8
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake Risklib is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# OpenQuake Risklib 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 Affero General Public
# License along with OpenQuake Risklib. If not, see
# <http://www.gnu.org/licenses/>.
import os
import sys
from openquake.risklib.scientific import (
VulnerabilityFunction, DegenerateDistribution, classical)
from openquake.baselib.general import search_module
from openquake.hazardlib.general import git_suffix
__all__ = ["VulnerabilityFunction", "DegenerateDistribution", "classical"]
# the version is managed by packager.sh with a sed
__version__ = '0.5.1'
__version__ += git_suffix(__file__)
path = search_module('openquake.commonlib.general')
if path:
sys.exit('Found an obsolete version of commonlib; '
'please remove %s and/or fix your PYTHONPATH'
% os.path.dirname(path))
| # coding=utf-8
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake Risklib is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# OpenQuake Risklib 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 Affero General Public
# License along with OpenQuake Risklib. If not, see
# <http://www.gnu.org/licenses/>.
import os
import sys
from openquake.risklib.scientific import (
VulnerabilityFunction, DegenerateDistribution, classical)
from openquake.baselib.general import search_module
from openquake.hazardlib.general import git_suffix
__all__ = ["VulnerabilityFunction", "DegenerateDistribution", "classical"]
# the version is managed by packager.sh with a sed
__version__ = '0.6.0'
__version__ += git_suffix(__file__)
path = search_module('openquake.commonlib.general')
if path:
sys.exit('Found an obsolete version of commonlib; '
'please remove %s and/or fix your PYTHONPATH'
% os.path.dirname(path))
| Upgrade release number to 0.6.0 (oq-engine 1.3.0) | Upgrade release number to 0.6.0 (oq-engine 1.3.0)
| Python | agpl-3.0 | g-weatherill/oq-risklib,vup1120/oq-risklib,raoanirudh/oq-risklib,gem/oq-engine,gem/oq-engine,g-weatherill/oq-risklib,gem/oq-engine,gem/oq-engine,raoanirudh/oq-risklib,g-weatherill/oq-risklib,gem/oq-engine,vup1120/oq-risklib | ---
+++
@@ -25,7 +25,7 @@
__all__ = ["VulnerabilityFunction", "DegenerateDistribution", "classical"]
# the version is managed by packager.sh with a sed
-__version__ = '0.5.1'
+__version__ = '0.6.0'
__version__ += git_suffix(__file__)
path = search_module('openquake.commonlib.general') |
43ee2b8cfde4d0276cfd561063554705462001cf | openmm/run_test.py | openmm/run_test.py | #!/usr/bin/env python
from simtk import openmm
# Check major version number
assert openmm.Platform.getOpenMMVersion() == '7.1', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion()
# Check git hash
assert openmm.version.git_revision == '1e5b258c0df6ab8b4350fd2c3cbf6c6f7795847c', "openmm.version.git_revision = %s" % openmm.version.git_revision
| #!/usr/bin/env python
from simtk import openmm
# Check major version number
assert openmm.Platform.getOpenMMVersion() == '7.1', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion()
# Check git hash
assert openmm.version.git_revision == '9567ddb304c48d336e82927adf2761e8780e9270', "openmm.version.git_revision = %s" % openmm.version.git_revision
| Update git hash in test | Update git hash in test
| Python | mit | peastman/conda-recipes,cwehmeyer/conda-recipes,jchodera/conda-recipes,peastman/conda-recipes,swails/conda-recipes,cwehmeyer/conda-recipes,cwehmeyer/conda-recipes,swails/conda-recipes,swails/conda-recipes,jchodera/conda-recipes,omnia-md/conda-recipes,jchodera/conda-recipes,omnia-md/conda-recipes,cwehmeyer/conda-recipes,omnia-md/conda-recipes,peastman/conda-recipes,jchodera/conda-recipes,swails/conda-recipes | ---
+++
@@ -6,4 +6,4 @@
assert openmm.Platform.getOpenMMVersion() == '7.1', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion()
# Check git hash
-assert openmm.version.git_revision == '1e5b258c0df6ab8b4350fd2c3cbf6c6f7795847c', "openmm.version.git_revision = %s" % openmm.version.git_revision
+assert openmm.version.git_revision == '9567ddb304c48d336e82927adf2761e8780e9270', "openmm.version.git_revision = %s" % openmm.version.git_revision |
37f08dab37601b7621743467d6b78fb0306b5054 | lcapy/config.py | lcapy/config.py | # SymPy symbols to exclude
exclude = ('C', 'O', 'S', 'N', 'E', 'E1', 'Q')
# Aliases for SymPy symbols
aliases = {'delta': 'DiracDelta', 'step': 'Heaviside', 'u': 'Heaviside',
'j': 'I'}
# String replacements when printing as LaTeX. For example, SymPy uses
# theta for Heaviside's step.
latex_string_map = {r'\theta\left': r'u\left'}
import sympy as sym
print_expr_map = {sym.I: 'j'}
# Hack to print i as j
from sympy.printing.pretty.pretty_symbology import atoms_table
atoms_table['ImaginaryUnit'] = '\u2149'
| # SymPy symbols to exclude
exclude = ('C', 'O', 'S', 'N', 'E', 'E1', 'Q', 'beta', 'gamma', 'zeta')
# Aliases for SymPy symbols
aliases = {'delta': 'DiracDelta', 'step': 'Heaviside', 'u': 'Heaviside',
'j': 'I'}
# String replacements when printing as LaTeX. For example, SymPy uses
# theta for Heaviside's step.
latex_string_map = {r'\theta\left': r'u\left'}
import sympy as sym
print_expr_map = {sym.I: 'j'}
# Hack to pretty print i as j
from sympy.printing.pretty.pretty_symbology import atoms_table
atoms_table['ImaginaryUnit'] = '\u2149'
| Exclude beta, gamma, zeta functions | Exclude beta, gamma, zeta functions
| Python | lgpl-2.1 | mph-/lcapy | ---
+++
@@ -1,5 +1,5 @@
# SymPy symbols to exclude
-exclude = ('C', 'O', 'S', 'N', 'E', 'E1', 'Q')
+exclude = ('C', 'O', 'S', 'N', 'E', 'E1', 'Q', 'beta', 'gamma', 'zeta')
# Aliases for SymPy symbols
aliases = {'delta': 'DiracDelta', 'step': 'Heaviside', 'u': 'Heaviside',
@@ -12,6 +12,6 @@
import sympy as sym
print_expr_map = {sym.I: 'j'}
-# Hack to print i as j
+# Hack to pretty print i as j
from sympy.printing.pretty.pretty_symbology import atoms_table
atoms_table['ImaginaryUnit'] = '\u2149' |
b278cf74b6ac57daee8e4ead6044f43ffd89a1f1 | importer/importer/__init__.py | importer/importer/__init__.py | import aiohttp
import os.path
from datetime import datetime
from aioes import Elasticsearch
from .importer import import_data
from .kudago import KudaGo
from .utils import read_json_file
ELASTIC_ENDPOINTS = ['localhost:9200']
ELASTIC_ALIAS = 'theatrics'
async def initialize():
elastic = Elasticsearch(ELASTIC_ENDPOINTS)
module_path = os.path.dirname(__file__)
config_filename = os.path.join(module_path, 'configuration', 'index.json')
index_configuration = read_json_file(config_filename)
alias_name = ELASTIC_ALIAS
index_name = generate_index_name()
await elastic.indices.create(index_name, index_configuration)
await elastic.indices.put_alias(alias_name, index_name)
async def update(since):
async with aiohttp.ClientSession() as http_client:
elastic = Elasticsearch(ELASTIC_ENDPOINTS)
kudago = KudaGo(http_client)
await import_data(kudago, elastic, ELASTIC_ALIAS, since=since)
def generate_index_name():
return '{}-{}'.format(ELASTIC_ALIAS, int(datetime.now().timestamp()))
| import aiohttp
import os.path
from datetime import datetime
from aioes import Elasticsearch
from .importer import import_data
from .kudago import KudaGo
from .utils import read_json_file
ELASTIC_ENDPOINTS = ['localhost:9200']
ELASTIC_ALIAS = 'theatrics'
# commands
async def initialize():
elastic = Elasticsearch(ELASTIC_ENDPOINTS)
index_name = await create_new_index(elastic)
await switch_alias_to_index(elastic, ELASTIC_ALIAS, index_name)
async def update(since):
async with aiohttp.ClientSession() as http_client:
elastic = Elasticsearch(ELASTIC_ENDPOINTS)
kudago = KudaGo(http_client)
await import_data(kudago, elastic, ELASTIC_ALIAS, since=since)
# index management
async def create_new_index(elastic):
module_path = os.path.dirname(__file__)
config_filename = os.path.join(module_path, 'configuration', 'index.json')
index_configuration = read_json_file(config_filename)
index_name = generate_index_name()
await elastic.indices.create(index_name, index_configuration)
return index_name
async def switch_alias_to_index(elastic, alias_name, index_name):
existing_aliases = await elastic.indices.get_aliases(name=alias_name)
actions = [{
'add': {
'index': index_name,
'alias': alias_name
}
}]
for existing_index_name in existing_aliases:
actions.append({
'remove': {
'index': existing_index_name,
'alias': alias_name,
}
})
await elastic.indices.update_aliases(actions)
def generate_index_name():
return '{}-{}'.format(ELASTIC_ALIAS, int(datetime.now().timestamp()))
| Remove all previous aliases when initializing | Remove all previous aliases when initializing
| Python | mit | despawnerer/theatrics,despawnerer/theatrics,despawnerer/theatrics | ---
+++
@@ -12,17 +12,12 @@
ELASTIC_ALIAS = 'theatrics'
+# commands
+
async def initialize():
elastic = Elasticsearch(ELASTIC_ENDPOINTS)
- module_path = os.path.dirname(__file__)
- config_filename = os.path.join(module_path, 'configuration', 'index.json')
- index_configuration = read_json_file(config_filename)
-
- alias_name = ELASTIC_ALIAS
- index_name = generate_index_name()
-
- await elastic.indices.create(index_name, index_configuration)
- await elastic.indices.put_alias(alias_name, index_name)
+ index_name = await create_new_index(elastic)
+ await switch_alias_to_index(elastic, ELASTIC_ALIAS, index_name)
async def update(since):
@@ -32,5 +27,35 @@
await import_data(kudago, elastic, ELASTIC_ALIAS, since=since)
+# index management
+
+async def create_new_index(elastic):
+ module_path = os.path.dirname(__file__)
+ config_filename = os.path.join(module_path, 'configuration', 'index.json')
+ index_configuration = read_json_file(config_filename)
+ index_name = generate_index_name()
+ await elastic.indices.create(index_name, index_configuration)
+ return index_name
+
+
+async def switch_alias_to_index(elastic, alias_name, index_name):
+ existing_aliases = await elastic.indices.get_aliases(name=alias_name)
+ actions = [{
+ 'add': {
+ 'index': index_name,
+ 'alias': alias_name
+ }
+ }]
+ for existing_index_name in existing_aliases:
+ actions.append({
+ 'remove': {
+ 'index': existing_index_name,
+ 'alias': alias_name,
+ }
+ })
+
+ await elastic.indices.update_aliases(actions)
+
+
def generate_index_name():
return '{}-{}'.format(ELASTIC_ALIAS, int(datetime.now().timestamp())) |
3dd205a9dad39abb12e7a05c178117545402c2e1 | reinforcement-learning/train.py | reinforcement-learning/train.py | """This is the agent which currently takes the action with proper q learning."""
import time
start = time.time()
from tqdm import tqdm
import env
import os
import rl
env.make("text")
episodes = 10000
import argparse
parser = argparse.ArgumentParser(description="Train agent on the falling game.")
parser.add_argument("--remove-file", help="Remove existing q table.", default=True)
parser.add_argument("--episodes", type=str, help="Number of episodes to train for.", default=10000)
args = parser.parse_args()
if args.remove_file == True:
os.remove("q-table.npy")
rl.load_q()
elif args.remove_file == "False":
rl.load_q()
else:
print("Invalid argument.")
quit()
episodes = int(args.episodes)
with tqdm(total=episodes) as pbar:
for episode in range(episodes):
env.reset()
episode_reward = 0
for t in range(100):
episode_reward += env.actual_reward
if env.done:
pbar.update(1)
break
action = rl.choose_action(rl.table[env.object[0]])
rl.q(env.player, action)
episode_reward += env.reward(action)
env.action(action)
env.update()
rl.save_q()
print("Q table:")
print(rl.table[env.object[0]])
| """This is the agent which currently takes the action with proper q learning."""
import time
start = time.time()
from tqdm import tqdm
import env
import os
import rl
env.make("text")
episodes = 10000
import argparse
parser = argparse.ArgumentParser(description="Train agent on the falling game.")
parser.add_argument("--remove-file", help="Remove existing q table.", default=True)
parser.add_argument("--episodes", type=str, help="Number of episodes to train for.", default=10000)
args = parser.parse_args()
if args.remove_file == True:
os.remove("q-table.npy")
rl.load_q()
elif args.remove_file == "False":
rl.load_q()
else:
print("Invalid argument.")
quit()
episodes = int(args.episodes)
with tqdm(total=episodes) as pbar:
for episode in range(episodes):
env.reset()
episode_reward = 0
for t in range(100):
episode_reward += env.actual_reward
if env.done:
pbar.update(1)
break
action = rl.choose_action(env.player, "train")
rl.q(env.player, action)
episode_reward += env.reward(action)
env.action(action)
env.update()
rl.save_q()
print("Q table:")
print(rl.table[env.object[0]])
| Update to newest version of rl.py. | Update to newest version of rl.py.
| Python | mit | danieloconell/Louis | ---
+++
@@ -35,7 +35,7 @@
if env.done:
pbar.update(1)
break
- action = rl.choose_action(rl.table[env.object[0]])
+ action = rl.choose_action(env.player, "train")
rl.q(env.player, action)
episode_reward += env.reward(action)
env.action(action) |
f88c2135ddc197283bbfb8b481774deb613571cf | python/raindrops/raindrops.py | python/raindrops/raindrops.py | def raindrops(number):
if is_three_a_factor(number):
return "Pling"
return "{}".format(number)
def is_three_a_factor(number):
return number % 3 == 0
| def raindrops(number):
if is_three_a_factor(number):
return "Pling"
if is_five_a_factor(number):
return "Plang"
return "{}".format(number)
def is_three_a_factor(number):
return number % 3 == 0
def is_five_a_factor(number):
return number % 5 == 0
| Handle 5 as a factor | Handle 5 as a factor
| Python | mit | rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism | ---
+++
@@ -1,7 +1,12 @@
def raindrops(number):
if is_three_a_factor(number):
return "Pling"
+ if is_five_a_factor(number):
+ return "Plang"
return "{}".format(number)
def is_three_a_factor(number):
return number % 3 == 0
+
+def is_five_a_factor(number):
+ return number % 5 == 0 |
2f10aa07422c8132218d8af336406629b336550c | docs/src/conf.py | docs/src/conf.py | # -*- coding: utf-8 -*-
import os
import stat
from os.path import join, abspath
from subprocess import call
def prepare(globs, locs):
# RTD defaults the current working directory to where conf.py resides.
# In our case, that means <root>/docs/src/.
cwd = os.getcwd()
root = abspath(join(cwd, '..', '..'))
os.chdir(root)
# Download the PHP binary & composer.phar if necessary
base = 'https://github.com/Erebot/Buildenv/releases/download/1.4.0'
for f in ('php', 'composer.phar'):
call(['curl', '-L', '-z', f, '-o', f, '%s/%s' % (base, f)])
# Make sure the PHP interpreter is executable
os.chmod('./php', stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
# Call composer to download/update dependencies as necessary
os.environ['COMPOSER_CACHE_DIR'] = './cache'
call(['./php', 'composer.phar', 'update', '-n', '--ignore-platform-reqs',
'--no-progress'], env=os.environ)
# Load the second-stage configuration file.
os.chdir(cwd)
conf = join(root, 'vendor', 'erebot', 'buildenv', 'sphinx', 'rtd.py')
print "Including the second configuration file (%s)..." % (conf, )
execfile(conf, globs, locs)
prepare(globals(), locals())
| # -*- coding: utf-8 -*-
import os
import stat
from os.path import join, abspath
from subprocess import call
def prepare(globs, locs):
# RTD defaults the current working directory to where conf.py resides.
# In our case, that means <root>/docs/src/.
cwd = os.getcwd()
root = abspath(join(cwd, '..', '..'))
os.chdir(root)
# Download the PHP binary & composer.phar if necessary
base = 'https://github.com/Erebot/Buildenv/releases/download/1.4.0'
for f in ('php', 'composer.phar'):
call(['curl', '-L', '-z', f, '-o', f, '%s/%s' % (base, f)])
# Make sure the PHP interpreter is executable
os.chmod('./php', stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
# Call composer to download/update dependencies as necessary
os.environ['COMPOSER_CACHE_DIR'] = './cache'
call(['./php', 'composer.phar', 'update', '-n', '--ignore-platform-reqs',
'--no-progress'], env=os.environ)
# Load the second-stage configuration file.
os.chdir(cwd)
conf = join(root, 'vendor', 'erebot', 'buildenv', 'sphinx', 'rtd.py')
print "Including the second configuration file (%s)..." % (conf, )
exec(compile(open(conf).read(), conf, 'exec'), globs, locs)
prepare(globals(), locals())
| Replace execfile with py3-compatible equivalent | Replace execfile with py3-compatible equivalent
| Python | bsd-3-clause | fpoirotte/XRL | ---
+++
@@ -29,6 +29,6 @@
os.chdir(cwd)
conf = join(root, 'vendor', 'erebot', 'buildenv', 'sphinx', 'rtd.py')
print "Including the second configuration file (%s)..." % (conf, )
- execfile(conf, globs, locs)
+ exec(compile(open(conf).read(), conf, 'exec'), globs, locs)
prepare(globals(), locals()) |
5e5a6a55d43bf66c7f71d054b92a66528bf2a571 | driver/driver.py | driver/driver.py | from abc import ABCMeta, abstractmethod
class Driver(metaclass=ABCMeta):
@abstractmethod
def create(self):
pass
@abstractmethod
def resize(self, id, quota):
pass
@abstractmethod
def clone(self, id):
pass
@abstractmethod
def remove(self, id):
pass
@abstractmethod
def expose(self, id):
pass | from abc import ABCMeta, abstractmethod
class Driver(metaclass=ABCMeta):
@abstractmethod
def create(self, requirements):
pass
@abstractmethod
def _set_quota(self, id, quota):
pass
@abstractmethod
def resize(self, id, quota):
pass
@abstractmethod
def clone(self, id):
pass
@abstractmethod
def remove(self, id):
pass
@abstractmethod
def expose(self, id, host, permissions):
pass
| Fix inconsistency in parameters with base class | Fix inconsistency in parameters with base class
| Python | apache-2.0 | PressLabs/cobalt,PressLabs/cobalt | ---
+++
@@ -3,7 +3,11 @@
class Driver(metaclass=ABCMeta):
@abstractmethod
- def create(self):
+ def create(self, requirements):
+ pass
+
+ @abstractmethod
+ def _set_quota(self, id, quota):
pass
@abstractmethod
@@ -19,5 +23,5 @@
pass
@abstractmethod
- def expose(self, id):
+ def expose(self, id, host, permissions):
pass |
1fe377ec1957d570a1dcc860c2bda415088bf6be | dwight_chroot/platform_utils.py | dwight_chroot/platform_utils.py | import os
import pwd
import subprocess
from .exceptions import CommandFailed
def get_user_shell():
return pwd.getpwuid(os.getuid()).pw_shell
def execute_command_assert_success(cmd, **kw):
returned = execute_command(cmd, **kw)
if returned.returncode != 0:
raise CommandFailed("Command {0!r} failed with exit code {1}".format(cmd, returned))
return returned
def execute_command(cmd, **kw):
returned = subprocess.Popen(cmd, shell=True, **kw)
returned.wait()
return returned
| import os
import pwd
import subprocess
from .exceptions import CommandFailed
def get_user_shell():
return pwd.getpwuid(os.getuid()).pw_shell
def execute_command_assert_success(cmd, **kw):
returned = execute_command(cmd, **kw)
if returned.returncode != 0:
raise CommandFailed("Command {0!r} failed with exit code {1}".format(cmd, returned.returncode))
return returned
def execute_command(cmd, **kw):
returned = subprocess.Popen(cmd, shell=True, **kw)
returned.wait()
return returned
| Fix execute_command_assert_success return code logging | Fix execute_command_assert_success return code logging
| Python | bsd-3-clause | vmalloc/dwight,vmalloc/dwight,vmalloc/dwight | ---
+++
@@ -9,7 +9,7 @@
def execute_command_assert_success(cmd, **kw):
returned = execute_command(cmd, **kw)
if returned.returncode != 0:
- raise CommandFailed("Command {0!r} failed with exit code {1}".format(cmd, returned))
+ raise CommandFailed("Command {0!r} failed with exit code {1}".format(cmd, returned.returncode))
return returned
def execute_command(cmd, **kw): |
b1c5f75c266f5f5b9976ce2ca7c2b9065ef41bb1 | groupmestats/generatestats.py | groupmestats/generatestats.py | import argparse
import webbrowser
from .groupserializer import GroupSerializer
from .statistic import all_statistics
from .statistics import *
def gstat_stats():
parser = argparse.ArgumentParser(description="Generates stats for a group")
parser.add_argument("-g", "--group", dest="group_name", required=True,
help="Group to generate stats for.")
parser.add_argument("-s", "--stat", dest="stats", default=[],
action="append",
help=("Name of stat to generate. This may be specified"
" more than once. Choices: %s "
% ", ".join(all_statistics.keys())))
parser.add_argument("--all-stats", action="store_true", default=False,
help="Generate all possible stats.")
parser.add_argument("--ignore-user", dest="ignore_users", default=[],
action="append",
help="User to ignore. May be specified more than once.")
args = parser.parse_args()
stats = [stat_class() for name, stat_class in all_statistics.items()
if args.all_stats or name in args.stats]
if not stats:
parser.print_help()
raise RuntimeError("Must specify a valid --stat or use --all-stats")
(group, messages) = GroupSerializer.load(args.group_name)
for stat in stats:
stat.calculate(group, messages, ignore_users=args.ignore_users)
for stat in stats:
output_html_filename = stat.show()
try:
# webbrowser.open_new_tab(output_html_filename)
pass
except:
pass
| import argparse
import webbrowser
from .groupserializer import GroupSerializer
from .statistic import all_statistics
from .statistics import *
def gstat_stats():
parser = argparse.ArgumentParser(description="Generates stats for a group")
parser.add_argument("-g", "--group", dest="group_name", required=True,
help="Group to generate stats for.")
parser.add_argument("-s", "--stat", dest="stats", default=[],
action="append",
help=("Name of stat to generate. This may be specified"
" more than once. Choices: %s "
% ", ".join(all_statistics.keys())))
parser.add_argument("--all-stats", action="store_true", default=False,
help="Generate all possible stats.")
parser.add_argument("--ignore-user", dest="ignore_users", default=[],
action="append",
help="User to ignore. May be specified more than once.")
args = parser.parse_args()
stats = [stat_class() for name, stat_class in all_statistics.items()
if args.all_stats or name in args.stats]
print("args: %s" % str(args))
if not stats:
parser.print_help()
raise RuntimeError("Must specify a valid --stat or use --all-stats")
(group, messages) = GroupSerializer.load(args.group_name)
for stat in stats:
stat.calculate(group, messages, ignore_users=args.ignore_users)
for stat in stats:
output_html_filename = stat.show()
try:
# webbrowser.open_new_tab(output_html_filename)
pass
except:
pass
| Print args when generating stats | Print args when generating stats
| Python | mit | kjteske/groupmestats,kjteske/groupmestats | ---
+++
@@ -22,6 +22,8 @@
args = parser.parse_args()
stats = [stat_class() for name, stat_class in all_statistics.items()
if args.all_stats or name in args.stats]
+
+ print("args: %s" % str(args))
if not stats:
parser.print_help()
raise RuntimeError("Must specify a valid --stat or use --all-stats") |
7b7f33439b16faeef67022374cf88ba9a275ce8a | flocker/filesystems/interfaces.py | flocker/filesystems/interfaces.py | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Interfaces that filesystem APIs need to expose.
"""
from __future__ import absolute_import
from zope.interface import Interface
class IFilesystemSnapshots(Interface):
"""
Support creating and listing snapshots of a specific filesystem.
"""
def create(name):
"""
Create a snapshot of the filesystem.
:param name: The name of the snapshot.
:type name: :py:class:`flocker.snapshots.SnapshotName`
:return: Deferred that fires on snapshot creation, or errbacks if
snapshotting failed. The Deferred should support cancellation
if at all possible.
"""
def list():
"""
Return all the filesystem's snapshots.
:return: Deferred that fires with a ``list`` of
:py:class:`flocker.snapshots.SnapshotName`. This will likely be
improved in later iterations.
"""
| # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Interfaces that filesystem APIs need to expose.
"""
from __future__ import absolute_import
from zope.interface import Interface
class IFilesystemSnapshots(Interface):
"""
Support creating and listing snapshots of a specific filesystem.
"""
def create(name):
"""
Create a snapshot of the filesystem.
:param name: The name of the snapshot.
:type name: :py:class:`flocker.snapshots.SnapshotName`
:return: Deferred that fires on snapshot creation, or errbacks if
snapshotting failed. The Deferred should support cancellation
if at all possible.
"""
def list():
"""
Return all the filesystem's snapshots.
:return: Deferred that fires with a ``list`` of
:py:class:`flocker.snapshots.SnapshotName`.
"""
| Address review comment: Don't state the obvious. | Address review comment: Don't state the obvious.
| Python | apache-2.0 | LaynePeng/flocker,agonzalezro/flocker,AndyHuu/flocker,achanda/flocker,jml/flocker,AndyHuu/flocker,lukemarsden/flocker,mbrukman/flocker,runcom/flocker,Azulinho/flocker,jml/flocker,mbrukman/flocker,w4ngyi/flocker,hackday-profilers/flocker,achanda/flocker,lukemarsden/flocker,achanda/flocker,beni55/flocker,lukemarsden/flocker,beni55/flocker,Azulinho/flocker,mbrukman/flocker,hackday-profilers/flocker,moypray/flocker,AndyHuu/flocker,LaynePeng/flocker,moypray/flocker,adamtheturtle/flocker,w4ngyi/flocker,1d4Nf6/flocker,agonzalezro/flocker,Azulinho/flocker,wallnerryan/flocker-profiles,adamtheturtle/flocker,adamtheturtle/flocker,LaynePeng/flocker,beni55/flocker,moypray/flocker,runcom/flocker,jml/flocker,hackday-profilers/flocker,agonzalezro/flocker,runcom/flocker,wallnerryan/flocker-profiles,1d4Nf6/flocker,1d4Nf6/flocker,wallnerryan/flocker-profiles,w4ngyi/flocker | ---
+++
@@ -31,6 +31,5 @@
Return all the filesystem's snapshots.
:return: Deferred that fires with a ``list`` of
- :py:class:`flocker.snapshots.SnapshotName`. This will likely be
- improved in later iterations.
+ :py:class:`flocker.snapshots.SnapshotName`.
""" |
df51d042bf1958f48fc39f1f3870285c87491243 | lemon/templatetags/main_menu.py | lemon/templatetags/main_menu.py | from django.template import Library, Variable
from django.template import TemplateSyntaxError, VariableDoesNotExist
from django.template.defaulttags import URLNode
from ..models import MenuItem
from ..settings import CONFIG
register = Library()
class MainMenuItemURLNode(URLNode):
def __init__(self, content_type):
self.content_type = Variable(content_type)
self.args = ()
self.kwargs = {}
self.asvar = False
self.legacy_view_name = True
def render(self, context):
try:
content_type = self.content_type.resolve(context)
opts = content_type.model_class()._meta
app_label = opts.app_label
module_name = opts.module_name
self.view_name = 'admin:%s_%s_changelist' % \
(app_label, module_name)
except VariableDoesNotExist:
return ''
return super(MainMenuItemURLNode, self).render(context)
@register.inclusion_tag('lemon/main_menu.html')
def main_menu():
queryset = MenuItem.objects.select_related('section', 'content_type')
queryset = queryset.order_by('section__position', 'position')
return {'menu_items': queryset, 'menu_links': CONFIG['MENU_LINKS']}
@register.tag
def main_menu_item_url(parser, token):
try:
tag_name, content_type = token.split_contents()
except ValueError:
raise TemplateSyntaxError(
'%r tag requiresa single argument' % token.contents.split()[0]
)
return MainMenuItemURLNode(content_type)
| from django.core.urlresolvers import reverse, NoReverseMatch
from django.template import Library, Variable, Node
from django.template import TemplateSyntaxError, VariableDoesNotExist
from django.template.defaulttags import URLNode
from ..models import MenuItem
from ..settings import CONFIG
register = Library()
class MainMenuItemURLNode(Node):
def __init__(self, content_type):
self.content_type = Variable(content_type)
def render(self, context):
try:
content_type = self.content_type.resolve(context)
except VariableDoesNotExist:
return ''
opts = content_type.model_class()._meta
app_label = opts.app_label
module_name = opts.module_name
view_name = 'admin:%s_%s_changelist' % \
(app_label, module_name)
try:
return reverse(view_name)
except NoReverseMatch:
return ''
@register.inclusion_tag('lemon/main_menu.html')
def main_menu():
queryset = MenuItem.objects.select_related('section', 'content_type')
queryset = queryset.order_by('section__position', 'position')
return {'menu_items': queryset, 'menu_links': CONFIG['MENU_LINKS']}
@register.tag
def main_menu_item_url(parser, token):
try:
tag_name, content_type = token.split_contents()
except ValueError:
raise TemplateSyntaxError(
'%r tag requires a single argument' % token.contents.split()[0]
)
return MainMenuItemURLNode(content_type)
| Fix main menu url reversing in admin | Fix main menu url reversing in admin
| Python | bsd-3-clause | trilan/lemon,trilan/lemon,trilan/lemon | ---
+++
@@ -1,4 +1,5 @@
-from django.template import Library, Variable
+from django.core.urlresolvers import reverse, NoReverseMatch
+from django.template import Library, Variable, Node
from django.template import TemplateSyntaxError, VariableDoesNotExist
from django.template.defaulttags import URLNode
@@ -9,26 +10,25 @@
register = Library()
-class MainMenuItemURLNode(URLNode):
+class MainMenuItemURLNode(Node):
def __init__(self, content_type):
self.content_type = Variable(content_type)
- self.args = ()
- self.kwargs = {}
- self.asvar = False
- self.legacy_view_name = True
def render(self, context):
try:
content_type = self.content_type.resolve(context)
- opts = content_type.model_class()._meta
- app_label = opts.app_label
- module_name = opts.module_name
- self.view_name = 'admin:%s_%s_changelist' % \
- (app_label, module_name)
except VariableDoesNotExist:
return ''
- return super(MainMenuItemURLNode, self).render(context)
+ opts = content_type.model_class()._meta
+ app_label = opts.app_label
+ module_name = opts.module_name
+ view_name = 'admin:%s_%s_changelist' % \
+ (app_label, module_name)
+ try:
+ return reverse(view_name)
+ except NoReverseMatch:
+ return ''
@register.inclusion_tag('lemon/main_menu.html')
@@ -44,6 +44,6 @@
tag_name, content_type = token.split_contents()
except ValueError:
raise TemplateSyntaxError(
- '%r tag requiresa single argument' % token.contents.split()[0]
+ '%r tag requires a single argument' % token.contents.split()[0]
)
return MainMenuItemURLNode(content_type) |
e548713f5192d125b1313fa955240965a1136de8 | plugin/__init__.py | plugin/__init__.py | ########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# * See the License for the specific language governing permissions and
# * limitations under the License.
| # -*- coding: utf-8 -*-
########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# * See the License for the specific language governing permissions and
# * limitations under the License.
| UPDATE init; add utf-8 encoding | UPDATE init; add utf-8 encoding
| Python | apache-2.0 | fastconnect/cloudify-azure-plugin | ---
+++
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved
# |
28786f30be37bb43a175262f96b618fc440d5ace | send-email.py | send-email.py | #!/usr/bin/env python3
import datetime
import os
import sys
import smtplib
from email.mime.text import MIMEText
def timeString():
return str(datetime.datetime.now())
if not os.path.exists('email-list'):
print(timeString(), ':\tERROR: email-list not found.', sep='')
quit(1)
if not os.path.exists('credentials'):
print(timeString(), ':\tERROR: credentials not found.', sep='')
quit(1)
with open('credentials', 'r') as _file:
_lines = [str(e).strip('\n') for e in _file]
server = _lines[0]
port = _lines[1]
username = _lines[2]
password = _lines[3]
with open('new-products.html', 'r') as _file:
_message = _file.read()
with open('email-list', 'r') as _file:
recipients = [e.strip('\n') for e in _file]
session=smtplib.SMTP(server, port)
session.ehlo()
session.starttls()
session.login(username, password)
for message_to in recipients:
msg = MIMEText(_message, 'html')
msg['To'] = message_to
msg['From'] = username
msg['Subject'] = 'ALERT: New Cymbals detected on mycymbal.com'
msg = msg.as_string()
session.sendmail(username, message_to, msg)
print(timeString(), ':\tEmailed ', message_to, sep='')
session.quit()
| #!/usr/bin/env python3
import datetime
import os
import sys
import smtplib
from email.mime.text import MIMEText
def timeString():
return str(datetime.datetime.now())
if not os.path.exists('email-list'):
print(timeString(), ':\tERROR: email-list not found.', sep='')
quit(1)
if not os.path.exists('credentials'):
print(timeString(), ':\tERROR: credentials not found.', sep='')
quit(1)
with open('credentials', 'r') as _file:
_lines = [str(e).strip('\n') for e in _file]
server = _lines[0]
port = _lines[1]
username = _lines[2]
password = _lines[3]
with open('new-products.html', 'r') as _file:
_message = _file.read()
with open('email-list', 'r') as _file:
recipients = [e.strip('\n') for e in _file]
session=smtplib.SMTP(server, port)
session.ehlo()
session.starttls()
session.login(username, password)
for message_to in recipients:
msg = MIMEText(_message, 'html')
msg['To'] = message_to
msg['From'] = username
msg['Subject'] = 'MyCymbal Digest'
msg = msg.as_string()
session.sendmail(username, message_to, msg)
print(timeString(), ':\tEmailed ', message_to, sep='')
session.quit()
| Change email subject. Not much of an ALERT if it happens every day. | Change email subject. Not much of an ALERT if it happens every day.
| Python | unlicense | nerflad/mds-new-products,nerflad/mds-new-products,nerflad/mds-new-products | ---
+++
@@ -39,7 +39,7 @@
msg = MIMEText(_message, 'html')
msg['To'] = message_to
msg['From'] = username
- msg['Subject'] = 'ALERT: New Cymbals detected on mycymbal.com'
+ msg['Subject'] = 'MyCymbal Digest'
msg = msg.as_string()
session.sendmail(username, message_to, msg)
print(timeString(), ':\tEmailed ', message_to, sep='') |
400c506627deca5d85454928254b1968e09dc33e | scrape.py | scrape.py | import scholarly
import requests
_EXACT_SEARCH = '/scholar?q="{}"'
_START_YEAR = '&as_ylo={}'
_END_YEAR = '&as_yhi={}'
def search(query, exact=True, start_year=None, end_year=None):
"""Search by scholar query and return a generator of Publication objects"""
url = _EXACT_SEARCH.format(requests.utils.quote(query))
if start_year:
url += _START_YEAR.format(start_year)
if end_year:
url += _END_YEAR.format(end_year)
soup = scholarly._get_soup(url)
return scholarly._search_scholar_soup(soup)
if __name__ == '__main__':
s = search("Cure Alzheimer's Fund", start_year=2015, end_year=2015)
num = 0
for x in s:
x.fill()
stuff = ['title', 'author', 'journal', 'volume', 'issue']
for thing in stuff:
if thing in x.bib:
print("{}: {}".format(thing, x.bib[thing]))
num += 1
print("Number of results:", num)
| import re
import requests
import scholarly
_EXACT_SEARCH = '/scholar?q="{}"'
_START_YEAR = '&as_ylo={}'
_END_YEAR = '&as_yhi={}'
class Papers(object):
"""Wrapper around scholarly._search_scholar_soup that allows one to get the
number of papers found in the search with len()"""
def __init__(self, query, start_year=None, end_year=None):
url = _EXACT_SEARCH.format(requests.utils.quote(query))
if start_year:
url += _START_YEAR.format(start_year)
if end_year:
url += _END_YEAR.format(end_year)
soup = scholarly._get_soup(url)
results = soup.find('div', id='gs_ab_md').text
self.num = int(re.search(r'\d+ results', results).group(0).split()[0])
self.papers = scholarly._search_scholar_soup(soup)
def __len__(self):
return self.num
def __iter__(self):
return (paper.fill().bib for paper in self.papers)
def get_published_papers():
""" Returns a generator that returns dicts with paper metadata."""
return Papers("Cure Alzheimer's Fund", start_year=2015, end_year=2015)
def main():
papers = get_published_papers()
print("Number of results:", len(papers))
for paper in papers:
stuff = ['title', 'author', 'journal', 'volume', 'issue']
for thing in stuff:
if thing in paper:
print("{}: {}".format(thing, paper[thing]))
if __name__ == '__main__':
main()
| Allow getting number of results found with len() | Allow getting number of results found with len()
| Python | mit | Spferical/cure-alzheimers-fund-tracker,Spferical/cure-alzheimers-fund-tracker,Spferical/cure-alzheimers-fund-tracker | ---
+++
@@ -1,28 +1,48 @@
+import re
+import requests
import scholarly
-import requests
_EXACT_SEARCH = '/scholar?q="{}"'
_START_YEAR = '&as_ylo={}'
_END_YEAR = '&as_yhi={}'
-def search(query, exact=True, start_year=None, end_year=None):
- """Search by scholar query and return a generator of Publication objects"""
- url = _EXACT_SEARCH.format(requests.utils.quote(query))
- if start_year:
- url += _START_YEAR.format(start_year)
- if end_year:
- url += _END_YEAR.format(end_year)
- soup = scholarly._get_soup(url)
- return scholarly._search_scholar_soup(soup)
+
+
+class Papers(object):
+ """Wrapper around scholarly._search_scholar_soup that allows one to get the
+ number of papers found in the search with len()"""
+ def __init__(self, query, start_year=None, end_year=None):
+ url = _EXACT_SEARCH.format(requests.utils.quote(query))
+ if start_year:
+ url += _START_YEAR.format(start_year)
+ if end_year:
+ url += _END_YEAR.format(end_year)
+ soup = scholarly._get_soup(url)
+ results = soup.find('div', id='gs_ab_md').text
+ self.num = int(re.search(r'\d+ results', results).group(0).split()[0])
+
+ self.papers = scholarly._search_scholar_soup(soup)
+
+ def __len__(self):
+ return self.num
+
+ def __iter__(self):
+ return (paper.fill().bib for paper in self.papers)
+
+
+def get_published_papers():
+ """ Returns a generator that returns dicts with paper metadata."""
+ return Papers("Cure Alzheimer's Fund", start_year=2015, end_year=2015)
+
+
+def main():
+ papers = get_published_papers()
+ print("Number of results:", len(papers))
+ for paper in papers:
+ stuff = ['title', 'author', 'journal', 'volume', 'issue']
+ for thing in stuff:
+ if thing in paper:
+ print("{}: {}".format(thing, paper[thing]))
if __name__ == '__main__':
- s = search("Cure Alzheimer's Fund", start_year=2015, end_year=2015)
- num = 0
- for x in s:
- x.fill()
- stuff = ['title', 'author', 'journal', 'volume', 'issue']
- for thing in stuff:
- if thing in x.bib:
- print("{}: {}".format(thing, x.bib[thing]))
- num += 1
+ main()
- print("Number of results:", num) |
ce2ea43a9ca49caa50e26bc7d7e11ba97edea929 | src/zeit/content/article/edit/browser/tests/test_header.py | src/zeit/content/article/edit/browser/tests/test_header.py | import zeit.content.article.edit.browser.testing
class HeaderModules(zeit.content.article.edit.browser.testing.EditorTestCase):
def test_can_create_module_by_drag_and_drop(self):
s = self.selenium
self.add_article()
block = 'quiz'
# copy&paste from self.create_block()
s.click('link=Struktur')
s.click('link=Header')
s.waitForElementPresent('css=#header-modules .module')
block_sel = '.block.type-{0}'.format(block)
count = s.getCssCount('css={0}'.format(block_sel))
s.dragAndDropToObject(
'css=#header-modules .module[cms\\:block_type={0}]'.format(block),
'css=#editable-header > .landing-zone', '10,10')
s.waitForCssCount('css={0}'.format(block_sel), count + 1)
| import zeit.content.article.edit.browser.testing
class HeaderModules(zeit.content.article.edit.browser.testing.EditorTestCase):
def test_can_create_module_by_drag_and_drop(self):
s = self.selenium
self.add_article()
# Select header that allows header module
s.click('css=#edit-form-misc .edit-bar .fold-link')
s.select('id=options-template.template', 'Kolumne')
s.waitForVisible('css=.fieldname-header_layout')
s.select('id=options-template.header_layout', 'Standard')
s.type('id=options-template.header_layout', '\t')
s.pause(500)
block = 'quiz'
# copy&paste from self.create_block()
s.click('link=Struktur')
s.click('link=Header')
s.waitForElementPresent('css=#header-modules .module')
block_sel = '.block.type-{0}'.format(block)
count = s.getCssCount('css={0}'.format(block_sel))
s.dragAndDropToObject(
'css=#header-modules .module[cms\\:block_type={0}]'.format(block),
'css=#editable-header > .landing-zone', '10,10')
s.waitForCssCount('css={0}'.format(block_sel), count + 1)
| Fix test, needs to select proper header for header-module to be enabled (belongs to commit:eb1b6fa) | ZON-3167: Fix test, needs to select proper header for header-module to be enabled (belongs to commit:eb1b6fa)
| Python | bsd-3-clause | ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article | ---
+++
@@ -6,6 +6,14 @@
def test_can_create_module_by_drag_and_drop(self):
s = self.selenium
self.add_article()
+ # Select header that allows header module
+ s.click('css=#edit-form-misc .edit-bar .fold-link')
+ s.select('id=options-template.template', 'Kolumne')
+ s.waitForVisible('css=.fieldname-header_layout')
+ s.select('id=options-template.header_layout', 'Standard')
+ s.type('id=options-template.header_layout', '\t')
+ s.pause(500)
+
block = 'quiz'
# copy&paste from self.create_block()
s.click('link=Struktur') |
2e9cb250d58474354bdfff1edb4fc9e71ee95d60 | lightbus/utilities/importing.py | lightbus/utilities/importing.py | import importlib
import logging
from typing import Sequence, Tuple, Callable
import pkg_resources
logger = logging.getLogger(__name__)
def import_module_from_string(name):
return importlib.import_module(name)
def import_from_string(name):
components = name.split(".")
mod = __import__(components[0])
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
def load_entrypoint_classes(entrypoint_name) -> Sequence[Tuple[str, str, Callable]]:
"""Load classes specified in an entrypoint
Entrypoints are specified in setup.py, and Lightbus uses them to
discover plugins & transports.
"""
found_classes = []
for entrypoint in pkg_resources.iter_entry_points(entrypoint_name):
class_ = entrypoint.load()
found_classes.append((entrypoint.module_name, entrypoint.name, class_))
return found_classes
| import importlib
import logging
import sys
from typing import Sequence, Tuple, Callable
import pkg_resources
logger = logging.getLogger(__name__)
def import_module_from_string(name):
if name in sys.modules:
return sys.modules[name]
else:
return importlib.import_module(name)
def import_from_string(name):
components = name.split(".")
mod = __import__(components[0])
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
def load_entrypoint_classes(entrypoint_name) -> Sequence[Tuple[str, str, Callable]]:
"""Load classes specified in an entrypoint
Entrypoints are specified in setup.py, and Lightbus uses them to
discover plugins & transports.
"""
found_classes = []
for entrypoint in pkg_resources.iter_entry_points(entrypoint_name):
class_ = entrypoint.load()
found_classes.append((entrypoint.module_name, entrypoint.name, class_))
return found_classes
| Fix to import_module_from_string() to prevent multiple imports | Fix to import_module_from_string() to prevent multiple imports
| Python | apache-2.0 | adamcharnock/lightbus | ---
+++
@@ -1,5 +1,6 @@
import importlib
import logging
+import sys
from typing import Sequence, Tuple, Callable
import pkg_resources
@@ -8,7 +9,10 @@
def import_module_from_string(name):
- return importlib.import_module(name)
+ if name in sys.modules:
+ return sys.modules[name]
+ else:
+ return importlib.import_module(name)
def import_from_string(name): |
0c18e83248a752a3191da1d9c8369fafc2b61674 | purepython/urls.py | purepython/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'purepython.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
from fb.views import index
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', index),
url(r'^admin/', include(admin.site.urls)),
)
| Add url to access the index view. | Add url to access the index view.
| Python | apache-2.0 | pure-python/brainmate | ---
+++
@@ -1,12 +1,11 @@
from django.conf.urls import patterns, include, url
+from django.contrib import admin
-from django.contrib import admin
+from fb.views import index
+
admin.autodiscover()
urlpatterns = patterns('',
- # Examples:
- # url(r'^$', 'purepython.views.home', name='home'),
- # url(r'^blog/', include('blog.urls')),
-
+ url(r'^$', index),
url(r'^admin/', include(admin.site.urls)),
) |
8b9065b99c8bcbb401f12e9e10b23d6ea4b976f0 | runtests.py | runtests.py | #!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
def main():
import warnings
warnings.filterwarnings('error', category=DeprecationWarning)
if not settings.configured:
# Dynamically configure the Django settings with the minimum necessary to
# get Django running tests
settings.configure(
INSTALLED_APPS=[
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.admin',
'django.contrib.sessions',
'parse_push',
],
# Django still complains? :(
DATABASE_ENGINE='django.db.backends.sqlite3',
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}
},
# MEDIA_PATH='/media/',
# ROOT_URLCONF='parse_push.tests.urls',
# DEBUG=True,
# TEMPLATE_DEBUG=True,
)
# Compatibility with Django 1.7's stricter initialization
if hasattr(django, 'setup'):
django.setup()
from django.test.utils import get_runner
test_runner = get_runner(settings)(verbosity=2, interactive=True)
if '--failfast' in sys.argv:
test_runner.failfast = True
failures = test_runner.run_tests(['parse_push'])
sys.exit(failures)
if __name__ == '__main__':
main() | #!/usr/bin/env python
import sys
import django
from django.conf import settings
def main():
import warnings
warnings.filterwarnings('error', category=DeprecationWarning)
if not settings.configured:
# Dynamically configure the Django settings with the minimum necessary to
# get Django running tests
settings.configure(
INSTALLED_APPS=[
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.admin',
'django.contrib.sessions',
'parse_push',
],
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
DEBUG=True,
# ROOT_URLCONF='testproject.urls',
)
# Compatibility with Django 1.7's stricter initialization
if hasattr(django, 'setup'):
django.setup()
from django.test.utils import get_runner
test_runner = get_runner(settings)(verbosity=2, interactive=True)
if '--failfast' in sys.argv:
test_runner.failfast = True
failures = test_runner.run_tests(['parse_push'])
sys.exit(failures)
if __name__ == '__main__':
main() | Remove ':memory:' as that is default | Remove ':memory:' as that is default
| Python | bsd-3-clause | willandskill/django-parse-push | ---
+++
@@ -1,6 +1,5 @@
#!/usr/bin/env python
-import os
import sys
import django
@@ -22,18 +21,13 @@
'django.contrib.sessions',
'parse_push',
],
- # Django still complains? :(
- DATABASE_ENGINE='django.db.backends.sqlite3',
- DATABASES = {
+ DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
- 'NAME': ':memory:'
}
},
- # MEDIA_PATH='/media/',
- # ROOT_URLCONF='parse_push.tests.urls',
- # DEBUG=True,
- # TEMPLATE_DEBUG=True,
+ DEBUG=True,
+ # ROOT_URLCONF='testproject.urls',
)
# Compatibility with Django 1.7's stricter initialization |
d2716cf8a5d605098b296ab835c1f4115dd45a5b | test/integration/ggrc/models/__init__.py | test/integration/ggrc/models/__init__.py | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
| # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
| Create mixins package for testing | Create mixins package for testing
| Python | apache-2.0 | VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,kr41/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,selahssea/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,j0gurt/ggrc-core,kr41/ggrc-core,edofic/ggrc-core,andrei-karalionak/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,edofic/ggrc-core,josthkko/ggrc-core,edofic/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,j0gurt/ggrc-core,plamut/ggrc-core,josthkko/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,kr41/ggrc-core,kr41/ggrc-core,edofic/ggrc-core,josthkko/ggrc-core | ---
+++
@@ -1,3 +1,2 @@
# Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
- |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.