commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
56e2bea0798ae3afbc50d53947e505e7df9edba3 | config/invariant_checks.py | config/invariant_checks.py | from sts.invariant_checker import InvariantChecker
def check_for_loops_or_connectivity(simulation):
from sts.invariant_checker import InvariantChecker
result = InvariantChecker.check_loops(simulation)
if result:
return result
result = InvariantChecker.python_check_connectivity(simulation)
if not result:
... | from sts.invariant_checker import InvariantChecker
import sys
def bail_on_connectivity(simulation):
result = InvariantChecker.python_check_connectivity(simulation)
if not result:
print "Connectivity established - bailing out"
sys.exit(0)
return []
def check_for_loops_or_connectivity(simulation):
resul... | Add a new invariant check: check blackholes *or* loops | Add a new invariant check: check blackholes *or* loops
| Python | apache-2.0 | ucb-sts/sts,jmiserez/sts,jmiserez/sts,ucb-sts/sts |
d58c04d9745f1a0af46f35fba7b3e2aef704547e | application.py | application.py | import os
from flask import Flask
from whitenoise import WhiteNoise
from app import create_app
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'app', 'static')
STATIC_URL = 'static/'
app = Flask('app')
create_app(app)
application = WhiteNoise(app, STATIC_ROOT, STA... | import os
from flask import Flask
from whitenoise import WhiteNoise
from app import create_app
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'app', 'static')
STATIC_URL = 'static/'
app = Flask('app')
create_app(app)
app.wsgi_app = WhiteNoise(app.wsgi_app, STATIC... | Make Whitenoise serve static assets | Make Whitenoise serve static assets
Currently it’s not configured properly, so isn’t having any effect.
This change makes it wrap the Flask app, so it intercepts any requests
for static content.
Follows the pattern documented in http://whitenoise.evans.io/en/stable/flask.html#enable-whitenoise
| Python | mit | alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin |
7231111564145bdbc773ed2bb5479b6edc0c7426 | issues/admin.py | issues/admin.py | from django.contrib.admin import site, ModelAdmin
from .models import Issue, Jurisdiction, Service, Application
class ApplicationAdmin(ModelAdmin):
list_display = ('identifier', 'name', 'active')
list_filter = ('active',)
search_fields = ('identifier', 'name',)
def get_readonly_fields(self, requ... | from django.contrib.admin import site, ModelAdmin
from parler.admin import TranslatableAdmin
from .models import Issue, Jurisdiction, Service, Application
class ApplicationAdmin(ModelAdmin):
list_display = ('identifier', 'name', 'active')
list_filter = ('active',)
search_fields = ('identifier', 'name',)
... | Use a `TranslatableAdmin` for `Service`s | Use a `TranslatableAdmin` for `Service`s
Fixes #70
| Python | mit | 6aika/issue-reporting,6aika/issue-reporting,6aika/issue-reporting |
4d446f6b810fdb1a996ab9b65259c1212c6b951a | connect_to_postgres.py | connect_to_postgres.py | import os
import psycopg2
import urlparse
urlparse.uses_netloc.append("postgres")
url = urlparse.urlparse(os.environ["DATABASE_URL"])
conn = psycopg2.connect(
database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port
)
cur = conn.cursor()
cur.execute("SE... | import os
import psycopg2
import urlparse
# urlparse.uses_netloc.append("postgres")
# url = urlparse.urlparse(os.environ["DATABASE_URL"])
# conn = psycopg2.connect(
# database=url.path[1:],
# user=url.username,
# password=url.password,
# host=url.hostname,
# port=url.port
# )
# cur = conn.cursor(... | Test functional version of connecting to postgres | Test functional version of connecting to postgres
| Python | mit | gsganden/pitcher-reports,gsganden/pitcher-reports |
5839e70f2ffab6640997e3a609a26e50ff2b4da6 | opps/containers/urls.py | opps/containers/urls.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
from django.conf import settings
from django.views.decorators.cache import cache_page
from .views import ContainerList, ContainerDetail
from .views import Search
from opps.contrib.feeds.views import ContainerFeed, ChannelFeed
ur... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
from django.conf import settings
from django.views.decorators.cache import cache_page
from .views import ContainerList, ContainerDetail
from .views import ContainerAPIList, ContainerAPIDetail
from .views import Search
from opps.co... | Add url entry container api | Add url entry container api
| Python | mit | jeanmask/opps,williamroot/opps,opps/opps,opps/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps,opps/opps,jeanmask/opps,williamroot/opps,opps/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,YACOWS/opps |
2205ea40f64b09f611b7f6cb4c9716d8e29136d4 | grammpy/Rule.py | grammpy/Rule.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
class Rule:
pass
| #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from grammpy import EPSILON
class Rule:
right = [EPSILON]
left = [EPSILON]
rule = ([EPSILON], [EPSILON])
rules = [([EPSILON], [EPSILON])]
def is_regular(self):
return False
... | Add base interface for rule | Add base interface for rule
| Python | mit | PatrikValkovic/grammpy |
0ea263fa9a496d8dbd8ff3f966cc23eba170842c | django_mfa/models.py | django_mfa/models.py | from django.db import models
from django.conf import settings
class UserOTP(models.Model):
OTP_TYPES = (
('HOTP', 'hotp'),
('TOTP', 'totp'),
)
user = models.OneToOneField(settings.AUTH_USER_MODEL)
otp_type = models.CharField(max_length=20, choices=OTP_TYPES)
secre... | from django.conf import settings
from django.db import models
class UserOTP(models.Model):
OTP_TYPES = (
('HOTP', 'hotp'),
('TOTP', 'totp'),
)
user = models.OneToOneField(settings.AUTH_USER_MODEL)
otp_type = models.CharField(max_length=20, choices=OTP_TYPES)
secret_key = models.C... | Remove try/except from determing if mfa is enabled | Remove try/except from determing if mfa is enabled
| Python | mit | MicroPyramid/django-mfa,MicroPyramid/django-mfa,MicroPyramid/django-mfa |
2bdbcf41cc99f9c7430f8d429cc8d2a5e2ee6701 | pyrho/NEURON/minimal.py | pyrho/NEURON/minimal.py | # minNEURON.py
cell = h.SectionList()
soma = h.Section(name='soma') #create soma
soma.push()
#h.topology()
# Geometry
soma.nseg = 1
soma.L = 20
soma.diam = 20
# Biophysics
for sec in h.allsec():
sec.Ra = 100
sec.cm = 1
sec.insert('pas')
#sec.insert('hh') # insert hh
cell.append(sec)
#h('objre... | # minNEURON.py
from neuron import h
cell = h.SectionList()
soma = h.Section(name='soma') #create soma
soma.push()
#h.topology()
# Geometry
soma.nseg = 1
soma.L = 20
soma.diam = 20
# Biophysics
for sec in h.allsec():
sec.Ra = 100
sec.cm = 1
sec.insert('pas')
#sec.insert('hh') # insert hh
cell.a... | Add import to stop warnings | Add import to stop warnings
| Python | bsd-3-clause | ProjectPyRhO/PyRhO,ProjectPyRhO/PyRhO |
be16b3c2b67f160e46ed951a8e9e691bc09b8d05 | easypyplot/pdf.py | easypyplot/pdf.py | """
* Copyright (c) 2016. Mingyu Gao
* All rights reserved.
*
"""
import matplotlib.backends.backend_pdf
from .format import paper_plot
def plot_setup(name, dims, fontsize=9):
""" Setup a PDF page for plot.
name: PDF file name. If not ending with .pdf, will automatically append.
dims: dimension of the... | """
* Copyright (c) 2016. Mingyu Gao
* All rights reserved.
*
"""
from contextlib import contextmanager
import matplotlib.backends.backend_pdf
from .format import paper_plot
def plot_setup(name, figsize=None, fontsize=9):
""" Setup a PDF page for plot.
name: PDF file name. If not ending with .pdf, will au... | Add a context manager for PDF plot. | Add a context manager for PDF plot.
| Python | bsd-3-clause | gaomy3832/easypyplot,gaomy3832/easypyplot |
792d0ace4f84023d1132f8d61a88bd48e3d7775d | test/contrib/test_pyopenssl.py | test/contrib/test_pyopenssl.py | from nose.plugins.skip import SkipTest
from urllib3.packages import six
if six.PY3:
raise SkipTest('Testing of PyOpenSSL disabled on PY3')
try:
from urllib3.contrib.pyopenssl import (inject_into_urllib3,
extract_from_urllib3)
except ImportError as e:
raise SkipTe... | from nose.plugins.skip import SkipTest
from urllib3.packages import six
try:
from urllib3.contrib.pyopenssl import (inject_into_urllib3,
extract_from_urllib3)
except ImportError as e:
raise SkipTest('Could not import PyOpenSSL: %r' % e)
from ..with_dummyserver.test_... | Enable PyOpenSSL testing on Python 3. | Enable PyOpenSSL testing on Python 3.
| Python | mit | Lukasa/urllib3,haikuginger/urllib3,Disassem/urllib3,urllib3/urllib3,Disassem/urllib3,haikuginger/urllib3,urllib3/urllib3,sigmavirus24/urllib3,sigmavirus24/urllib3,Lukasa/urllib3 |
0388ab2bb8ad50aa40716a1c5f83f5e1f400bb32 | scripts/start_baxter.py | scripts/start_baxter.py | #!/usr/bin/python
from baxter_myo.arm_controller import ArmController
from baxter_myo.config_reader import ConfigReader
def main():
c = ConfigReader("demo_config")
c.parse_all()
s = ArmController('right', c.right_angles, c.push_thresh)
s.move_loop()
if __name__ == "__main__":
main()
| #!/usr/bin/python
import time
import rospy
from baxter_myo.arm_controller import ArmController
from baxter_myo.config_reader import ConfigReader
def main():
c = ConfigReader("demo_config")
c.parse_all()
s = ArmController('right', c.right_angles, c.push_thresh)
while not rospy.is_shutdown():
s... | Enable ctrl-c control with rospy | Enable ctrl-c control with rospy
| Python | mit | ipab-rad/baxter_myo,ipab-rad/myo_baxter_pc,ipab-rad/myo_baxter_pc,ipab-rad/baxter_myo |
f198941de6191ef9f729d1d8758c588654598f48 | runtests.py | runtests.py | #!/usr/bin/env python
from __future__ import unicode_literals
import os, sys
import six
try:
from django.conf import settings
except ImportError:
print("Django has not been installed.")
sys.exit(0)
if not settings.configured:
settings.configure(
INSTALLED_APPS=["jstemplate"],
DATABAS... | #!/usr/bin/env python
from __future__ import unicode_literals
import os, sys
try:
import six
from django.conf import settings
except ImportError:
print("Django has not been installed.")
sys.exit(0)
if not settings.configured:
settings.configure(
INSTALLED_APPS=["jstemplate"],
DAT... | Check whether six has been installed before running tests | Check whether six has been installed before running tests
| Python | bsd-3-clause | mjumbewu/django-jstemplate,mjumbewu/django-jstemplate,bopo/django-jstemplate,bopo/django-jstemplate,bopo/django-jstemplate,mjumbewu/django-jstemplate |
0b8e99a6c7ecf5b35c61ce4eed1b2eec3110d41d | runtests.py | runtests.py | import os
import sys
# Force this to happen before loading django
try:
os.environ["DJANGO_SETTINGS_MODULE"] = "testtinymce.settings"
test_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, test_dir)
except ImportError:
pass
else:
import django
from django.conf ... | import argparse
import os
import sys
# Force this to happen before loading django
try:
os.environ["DJANGO_SETTINGS_MODULE"] = "testtinymce.settings"
test_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, test_dir)
except ImportError:
pass
else:
import django
f... | Add ability to run tests with verbosity and failfast options | Add ability to run tests with verbosity and failfast options
| Python | mit | aljosa/django-tinymce,aljosa/django-tinymce,aljosa/django-tinymce,aljosa/django-tinymce |
50a88c05c605f5157eebadb26e30f418dc3251b6 | tests/teamscale_client_test.py | tests/teamscale_client_test.py | import requests
import responses
from teamscale_client.teamscale_client import TeamscaleClient
def get_client():
return TeamscaleClient("http://localhost:8080", "admin", "admin", "foo")
@responses.activate
def test_put():
responses.add(responses.PUT, 'http://localhost:8080',
body='succes... | import requests
import responses
import re
from teamscale_client.teamscale_client import TeamscaleClient
URL = "http://localhost:8080"
def get_client():
return TeamscaleClient(URL, "admin", "admin", "foo")
def get_project_service_mock(service_id):
return re.compile(r'%s/p/foo/%s/.*' % (URL, service_id))
def... | Add basic execution tests for upload methods | Add basic execution tests for upload methods
| Python | apache-2.0 | cqse/teamscale-client-python |
441eac1b7d9d3f2fb30fbd2faf1dbe8fe3908402 | 99_misc/control_flow.py | 99_misc/control_flow.py | #!/usr/bin/env python
# function
def sum(op1, op2):
return op1 + op2
my_sum = sum
print my_sum(1, 2)
print my_sum("I am ", "zzz");
# pass
print "press ctrl + c to continue"
while True:
pass
| #!/usr/bin/env python
# function
def sum(op1, op2):
return op1 + op2
my_sum = sum
print my_sum(1, 2)
print my_sum("I am ", "zzz");
# Default value in a fuction
init = 12
def accumulate(val = init):
val += val
return val
my_accu = accumulate
init = 11
print my_accu() # is 12 + 12 rather than 11 + 11
# pa... | Test default value of a function | Test default value of a function
| Python | bsd-2-clause | zzz0072/Python_Exercises,zzz0072/Python_Exercises |
c4cdb8429ab9eeeeb7182191589e0594c201d0d2 | glue/_mpl_backend.py | glue/_mpl_backend.py | class MatplotlibBackendSetter(object):
"""
Import hook to make sure the proper Qt backend is set when importing
Matplotlib.
"""
enabled = True
def find_module(self, mod_name, pth):
if self.enabled and 'matplotlib' in mod_name:
self.enabled = False
set_mpl_backen... | class MatplotlibBackendSetter(object):
"""
Import hook to make sure the proper Qt backend is set when importing
Matplotlib.
"""
enabled = True
def find_module(self, mod_name, pth):
if self.enabled and 'matplotlib' in mod_name:
self.enabled = False
set_mpl_backen... | Add missing find_spec for import hook, to avoid issues when trying to set colormap | Add missing find_spec for import hook, to avoid issues when trying to set colormap | Python | bsd-3-clause | stscieisenhamer/glue,saimn/glue,saimn/glue,stscieisenhamer/glue |
a65eb4af0c35c8e79d44efa6acb546e19008a8ee | elmo/moon_tracker/forms.py | elmo/moon_tracker/forms.py | from django import forms
import csv
from io import StringIO
class BatchMoonScanForm(forms.Form):
data = forms.CharField(
widget=forms.Textarea(attrs={'class':'form-control monospace'}),
)
def clean(self):
cleaned_data = super(BatchMoonScanForm, self).clean()
raw = StringIO(cleaned... | from django import forms
import csv
from io import StringIO
class BatchMoonScanForm(forms.Form):
data = forms.CharField(
widget=forms.Textarea(attrs={'class':'form-control monospace'}),
)
def clean(self):
cleaned_data = super(BatchMoonScanForm, self).clean()
raw = StringIO(cleaned... | Improve batch form return data structure. | Improve batch form return data structure.
| Python | mit | StephenSwat/eve_lunar_mining_organiser,StephenSwat/eve_lunar_mining_organiser |
2b4b4ac3ec238a039717feff727316217c13d294 | test/test_cronquot.py | test/test_cronquot.py | import unittest
from cronquot.cronquot import has_directory
class CronquotTest(unittest.TestCase):
def test_has_directory(self):
self.assertTrue(has_directory('/tmp'))
if __name__ == '__main__':
unittest.test()
| import unittest
import os
from cronquot.cronquot import has_directory
class CronquotTest(unittest.TestCase):
def test_has_directory(self):
sample_dir = os.path.join(
os.path.dirname(__file__), 'crontab')
self.assertTrue(has_directory(sample_dir))
if __name__ == '__main__':
un... | Fix to test crontab dir | Fix to test crontab dir
| Python | mit | pyohei/cronquot,pyohei/cronquot |
038e619e47a05aadf7e0641dd87b6dc573abe3e5 | massa/domain.py | massa/domain.py | # -*- coding: utf-8 -*-
from sqlalchemy import (
Column,
Date,
Integer,
MetaData,
Numeric,
String,
Table,
create_engine,
)
metadata = MetaData()
measurement = Table('measurement', metadata,
Column('id', Integer, primary_key=True),
Column('weight', Numeric(4, 1), nullable=Fals... | # -*- coding: utf-8 -*-
from sqlalchemy import (
Column,
Date,
Integer,
MetaData,
Numeric,
String,
Table,
create_engine,
)
metadata = MetaData()
measurement = Table('measurement', metadata,
Column('id', Integer, primary_key=True),
Column('weight', Numeric(4, 1), nullable=Fals... | Add a function to drop db tables. | Add a function to drop db tables. | Python | mit | jaapverloop/massa |
5425c2419b7365969ea8b211432858d599214201 | tests/test_archive.py | tests/test_archive.py | from json import load
from django_archive import __version__
from .base import BaseArchiveTestCase
from .sample.models import Sample
class ArchiveTestCase(BaseArchiveTestCase):
"""
Test that the archive command includes correct data in the archive
"""
def setUp(self):
Sample().save()
... | from json import load
from django.core.files.base import ContentFile
from django_archive import __version__
from .base import BaseArchiveTestCase
from .sample.models import Sample
class ArchiveTestCase(BaseArchiveTestCase):
"""
Test that the archive command includes correct data in the archive
"""
... | Update test to ensure attached files are present in archives. | Update test to ensure attached files are present in archives.
| Python | mit | nathan-osman/django-archive,nathan-osman/django-archive |
1b5fc874924958664797ba2f1e73835b4cbcef57 | mfr/__init__.py | mfr/__init__.py | """The mfr core module."""
# -*- coding: utf-8 -*-
import os
__version__ = '0.1.0-alpha'
__author__ = 'Center for Open Science'
from mfr.core import (render, detect, FileHandler, get_file_extension,
register_filehandler, export, get_file_exporters,
config, collect_static
)
from mfr._config import Config
P... | """The mfr core module."""
# -*- coding: utf-8 -*-
import os
__version__ = '0.1.0-alpha'
__author__ = 'Center for Open Science'
from mfr.core import (
render,
detect,
FileHandler,
get_file_extension,
register_filehandler,
export,
get_file_exporters,
config,
collect_static,
Ren... | Add RenderResult to mfr namespace | Add RenderResult to mfr namespace
| Python | apache-2.0 | TomBaxter/modular-file-renderer,chrisseto/modular-file-renderer,mfraezz/modular-file-renderer,haoyuchen1992/modular-file-renderer,haoyuchen1992/modular-file-renderer,erinspace/modular-file-renderer,rdhyee/modular-file-renderer,CenterForOpenScience/modular-file-renderer,icereval/modular-file-renderer,TomBaxter/modular-f... |
0a5331c36cb469b2af10d87ab375d9bd0c6c3fb8 | tests/test_lattice.py | tests/test_lattice.py | import rml.lattice
def test_create_lattice():
l = rml.lattice.Lattice()
assert(len(l)) == 0
| import rml.lattice
def test_create_lattice():
l = rml.lattice.Lattice()
assert(len(l)) == 0
def test_non_negative_lattice():
l = rml.lattice.Lattice()
assert(len(l)) >= 0
| Test lattince length for non-negative values | Test lattince length for non-negative values
| Python | apache-2.0 | willrogers/pml,razvanvasile/RML,willrogers/pml |
19dc8b7e1535c4cc431b765f95db117175fc7d24 | server/admin.py | server/admin.py | from django.contrib import admin
from server.models import *
class MachineGroupAdmin(admin.ModelAdmin):
readonly_fields = ('key',)
class MachineAdmin(admin.ModelAdmin):
list_display = ('hostname', 'serial')
admin.site.register(UserProfile)
admin.site.register(BusinessUnit)
admin.site.register(MachineGroup... | from django.contrib import admin
from server.models import *
class ApiKeyAdmin(admin.ModelAdmin):
list_display = ('name', 'public_key', 'private_key')
class MachineAdmin(admin.ModelAdmin):
list_display = ('hostname', 'serial')
class MachineGroupAdmin(admin.ModelAdmin):
readonly_fields = ('key',)
ad... | Sort registrations. Separate classes of imports. Add API key display. | Sort registrations. Separate classes of imports. Add API key display.
| Python | apache-2.0 | salopensource/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,sheagcraig/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal |
b5aacae66d4395a3c507c661144b21f9b2838a0f | utils/dakota_utils.py | utils/dakota_utils.py | #! /usr/bin/env python
#
# Dakota utility programs.
#
# Mark Piper (mark.piper@colorado.edu)
import numpy as np
def get_names(dat_file):
'''
Reads the header from Dakota tabular graphics file. Returns a list
of variable names.
'''
fp = open(dat_file, 'r')
return fp.readline().split()
def ge... | #! /usr/bin/env python
#
# Dakota utility programs.
#
# Mark Piper (mark.piper@colorado.edu)
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
def get_names(dat_file):
'''
Reads the header from Dakota tabular graphics file. Returns a list
of variable names.
''... | Add routine to make surface plot from Dakota output | Add routine to make surface plot from Dakota output
| Python | mit | mdpiper/dakota-experiments,mdpiper/dakota-experiments,mdpiper/dakota-experiments,mcflugen/dakota-experiments,mcflugen/dakota-experiments |
f5a3148ed638c65a3de3e1de0e5dece96f0c049b | placidity/plugin_loader.py | placidity/plugin_loader.py | class PluginLoader:
def load(self, directory):
ret = []
for plugin in directory.children:
plugin_file = plugin.find(name=plugin.name, type='py')
plugin_class = plugin_file.classes[plugin.name]
self._check_attributes(plugin_class)
plugin_instance = ... | class PluginLoader:
def load(self, directory):
ret = []
for plugin in directory.children:
plugin_file = plugin.find(name=plugin.name, type='py')
if not plugin_file:
continue
plugin_class = plugin_file.classes[plugin.name]
... | Make plugin loader more robust | Make plugin loader more robust
| Python | mit | bebraw/Placidity |
b1b8c9b4e392d4865756ece6528e6668e2bc8975 | wafw00f/plugins/expressionengine.py | wafw00f/plugins/expressionengine.py | #!/usr/bin/env python
NAME = 'Expression Engine (EllisLab)'
def is_waf(self):
for attack in self.attacks:
r = attack(self)
if r is None:
return
response, page = r
# There are traces found where cookie is returning values like:
# Set-Cookie: exp_last_query=834y... | #!/usr/bin/env python
NAME = 'Expression Engine (EllisLab)'
def is_waf(self):
for attack in self.attacks:
r = attack(self)
if r is None:
return
response, page = r
# There are traces found where cookie is returning values like:
# Set-Cookie: exp_last_query=834y... | Fix to avoid NoneType bugs | Fix to avoid NoneType bugs
| Python | bsd-3-clause | EnableSecurity/wafw00f |
bf241d6c7aa96c5fca834eb1063fc009a9320329 | portfolio/urls.py | portfolio/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^about/$', views.about, name='about'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^projects/$', views.projects, name='projects'),
url(r'^tribute/$', views.tribute, name='tri... | from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^about/$', views.about, name='about'),
url(r'^contact/$', TemplateView.as_view(template_name="contact.html"), name='contact'),
# url(r'^contact/$... | Change URL pattern for contacts | Change URL pattern for contacts
| Python | mit | bacarlino/portfolio,bacarlino/portfolio,bacarlino/portfolio |
6e433c59348ed4c47c040efb50c891c4759bcee4 | jedihttp/__main__.py | jedihttp/__main__.py | # Copyright 2015 Cedraro Andrea <a.cedraro@gmail.com>
# 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... | # Copyright 2015 Cedraro Andrea <a.cedraro@gmail.com>
# 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... | Add command-line argument for server host | Add command-line argument for server host
| Python | apache-2.0 | vheon/JediHTTP,micbou/JediHTTP,micbou/JediHTTP,vheon/JediHTTP |
bd4506dc95ee7a778a5b0f062d6d0423ade5890c | alerts/lib/alert_plugin_set.py | alerts/lib/alert_plugin_set.py | from mozdef_util.plugin_set import PluginSet
from mozdef_util.utilities.logger import logger
class AlertPluginSet(PluginSet):
def send_message_to_plugin(self, plugin_class, message, metadata=None):
if 'utctimestamp' in message and 'summary' in message:
message_log_str = '{0} received message:... | from mozdef_util.plugin_set import PluginSet
class AlertPluginSet(PluginSet):
def send_message_to_plugin(self, plugin_class, message, metadata=None):
return plugin_class.onMessage(message), metadata
| Remove logger entry for alert plugins receiving alerts | Remove logger entry for alert plugins receiving alerts
| Python | mpl-2.0 | mozilla/MozDef,jeffbryner/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,mpurzynski/MozDef,mozilla/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,mozilla/MozDef,mozilla/MozDef |
1a4d2ea23ad37b63bab1751b7f3b7572f6804f14 | api/base/exceptions.py | api/base/exceptions.py |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.view... |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.view... | Use if response since 'is not None' is unnecessary. | Use if response since 'is not None' is unnecessary.
| Python | apache-2.0 | Johnetordoff/osf.io,njantrania/osf.io,pattisdr/osf.io,baylee-d/osf.io,GageGaskins/osf.io,brandonPurvis/osf.io,mfraezz/osf.io,TomHeatwole/osf.io,cosenal/osf.io,erinspace/osf.io,caneruguz/osf.io,crcresearch/osf.io,binoculars/osf.io,RomanZWang/osf.io,samanehsan/osf.io,doublebits/osf.io,caseyrygt/osf.io,TomHeatwole/osf.io,... |
d87cb6b401e38a06c5d594e40ad813a9db0738e6 | taca/analysis/cli.py | taca/analysis/cli.py | """ CLI for the analysis subcommand
"""
import click
from taca.analysis import analysis as an
@click.group()
def analysis():
""" Analysis methods entry point """
pass
# analysis subcommands
@analysis.command()
@click.option('-r', '--run', type=click.Path(exists=True), default=None,
help='Demultiplex only a pa... | """ CLI for the analysis subcommand
"""
import click
from taca.analysis import analysis as an
@click.group()
def analysis():
""" Analysis methods entry point """
pass
# analysis subcommands
@analysis.command()
@click.option('-r', '--run', type=click.Path(exists=True), default=None,
help='Demultiplex only a pa... | Add option for triggering or not the analysis | Add option for triggering or not the analysis
| Python | mit | senthil10/TACA,kate-v-stepanova/TACA,SciLifeLab/TACA,SciLifeLab/TACA,vezzi/TACA,guillermo-carrasco/TACA,senthil10/TACA,b97pla/TACA,kate-v-stepanova/TACA,SciLifeLab/TACA,b97pla/TACA,guillermo-carrasco/TACA,vezzi/TACA |
74a76dd7e21c4248d6a19e55fde69b92169d4008 | osmfilter/parsing.py | osmfilter/parsing.py | from .compat import etree
from .entities import Node, Way, Relation
def parse(fp):
context = etree.iterparse(fp, events=('end',))
for action, elem in context:
# Act only on node, ways and relations
if elem.tag not in ('node', 'way', 'relation'):
continue
tags = {t.get('k'... | from threading import Thread
from .compat import etree
from .entities import Node, Way, Relation
def xml_node_cleanup(elem):
elem.clear()
while elem.getprevious() is not None:
del elem.getparent()[0]
def parse(fp):
context = etree.iterparse(fp, events=('end',))
for action, elem in context:... | Make Reader subclass of Thread | Make Reader subclass of Thread
| Python | mit | gileri/osmfiltering |
675c6d78738a56cc556984553216ce92cf0ecd94 | test/parseResults.py | test/parseResults.py | #!/usr/bin/env python3
import json
import sys
PREFIXES = [
["FAIL", "PASS"],
["EXPECTED FAIL", "UNEXPECTED PASS"],
]
def parse_expected_failures():
expected_failures = set()
with open("expected-failures.txt", "r") as fp:
for line in fp:
line = line.strip()
if not line... | #!/usr/bin/env python3
import json
import sys
PREFIXES = [
["FAIL", "PASS"],
["EXPECTED FAIL", "UNEXPECTED PASS"],
]
def parse_expected_failures():
expected_failures = set()
with open("expected-failures.txt", "r") as fp:
for line in fp:
line = line.strip()
if not line... | Print the scenario when running 262-style tests. | Print the scenario when running 262-style tests.
| Python | isc | js-temporal/temporal-polyfill,js-temporal/temporal-polyfill,js-temporal/temporal-polyfill |
da516d06ab294dc2dde4bb671ab16653b1421314 | tests/performance.py | tests/performance.py | """Script to run performance check."""
import time
from examples.game_of_life import GameOfLife, GOLExperiment
from xentica.utils.formatters import sizeof_fmt
MODELS = [
("Conway's Life", GameOfLife, GOLExperiment),
]
NUM_STEPS = 10000
if __name__ == "__main__":
for name, model, experiment in MODELS:
... | """Script to run performance check."""
import time
from examples.game_of_life import (
GameOfLife, GOLExperiment
)
from examples.shifting_sands import (
ShiftingSands, ShiftingSandsExperiment
)
from xentica.utils.formatters import sizeof_fmt
MODELS = [
("Conway's Life", GameOfLife, GOLExperiment),
("... | Add Shifting Sands to benchmark tests | Add Shifting Sands to benchmark tests
| Python | mit | a5kin/hecate,a5kin/hecate |
d2130b64c63bdcfdea854db39fb21c7efe0b24e1 | tests/test_httpheader.py | tests/test_httpheader.py | # MIT licensed
# Copyright (c) 2021 lilydjwg <lilydjwg@gmail.com>, et al.
import pytest
pytestmark = pytest.mark.asyncio
async def test_redirection(get_version):
assert await get_version("jmeter-plugins-manager", {
"source": "httpheader",
"url": "https://www.unifiedremote.com/download/linux-x64-d... | # MIT licensed
# Copyright (c) 2021 lilydjwg <lilydjwg@gmail.com>, et al.
import pytest
pytestmark = pytest.mark.asyncio
async def test_redirection(get_version):
assert await get_version("unifiedremote", {
"source": "httpheader",
"url": "https://www.unifiedremote.com/download/linux-x64-deb",
... | Correct package name in httpheader test | Correct package name in httpheader test
| Python | mit | lilydjwg/nvchecker |
361a1a1ca88630981bb83a85648714c5bc4c5a89 | thinc/neural/_classes/feed_forward.py | thinc/neural/_classes/feed_forward.py | from .model import Model
from ... import describe
def _run_child_hooks(model, X, y):
for layer in model._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
X = layer(X)
@describe.on_data(_run_child_hooks)
class FeedForward(Model):
'''A feed-forward network, that chains mu... | from .model import Model
from ... import describe
def _run_child_hooks(model, X, y):
for layer in model._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
X = layer(X)
@describe.on_data(_run_child_hooks)
class FeedForward(Model):
'''A feed-forward network, that chains mu... | Add predict() path to feed-forward | Add predict() path to feed-forward
| Python | mit | explosion/thinc,explosion/thinc,spacy-io/thinc,spacy-io/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc |
76d9d1beaebf5b7d8e2ef051c8b8926724542387 | regenesis/storage.py | regenesis/storage.py | import os
import json
from regenesis.core import app
def cube_path(cube_name, ext):
return os.path.join(
app.config.get('DATA_DIRECTORY'),
cube_name + '.' + ext
)
def store_cube_raw(cube_name, cube_data):
fh = open(cube_path(cube_name, 'raw'), 'wb')
fh.write(cube_data.e... | import os
import json
from regenesis.core import app
def cube_path(cube_name, ext):
return os.path.join(
app.config.get('DATA_DIRECTORY'),
cube_name + '.' + ext
)
def exists_raw(cube_name):
return os.path.isfile(cube_path(cube_name, 'raw'))
def store_cube_raw(cube_name, cu... | Check if a cube exists on disk. | Check if a cube exists on disk. | Python | mit | pudo/regenesis,pudo/regenesis |
593c2ec0d62049cee9bedc282903491b670d811f | ci/set_secrets_file.py | ci/set_secrets_file.py | """
Move the right secrets file into place for Travis CI.
"""
| """
Move the right secrets file into place for Travis CI.
"""
import os
import shutil
from pathlib import Path
def move_secrets_file() -> None:
"""
Move the right secrets file to the current directory.
"""
branch = os.environ['TRAVIS_BRANCH']
is_pr = os.environ['TRAVIS_PULL_REQUEST'] != 'false'
... | Add script to move secrets file | Add script to move secrets file
| Python | mit | adamtheturtle/vws-python,adamtheturtle/vws-python |
255a93e2e075a8db914e4736cb79fbdb58b41a24 | file_transfer/baltrad_to_s3.py | file_transfer/baltrad_to_s3.py | """
Baltrad to S3 porting
"""
import sys
from creds import URL, LOGIN, PASSWORD
import datamover as dm
def main():
"""Run data transfer from Baltrad to S3"""
# ------------------
# DATA TRANSFER
# ------------------
# Setup the connection of the Baltrad and S3
btos = dm.BaltradToS3(URL, L... | """
Baltrad to S3 porting
"""
import sys
from creds import URL, LOGIN, PASSWORD
import datamover as dm
def main():
"""Run data transfer from Baltrad to S3"""
# ------------------
# DATA TRANSFER
# ------------------
# Setup the connection of the Baltrad and S3
btos = dm.BaltradToS3(URL, L... | Extend data pipeline from baltrad | Extend data pipeline from baltrad
| Python | mit | enram/data-repository,enram/data-repository,enram/data-repository,enram/data-repository,enram/infrastructure,enram/infrastructure |
fd721c76e30f776b04c7691ce536525561dd2cfa | sympy/matrices/expressions/transpose.py | sympy/matrices/expressions/transpose.py | from matexpr import MatrixExpr
from sympy import Basic
class Transpose(MatrixExpr):
"""Matrix Transpose
Represents the transpose of a matrix expression.
Use .T as shorthand
>>> from sympy import MatrixSymbol, Transpose
>>> A = MatrixSymbol('A', 3, 5)
>>> B = MatrixSymbol('B', 5, 3)
>>> T... | from matexpr import MatrixExpr
from sympy import Basic
class Transpose(MatrixExpr):
"""Matrix Transpose
Represents the transpose of a matrix expression.
Use .T as shorthand
>>> from sympy import MatrixSymbol, Transpose
>>> A = MatrixSymbol('A', 3, 5)
>>> B = MatrixSymbol('B', 5, 3)
>>> T... | Remove unnecessary MatAdd and MatMul imports | Remove unnecessary MatAdd and MatMul imports
| Python | bsd-3-clause | drufat/sympy,hrashk/sympy,toolforger/sympy,yashsharan/sympy,AunShiLord/sympy,oliverlee/sympy,MridulS/sympy,Arafatk/sympy,shikil/sympy,MechCoder/sympy,lindsayad/sympy,kevalds51/sympy,iamutkarshtiwari/sympy,cswiercz/sympy,mafiya69/sympy,AkademieOlympia/sympy,Designist/sympy,garvitr/sympy,sahmed95/sympy,pandeyadarsh/sympy... |
ed40088b5e913e70c161e8148ab76fdc0b6c5c46 | clt_utils/argparse.py | clt_utils/argparse.py | from datetime import datetime
import argparse
import os
def is_dir(string):
"""
Type check for a valid directory for ArgumentParser.
"""
if not os.path.isdir(string):
msg = '{0} is not a directory'.format(string)
raise argparse.ArgumentTypeError(msg)
return string
def is_file(str... | from __future__ import absolute_import
from datetime import datetime
import argparse as _argparse
import os
def is_dir(string):
"""
Type check for a valid directory for ArgumentParser.
"""
if not os.path.isdir(string):
msg = '{0} is not a directory'.format(string)
raise _argparse.Argu... | Fix bug with self reference | Fix bug with self reference
| Python | apache-2.0 | 55minutes/clt-utils |
29f91d362689a53e04557588e47f1ac3e8d0fadc | server/lib/pricing.py | server/lib/pricing.py | def price(printTime, filamentUsed, filament=None):
return round((printTime/60/60)*filament['price'])
| def price(printTime, filamentUsed, filament=None):
return round((printTime/60/60)*200)
| Set constant price for all filaments | Set constant price for all filaments
| Python | agpl-3.0 | MakersLab/custom-print |
edd2cc66fff3159699c28c8f86c52e6524ce9d86 | social_auth/fields.py | social_auth/fields.py | from django.core.exceptions import ValidationError
from django.db import models
from django.utils import simplejson
class JSONField(models.TextField):
"""Simple JSON field that stores python structures as JSON strings
on database.
"""
__metaclass__ = models.SubfieldBase
def to_python(self, value... | from django.core.exceptions import ValidationError
from django.db import models
from django.utils import simplejson
class JSONField(models.TextField):
"""Simple JSON field that stores python structures as JSON strings
on database.
"""
__metaclass__ = models.SubfieldBase
def to_python(self, value... | Use get_prep_value instead of the database related one. Closes gh-42 | Use get_prep_value instead of the database related one. Closes gh-42
| Python | bsd-3-clause | vuchau/django-social-auth,getsentry/django-social-auth,1st/django-social-auth,michael-borisov/django-social-auth,michael-borisov/django-social-auth,beswarm/django-social-auth,lovehhf/django-social-auth,omab/django-social-auth,adw0rd/django-social-auth,mayankcu/Django-social,caktus/django-social-auth,antoviaque/django-s... |
111682e3c19784aa87d5f3d4b56149226e6f9d3b | app/tests/archives_tests/test_models.py | app/tests/archives_tests/test_models.py | import pytest
from tests.archives_tests.factories import ArchiveFactory
from tests.model_helpers import do_test_factory
@pytest.mark.django_db
class TestArchivesModels:
# test functions are added dynamically to this class
def test_study_str(self):
model = ArchiveFactory()
assert str(model) == ... | import pytest
from django.core.exceptions import ObjectDoesNotExist
from tests.archives_tests.factories import ArchiveFactory
from tests.cases_tests.factories import ImageFactoryWithImageFile
from tests.model_helpers import do_test_factory
@pytest.mark.django_db
class TestArchivesModels:
# test functions are add... | Add test for cascading deletion of archive | Add test for cascading deletion of archive
| Python | apache-2.0 | comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django |
0acbe43b91fab6a01b5a773c4ac494d01138f216 | engines/mako_engine.py | engines/mako_engine.py | #!/usr/bin/env python3
"""Provide the mako templating engine."""
from __future__ import print_function
from mako.template import Template
from mako.lookup import TemplateLookup
from . import Engine
class MakoEngine(Engine):
"""Mako templating engine."""
handle = 'mako'
def __init__(self, template, ... | #!/usr/bin/env python3
"""Provide the mako templating engine."""
from __future__ import print_function
from mako.template import Template
from mako.lookup import TemplateLookup
from . import Engine
class MakoEngine(Engine):
"""Mako templating engine."""
handle = 'mako'
def __init__(self, template, ... | Handle undefined names in tolerant mode in the mako engine. | Handle undefined names in tolerant mode in the mako engine.
| Python | mit | blubberdiblub/eztemplate |
c2364bfe321bc19ab2d648fc77c8111522654237 | adhocracy/migration/versions/032_remove_comment_title.py | adhocracy/migration/versions/032_remove_comment_title.py | from datetime import datetime
from sqlalchemy import MetaData, Column, ForeignKey, Table
from sqlalchemy import DateTime, Integer, Unicode, UnicodeText
metadata = MetaData()
old_revision_table = Table('revision', metadata,
Column('id', Integer, primary_key=True),
Column('create_time', DateTime, default=datet... | from datetime import datetime
from sqlalchemy import MetaData, Column, ForeignKey, Table
from sqlalchemy import DateTime, Integer, Unicode, UnicodeText
metadata = MetaData()
old_revision_table = Table('revision', metadata,
Column('id', Integer, primary_key=True),
Column('create_time', DateTime, default=datet... | Remove silly exception inserted for testing | Remove silly exception inserted for testing
| Python | agpl-3.0 | SysTheron/adhocracy,DanielNeugebauer/adhocracy,SysTheron/adhocracy,DanielNeugebauer/adhocracy,DanielNeugebauer/adhocracy,SysTheron/adhocracy,alkadis/vcv,liqd/adhocracy,alkadis/vcv,phihag/adhocracy,liqd/adhocracy,alkadis/vcv,liqd/adhocracy,phihag/adhocracy,liqd/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,phiha... |
08ce22e8c467f7fb7da056e098ac88b64c3096dc | step_stool/content.py | step_stool/content.py | __author__ = 'Chris Krycho'
__copyright__ = '2013 Chris Krycho'
from logging import error
from os import path, walk
from sys import exit
try:
from markdown import Markdown
from mixins import DictAsMember
except ImportError as import_error:
error(import_error)
exit()
def convert_source(config):
... | __author__ = 'Chris Krycho'
__copyright__ = '2013 Chris Krycho'
from logging import error
from os import path, walk
from sys import exit
try:
from markdown import Markdown
from mixins import DictAsMember
except ImportError as import_error:
error(import_error)
exit()
def convert_source(config):
... | Fix file open/read/close - there was no close() call in previous version! Use context handler instead. | Fix file open/read/close - there was no close() call in previous version! Use context handler instead.
| Python | mit | chriskrycho/step-stool,chriskrycho/step-stool |
6930782947f604630142b106cb079e627fcff499 | readthedocs/v3/views.py | readthedocs/v3/views.py | import django_filters.rest_framework
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.renderers import JSONRenderer
from rest_framework.throttling import UserRateThrottle, AnonRateThrottle
from rest_flex_field... | import django_filters.rest_framework as filters
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.renderers import JSONRenderer
from rest_framework.throttling import UserRateThrottle, AnonRateThrottle
from rest... | Use a class filter to allow expansion | Use a class filter to allow expansion
| Python | mit | rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org |
a494260a8f9cf0e3ecf0c428bb70d4066623f1dd | wqflask/utility/elasticsearch_tools.py | wqflask/utility/elasticsearch_tools.py | es = None
try:
from elasticsearch import Elasticsearch, TransportError
from utility.tools import ELASTICSEARCH_HOST, ELASTICSEARCH_PORT
es = Elasticsearch([{
"host": ELASTICSEARCH_HOST
, "port": ELASTICSEARCH_PORT
}]) if (ELASTICSEARCH_HOST and ELASTICSEARCH_PORT) else None
except:
... | es = None
try:
from elasticsearch import Elasticsearch, TransportError
from utility.tools import ELASTICSEARCH_HOST, ELASTICSEARCH_PORT
es = Elasticsearch([{
"host": ELASTICSEARCH_HOST
, "port": ELASTICSEARCH_PORT
}]) if (ELASTICSEARCH_HOST and ELASTICSEARCH_PORT) else None
except:
... | Refactor common items to more generic methods. | Refactor common items to more generic methods.
* Refactor code that can be used in more than one place to a more
generic method/function that's called by other methods
| Python | agpl-3.0 | pjotrp/genenetwork2,DannyArends/genenetwork2,zsloan/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,DannyArends/genenetwork2,zsloan/genenetwork2,pjotrp/genenetwork2,DannyArends/genenetwork2,DannyArends/genenetwork2,DannyArends/genenetwork2,genenetwork/genenetwork2,genenetwork/genenetwork2,... |
c5b8ea3c7f3bf111e36515f92ab3aeb70026771e | openstack-dashboard/dashboard/tests.py | openstack-dashboard/dashboard/tests.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
from django import test
from django.core import mail
from mailer import engine
from mailer import send_mail
class DjangoMailerPresenceTest(test.TestCase):
def test_mailsent(self):
send_mail('subject', 'message_body', 'from@test.com', ['to@test.com'])
en... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
''' Test for django mailer.
This test is pretty much worthless, and should be removed once real testing of
views that send emails is implemented
'''
from django import test
from django.core import mail
from mailer import engine
from mailer import send_mail
class DjangoMa... | Add comment ot openstack test | Add comment ot openstack test
| Python | apache-2.0 | usc-isi/horizon-old,coreycb/horizon,Daniex/horizon,gochist/horizon,saydulk/horizon,CiscoSystems/avos,NCI-Cloud/horizon,pnavarro/openstack-dashboard,Solinea/horizon,promptworks/horizon,Mirantis/mos-horizon,tuskar/tuskar-ui,yjxtogo/horizon,mandeepdhami/horizon,cloud-smokers/openstack-dashboard,Metaswitch/horizon,asomya/t... |
f5cab8249d5e162285e5fc94ded8bf7ced292986 | test/test_ev3_key.py | test/test_ev3_key.py | from ev3.ev3dev import Key
import unittest
from util import get_input
import time
class TestTone(unittest.TestCase):
def test_tone(self):
d = Key()
get_input('Test keyboard. Hold Up key')
print(d.up)
get_input('Test keyboard. Release Up key')
print(d.up)
get_input(... | from ev3.ev3dev import Key
import unittest
from util import get_input
class TestKey(unittest.TestCase):
def test_key(self):
d = Key()
get_input('Test keyboard. Hold Up key')
print(d.up)
get_input('Test keyboard. Release Up key')
print(d.up)
get_input('Test keyboard... | Change dname of key test | Change dname of key test
| Python | apache-2.0 | topikachu/python-ev3,MaxNoe/python-ev3,evz/python-ev3,topikachu/python-ev3,MaxNoe/python-ev3,evz/python-ev3 |
517a76bc9aec3dbe8c21c96be424da838b5fcc02 | apistar/wsgi.py | apistar/wsgi.py | from typing import Iterable, List, Tuple
from werkzeug.http import HTTP_STATUS_CODES
from apistar import http
__all__ = ['WSGIEnviron', 'WSGIResponse']
STATUS_CODES = {
code: "%d %s" % (code, msg)
for code, msg in HTTP_STATUS_CODES.items()
}
WSGIEnviron = http.WSGIEnviron
class WSGIResponse(object):
... | from typing import Iterable, List, Tuple
from werkzeug.http import HTTP_STATUS_CODES
from apistar import http
__all__ = ['WSGIEnviron', 'WSGIResponse']
STATUS_CODES = {
code: "%d %s" % (code, msg)
for code, msg in HTTP_STATUS_CODES.items()
}
ACCESS_CONTROL_ALLOW_ORIGIN = 'Access-Control-Allow-Origin'
WSG... | Set "Access-Control-Allow-Origin: *" by default | Set "Access-Control-Allow-Origin: *" by default
| Python | bsd-3-clause | encode/apistar,rsalmaso/apistar,encode/apistar,tomchristie/apistar,tomchristie/apistar,tomchristie/apistar,encode/apistar,rsalmaso/apistar,tomchristie/apistar,encode/apistar,rsalmaso/apistar,rsalmaso/apistar |
c0ab344235fdd7df8e32c499124596d20f9d9e52 | src/tempel/forms.py | src/tempel/forms.py | from django import forms
from tempel import utils
class EntryForm(forms.Form):
language = forms.ChoiceField(choices=utils.get_languages(),
initial="python")
content = forms.CharField(widget=forms.Textarea)
private = forms.BooleanField(required=False)
| from django import forms
from tempel import utils
class EntryForm(forms.Form):
language = forms.ChoiceField(choices=utils.get_languages(),
initial="python")
content = forms.CharField(widget=forms.Textarea)
private = forms.BooleanField(required=False)
class EditForm(forms.... | Add EditForm that does not have 'private' field. | Add EditForm that does not have 'private' field.
| Python | agpl-3.0 | fajran/tempel |
c96da14b7bc05d6de7f1ddb9b634ef04ae2e2213 | tests/test_trivia.py | tests/test_trivia.py |
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
if __name__ == "__mai... |
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
def test_parenthes... | Test trivia answers in parentheses with article prefixes | [Tests] Test trivia answers in parentheses with article prefixes
| Python | mit | Harmon758/Harmonbot,Harmon758/Harmonbot |
ebb3b727b8d7592b7e9755b3f7665314e668a19d | node/string_literal.py | node/string_literal.py | #!/usr/bin/env python
from nodes import Node
class StringLiteral(Node):
args = 0
results = 1
char = '"'
def __init__(self, string):
self.string = string
@Node.test_func([], [""], "")
@Node.test_func([], ["World"], "World\"")
@Node.test_func([], ["Hello"], "Hello")
def func(se... | #!/usr/bin/env python
from nodes import Node
class StringLiteral(Node):
args = 0
results = 1
char = '"'
def __init__(self, string):
self.string = string
@Node.test_func([], [""], "")
@Node.test_func([], ["World"], "World\"")
@Node.test_func([], ["Hello"], "Hello")
def func(se... | Allow `"` to appear in string literals | Allow `"` to appear in string literals
| Python | mit | muddyfish/PYKE,muddyfish/PYKE |
5c2a691ff928c336c35a6ddef38c222b4bb3d2a4 | testproject/manage.py | testproject/manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| #!/usr/bin/env python
import os
import sys
try:
import pymysql
pymysql.install_as_MySQLdb()
except ImportError:
pass
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.settings")
from django.core.management import execute_from_command_line
execute_from_co... | Add support for testing with pymysql | Add support for testing with pymysql
| Python | bsd-3-clause | uranusjr/django-mosql |
1271f3b978d2ab46824ca7b33472bba5b725f9ac | tests/test_profile.py | tests/test_profile.py | import fiona
def test_profile():
with fiona.open('tests/data/coutwildrnp.shp') as src:
assert src.meta['crs_wkt'] == 'GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295],AUTHORITY["EPSG","4326"]]'
def test_profile_cre... | import os
import tempfile
import fiona
def test_profile():
with fiona.open('tests/data/coutwildrnp.shp') as src:
assert src.meta['crs_wkt'] == 'GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295],AUTHORITY["EPSG","4326... | Rework tmpdir for nose (no pytest) | Rework tmpdir for nose (no pytest)
| Python | bsd-3-clause | perrygeo/Fiona,perrygeo/Fiona,Toblerity/Fiona,rbuffat/Fiona,Toblerity/Fiona,rbuffat/Fiona |
f0e67ca657915e77b1f28bab9fa29f84bfbb8f06 | tests/unit/test_DB.py | tests/unit/test_DB.py | # standard modules
import StringIO
from unittest import TestCase
# custom modules
from iago.DatabaseProvider import DB
class TestDB(TestCase):
def test_read_empty(self):
s = StringIO.StringIO('{}')
d = DB()
try:
d.read(s)
except KeyError:
self.fail('DB cannot handle empty JSON files.')
| # standard modules
import StringIO
from unittest import TestCase
# custom modules
from iago.DatabaseProvider import DB
class TestDB(TestCase):
def test_read_empty(self):
s = StringIO.StringIO('{}')
d = DB()
try:
d.read(s, format='json')
except KeyError:
self.fail('DB cannot handle empty JSON files.')
| Fix test to specify file format | Fix test to specify file format
| Python | mit | ferchault/iago |
0e195e93e0a2f80bc85f8425254e8a1d3c324654 | bockus/books/search_indexes.py | bockus/books/search_indexes.py | from haystack import indexes
from books.models import Book, Series
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Book
def index_queryset(... | from haystack import indexes
from books.models import Book, Series
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Book
def index_queryset(... | Add library property to series search index | Add library property to series search index
| Python | mit | phildini/bockus,phildini/bockus,phildini/bockus |
2094f2ef5a47703a881643b8ca25a632fe54e892 | under_overfitting.py | under_overfitting.py | import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.cross_validation import cross_val_score
def main():
np.random.seed(0)
n_samples = 30
degrees = range(1, 16)
true_fn = lambd... | import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.cross_validation import cross_val_score
def main():
np.random.seed(0)
n_samples = 30
degrees = range(1, 16)
true_fn = lambd... | Complete walk of polynomial degrees to find most balance between under and overfitting | Complete walk of polynomial degrees to find most balance between under and overfitting
| Python | mit | noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit |
f915b101b635e644eb9018a8abb9e9c86e6c2a73 | test/test_config.py | test/test_config.py | import os
import stat
from nose.tools import *
from lctools import config
class TestConfig(object):
test_filename = "bebebe"
def setup(self):
fd = open(self.test_filename, 'w')
fd.write("[default]\n")
fd.write("foo = bar\n")
fd.close()
os.chmod(self.test_filename, sta... | import os
import stat
from nose.tools import *
from lctools import config
class TestConfig(object):
test_filename = "bebebe"
def setup(self):
fd = open(self.test_filename, 'w')
fd.write("[default]\n")
fd.write("foo = bar\n")
fd.close()
os.chmod(self.test_filename, sta... | Add a test for default config settings. | Add a test for default config settings.
| Python | apache-2.0 | novel/lc-tools,novel/lc-tools |
f6b4b16c26ee97d48ba524027a96d17fba63dc80 | project/models.py | project/models.py | import datetime
from project import db, bcrypt
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String, unique=True, nullable=False)
password = db.Column(db.String, nullable=False)
registered_on = db.Column(db.DateTime, nullable=Fal... | import datetime
from project import db, bcrypt
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String, unique=True, nullable=False)
password = db.Column(db.String, nullable=False)
registered_on = db.Column(db.DateTime, nullable=Fal... | Update user model with confirmed and confirmed_at | Update user model with confirmed and confirmed_at
| Python | mit | dylanshine/streamschool,dylanshine/streamschool |
09333f89a7ce9dfda59401bc59d92a3def9ca80c | mycroft/formatters/formatter_plugin.py | mycroft/formatters/formatter_plugin.py | from enum import Enum, unique
from inspect import signature, isclass
from mycroft.plugin.base_plugin import BasePlugin
from mycroft.util import log
@unique
class Format(Enum):
speech = 1
text = 2
class FormatterPlugin(BasePlugin):
and_ = 'and'
def __init__(self, rt):
super().__init__(rt)
... | from enum import Enum, unique
from inspect import signature, isclass
from mycroft.plugin.base_plugin import BasePlugin
from mycroft.util import log
@unique
class Format(Enum):
speech = 1
text = 2
class FormatterPlugin(BasePlugin):
and_ = 'and'
def __init__(self, rt):
super().__init__(rt)
... | Fix bug with list formatting | Fix bug with list formatting
Before it would completely fail to format any list of strings
| Python | apache-2.0 | MatthewScholefield/mycroft-simple,MatthewScholefield/mycroft-simple |
3ea7a61be81c0f2094d8b3b0d3a81dec267ac663 | GitSvnServer/client.py | GitSvnServer/client.py |
import parse
import generate as gen
from repos import find_repos
from errors import *
def parse_client_greeting(msg_str):
msg = parse.msg(msg_str)
proto_ver = int(msg[0])
client_caps = msg[1]
url = parse.string(msg[2])
print "ver: %d" % proto_ver
print "caps: %s" % client_caps
print "url... |
import parse
import generate as gen
from repos import find_repos
from errors import *
server_capabilities = [
'edit-pipeline', # This is required.
'svndiff1', # We support svndiff1
'absent-entries', # We support absent-dir and absent-dir editor commands
#'commit-revprops', # We don't curr... | Sort out the server announce message | Sort out the server announce message
Tidy up the server announce message a bit. In particular, we might as
well announce the absent-entries capability - we support the commands
even if they currently aren't implemented.
| Python | bsd-3-clause | slonopotamus/git_svn_server |
cbae1dafb07fda5afcd0f2573c81b6eeb08e6e20 | dependencies.py | dependencies.py | import os, pkgutil, site
if pkgutil.find_loader("gi"):
try:
import gi
print('Found gi:', os.path.abspath(gi.__file__))
gi.require_version('Gst', '1.0')
# from gi.repository import GLib, Gst
except ValueError:
print('Couldn\'t find Gst')
print('Please run \'sudo a... | import os
import pkgutil
import site
if pkgutil.find_loader("gi"):
try:
import gi
print('Found gi:', os.path.abspath(gi.__file__))
gi.require_version('Gst', '1.0')
# from gi.repository import GLib, Gst
except ValueError:
print('Couldn\'t find Gst')
print('Please ... | Exit program if exception is raised | Exit program if exception is raised
| Python | mit | Kane610/axis |
428c62ed4b10ba5714e2a0b718cd3f52e0376bc1 | feedhq/feeds/tasks.py | feedhq/feeds/tasks.py | from django.conf import settings
from django.db import connection
from ..tasks import raven
@raven
def update_feed(feed_url, use_etags=True):
from .models import UniqueFeed
UniqueFeed.objects.update_feed(feed_url, use_etags)
close_connection()
@raven
def read_later(entry_pk):
from .models import En... | from django.conf import settings
from django.db import connection
from ..tasks import raven
@raven
def update_feed(feed_url, use_etags=True):
from .models import UniqueFeed
UniqueFeed.objects.update_feed(feed_url, use_etags)
close_connection()
@raven
def read_later(entry_pk):
from .models import En... | Update favicon on UniqueFeed update | Update favicon on UniqueFeed update
| Python | bsd-3-clause | rmoorman/feedhq,feedhq/feedhq,vincentbernat/feedhq,rmoorman/feedhq,rmoorman/feedhq,vincentbernat/feedhq,feedhq/feedhq,feedhq/feedhq,rmoorman/feedhq,feedhq/feedhq,feedhq/feedhq,vincentbernat/feedhq,vincentbernat/feedhq,rmoorman/feedhq,vincentbernat/feedhq |
9dc90727df23e655e5c921ca84cb98b7d5ae5eb2 | example_game.py | example_game.py | from pygametemplate import Game
class ExampleGame(Game):
def logic(self):
pass
def draw(self):
pass
def quit(self):
pass
| from pygametemplate import Game
class ExampleGame(Game):
def logic(self):
pass
def draw(self):
pass
| Remove now unnecessary quit() method from ExampleGame | Remove now unnecessary quit() method from ExampleGame
| Python | mit | AndyDeany/pygame-template |
ee884a9cbaaaf7693e8d980d26cca480b9d1291e | app/models/__init__.py | app/models/__init__.py | """
Initialisation file for models directory.
The application SQLite database model is setup in SQLObject.
The db model structure is:
* Place
- contains records of all Places
* Supername -> Continent -> Country -> Town
- These tables are linked to each other in a hiearchy such that a
Supername has... | """
Initialisation file for models directory.
"""
# Create an _`_all__` list here, using values set in other application files.
from .places import __all__ as placesModel
from .trends import __all__ as trendsModel
from .tweets import __all__ as tweetsModel
from .cronJobs import __all__ as cronJobsModel
__all__ = places... | Add tweets model to models init file, for db setup to see it. | Add tweets model to models init file, for db setup to see it.
| Python | mit | MichaelCurrin/twitterverse,MichaelCurrin/twitterverse |
2352f18400d5b4b36052e04804bd04e32b000cc4 | streak-podium/render.py | streak-podium/render.py | import pygal
def horizontal_bar(sorted_streaks, sort_attrib):
"""
Render a horizontal bar chart of streaks.
Values have already been sorted by sort_attrib.
"""
users = [user for user, _ in sorted_streaks][::-1]
streaks = [getattr(streak, sort_attrib) for _, streak in sorted_streaks][::-1]
... | import pygal
def horizontal_bar(sorted_streaks, sort_attrib):
"""
Render a horizontal bar chart of streaks.
Values have already been sorted by sort_attrib.
"""
users = [user for user, _ in sorted_streaks][::-1]
streaks = [getattr(streak, sort_attrib) for _, streak in sorted_streaks][::-1]
... | Add links to profiles and clean up chart options | Add links to profiles and clean up chart options
| Python | mit | jollyra/hubot-commit-streak,supermitch/streak-podium,supermitch/streak-podium,jollyra/hubot-commit-streak,jollyra/hubot-streak-podium,jollyra/hubot-streak-podium |
08331a081713f880d5eca4fb7b18f4c61e360132 | tests/skipif_markers.py | tests/skipif_markers.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
skipif_markers
--------------
Contains pytest skipif markers to be used in the suite.
"""
import pytest
import os
try:
os.environ[u'TRAVIS']
except KeyError:
travis = False
else:
travis = True
try:
os.environ[u'DISABLE_NETWORK_TESTS']
except KeyErr... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
skipif_markers
--------------
Contains pytest skipif markers to be used in the suite.
"""
import pytest
import os
try:
os.environ[u'TRAVIS']
except KeyError:
travis = False
else:
travis = True
try:
os.environ[u'DISABLE_NETWORK_TESTS']
except KeyErr... | Revert skipif markers to use correct reasons (bug fixed in pytest) | Revert skipif markers to use correct reasons (bug fixed in pytest)
| Python | bsd-3-clause | hackebrot/cookiecutter,michaeljoseph/cookiecutter,willingc/cookiecutter,stevepiercy/cookiecutter,pjbull/cookiecutter,stevepiercy/cookiecutter,audreyr/cookiecutter,terryjbates/cookiecutter,luzfcb/cookiecutter,dajose/cookiecutter,dajose/cookiecutter,michaeljoseph/cookiecutter,Springerle/cookiecutter,terryjbates/cookiecut... |
022bbf819b3c4a14ade4100102d251eceb84c637 | tests/test_bijection.py | tests/test_bijection.py | """Test bijection class."""
import pytest
from collections_extended.bijection import bijection
def test_bijection():
"""General tests for bijection."""
b = bijection()
assert len(b) == 0
b['a'] = 1
assert len(b) == 1
assert b['a'] == 1
assert b.inverse[1] == 'a'
assert 'a' in b
assert 1 not in b
assert 1 i... | """Test bijection class."""
import pytest
from collections_extended.bijection import bijection
def test_bijection():
"""General tests for bijection."""
b = bijection()
assert len(b) == 0
b['a'] = 1
assert len(b) == 1
assert b['a'] == 1
assert b.inverse[1] == 'a'
assert 'a' in b
assert 1 not in b
assert 1 i... | Add test for bijection init from list of pairs | Add test for bijection init from list of pairs
| Python | apache-2.0 | mlenzen/collections-extended |
7f9a31a03e68e1d9dc6f420c6aa157e657da4157 | apps/core/templatetags/files.py | apps/core/templatetags/files.py | from pathlib import Path
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.filter
@stringfilter
def filename(path):
"""Removes traceback lines from a string (if any). It has no effect when
no 'Traceback' pattern has been found.
R... | from pathlib import Path
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.filter
@stringfilter
def filename(path):
"""Removes parent path from a relative or absolute filename
Returns: the filename
"""
return Path(path).name
| Fix filename template tag docstring | Fix filename template tag docstring
| Python | bsd-3-clause | Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel |
8a5d111b5c77ae9f7478dd7e73eca292c441d3fa | website_event_excerpt_img/__openerp__.py | website_event_excerpt_img/__openerp__.py | # -*- coding: utf-8 -*-
# © 2016 Antiun Ingeniería S.L. - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Excerpt + Image in Events",
"summary": "New layout for event summary, including an excerpt and image",
"version": "8.0.1.0.0",
"category": "Website",
"web... | # -*- coding: utf-8 -*-
# © 2016 Antiun Ingeniería S.L. - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Excerpt + Image in Events",
"summary": "New layout for event summary, including an excerpt and image",
"version": "8.0.1.0.0",
"category": "Website",
"web... | Update module name as changed in last module version. | Update module name as changed in last module version.
| Python | agpl-3.0 | open-synergy/event,open-synergy/event |
52c359c1348b9c21f7c47917d024d7c161652b43 | webapp/thing_test.py | webapp/thing_test.py | #!/usr/bin/env python
from thing import PiThing
# Instantiate a PiThing
pi_thing = PiThing()
# Get the current switch state
switch = pi_thing.read_switch()
print('Switch: {0}'.format(switch))
| #!/usr/bin/env python
from thing import PiThing
# Instantiate a PiThing
pi_thing = PiThing()
# Get the current switch state
switch = pi_thing.read_switch()
print('Switch: {0}'.format(switch))
# Blink the LED forever.
print('Blinking LED (Ctrl-C to stop)...')
while True:
pi_thing.set_led(True)
time.sleep(0.... | Add blink LED. TODO: Test on raspberry pi hardware. | Add blink LED. TODO: Test on raspberry pi hardware.
| Python | mit | beepscore/pi_thing,beepscore/pi_thing,beepscore/pi_thing |
ba6c2ba95f4d0ab8a6c153a617aa5d1c789318a5 | numpy/distutils/command/install.py | numpy/distutils/command/install.py |
from distutils.command.install import *
from distutils.command.install import install as old_install
class install(old_install):
def finalize_options (self):
old_install.finalize_options(self)
self.install_lib = self.install_libbase
|
import os
from distutils.command.install import *
from distutils.command.install import install as old_install
from distutils.file_util import write_file
class install(old_install):
def finalize_options (self):
old_install.finalize_options(self)
self.install_lib = self.install_libbase
def ru... | Fix bdist_rpm for path names containing spaces. | Fix bdist_rpm for path names containing spaces.
| Python | bsd-3-clause | empeeu/numpy,sonnyhu/numpy,dimasad/numpy,MaPePeR/numpy,tynn/numpy,dch312/numpy,stefanv/numpy,felipebetancur/numpy,ssanderson/numpy,MichaelAquilina/numpy,musically-ut/numpy,behzadnouri/numpy,ContinuumIO/numpy,madphysicist/numpy,mwiebe/numpy,stuarteberg/numpy,mwiebe/numpy,ChristopherHogan/numpy,rgommers/numpy,madphysicis... |
64dbe1d931edd38b4d731db18408e337d39e42c3 | cab/admin.py | cab/admin.py | from django.contrib import admin
from cab.models import Language, Snippet, SnippetFlag
class LanguageAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ['name']}
class SnippetAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'author', 'rating_score', 'pub_date')
list_filter = ('language',)
... | from django.contrib import admin
from cab.models import Language, Snippet, SnippetFlag
class LanguageAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ['name']}
class SnippetAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'author', 'rating_score', 'pub_date')
list_filter = ('language',)
... | Use raw_id_fields for users and snippets. | Use raw_id_fields for users and snippets.
| Python | bsd-3-clause | django/djangosnippets.org,django/djangosnippets.org,django/djangosnippets.org,django/djangosnippets.org,django-de/djangosnippets.org,django/djangosnippets.org,django-de/djangosnippets.org,django-de/djangosnippets.org,django-de/djangosnippets.org |
cb2cafc809481748ec64aa8ef9bfa3cc29660a6d | install_deps.py | install_deps.py | #!/usr/bin/env python
"""
Install the packages you have listed in the requirements file you input as
first argument.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys
import fileinput
import subprocess
from pip.req import parse_requirements
... | #!/usr/bin/env python
"""
Install the packages you have listed in the requirements file you input as
first argument.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys
import fileinput
import subprocess
from pip.req import parse_requirements
... | Correct for None appearing in requirements list | Correct for None appearing in requirements list
| Python | bsd-3-clause | Neurita/darwin |
fa92a5ff237abc0c3de169bac7784e48caa152dd | clean_lxd.py | clean_lxd.py | #!/usr/bin/env python
from __future__ import print_function
from argparse import ArgumentParser
from datetime import (
datetime,
timedelta,
)
import json
import os
import subprocess
import sys
def list_old_juju_containers(hours):
env = dict(os.environ)
containers = json.loads(subprocess.check_out... | #!/usr/bin/env python
from __future__ import print_function
from argparse import ArgumentParser
from datetime import (
datetime,
timedelta,
)
import json
import os
import subprocess
import sys
from dateutil import (
parser as date_parser,
tz,
)
def list_old_juju_containers(hours):
env = ... | Use dateutil to calculate age of container. | Use dateutil to calculate age of container. | Python | agpl-3.0 | mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju |
d360d4e5af09c5c194db783c4344aef10367b7f3 | kolla/cmd/build.py | kolla/cmd/build.py | #!/usr/bin/env python
# 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... | #!/usr/bin/env python
# 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... | Change the search path to look locally | Change the search path to look locally
In order to use tools/build.py, we need to search
locally for imports.
Closes-bug: #1592030
Change-Id: Idfa651c1268f93366de9f4e3fa80c33be42c71c3
| Python | apache-2.0 | mandre/kolla,intel-onp/kolla,mandre/kolla,GalenMa/kolla,openstack/kolla,stackforge/kolla,coolsvap/kolla,openstack/kolla,stackforge/kolla,dardelean/kolla-ansible,dardelean/kolla-ansible,dardelean/kolla-ansible,mrangana/kolla,rahulunair/kolla,nihilifer/kolla,intel-onp/kolla,rahulunair/kolla,nihilifer/kolla,mrangana/kolla... |
61fe996f79e34ac3f5be15213bfa2c16eccfa3ee | ptt_preproc_target.py | ptt_preproc_target.py | #!/usr/bin/env python
import json
from os import scandir
from os.path import (
join as path_join,
basename as to_basename,
splitext,
exists
)
import ptt_core
l = ptt_core.l
_TARGETS_DIR_PATH = 'targets'
def generate_target_from(json_path):
l.info('Generate target from {} ...'.format(json_pat... | #!/usr/bin/env python
import json
from pathlib import Path
from os import scandir
from os.path import (
join as path_join,
basename as to_basename,
splitext,
exists
)
import ptt_core
l = ptt_core.l
_TARGETS_DIR_PATH = Path('targets')
if not _TARGETS_DIR_PATH.exists():
_TARGETS_DIR_PATH.mkdir()... | Use pathlib in the target | Use pathlib in the target
| Python | mit | moskytw/mining-news |
5959bb60ca9e42d41386b2a1c672f7a1e666df0d | pybb/read_tracking.py | pybb/read_tracking.py | def update_read_tracking(topic, user):
tracking = user.readtracking
#if last_read > last_read - don't check topics
if tracking.last_read and tracking.last_read > (topic.last_post.updated or
topic.last_post.created):
return
if isinstance(track... | def update_read_tracking(topic, user):
tracking = user.readtracking
#if last_read > last_read - don't check topics
if tracking.last_read and tracking.last_read > (topic.last_post.updated or
topic.last_post.created):
return
if isinstance(track... | Fix bug in read tracking system | Fix bug in read tracking system
| Python | bsd-3-clause | gpetukhov/pybb,gpetukhov/pybb,gpetukhov/pybb |
22ac4b9f8dd7d74a84585131fb982f3594a91603 | hr_family/models/hr_children.py | hr_family/models/hr_children.py | # -*- coding:utf-8 -*-
#
#
# Copyright (C) 2011,2013 Michael Telahun Makonnen <mmakonnen@gmail.com>.
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation... | # -*- coding:utf-8 -*-
#
#
# Copyright (C) 2011,2013 Michael Telahun Makonnen <mmakonnen@gmail.com>.
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation... | Use the same selection like employee | [IMP][hr_family] Use the same selection like employee
| Python | agpl-3.0 | xpansa/hr,Vauxoo/hr,Eficent/hr,thinkopensolutions/hr,microcom/hr,hbrunn/hr,acsone/hr,hbrunn/hr,Antiun/hr,feketemihai/hr,thinkopensolutions/hr,Antiun/hr,xpansa/hr,Endika/hr,feketemihai/hr,Endika/hr,open-synergy/hr,VitalPet/hr,microcom/hr,Vauxoo/hr,VitalPet/hr,open-synergy/hr,Eficent/hr,acsone/hr |
ead2f795480ae7e671c93550e55cf9e106b2f306 | hubblestack_nova/pkgng_audit.py | hubblestack_nova/pkgng_audit.py | # -*- encoding: utf-8 -*-
'''
Hubble Nova plugin for FreeBSD pkgng audit
:maintainer: HubbleStack
:maturity: 20160421
:platform: FreeBSD
:requires: SaltStack
'''
from __future__ import absolute_import
import logging
log = logging.getLogger(__name__)
__tags__ = None
def __virtual__():
if 'FreeBSD' not in __grai... | # -*- encoding: utf-8 -*-
'''
Hubble Nova plugin for FreeBSD pkgng audit
:maintainer: HubbleStack
:maturity: 20160421
:platform: FreeBSD
:requires: SaltStack
'''
from __future__ import absolute_import
import logging
log = logging.getLogger(__name__)
def __virtual__():
if 'FreeBSD' not in __grains__['os']:
... | Update frebsd-pkg-audit to rely on yaml data and take data from hubble.py | Update frebsd-pkg-audit to rely on yaml data and take data from hubble.py
| Python | apache-2.0 | HubbleStack/Nova,avb76/Nova,SaltyCharles/Nova,cedwards/Nova |
5d448435477ce94273051b8351275d8c18838b8b | icekit/utils/fluent_contents.py | icekit/utils/fluent_contents.py | from django.contrib.contenttypes.models import ContentType
# USEFUL FUNCTIONS FOR FLUENT CONTENTS #############################################################
# Fluent Contents Helper Functions #################################################################
def create_content_instance(content_plugin_class, page, ... | from django.contrib.contenttypes.models import ContentType
# USEFUL FUNCTIONS FOR FLUENT CONTENTS #############################################################
# Fluent Contents Helper Functions #################################################################
def create_content_instance(content_plugin_class, test_p... | Change argument name to stop probable name clash. | Change argument name to stop probable name clash.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit |
2c652df7f7ec93ecad0eb23094f12c6acd86256c | python/hello.py | python/hello.py | #!/usr/bin/env python2
(lambda _, __, ___, ____, _____, ______, _______, ________:
getattr(
__import__(True.__class__.__name__[_] + [].__class__.__name__[__]),
().__class__.__eq__.__class__.__name__[:__] +
().__iter__().__class__.__name__[_____:________]
)(
_, (lambda _, __, ___:... | #!/usr/bin/env python2
print 'Hello, World!'
| Fix that damn obfuscated python | Fix that damn obfuscated python
| Python | mit | natemara/super-important-project,natemara/super-important-project |
8e3b686b413af1340ba1641b65d237791704e117 | protocols/views.py | protocols/views.py | from django.shortcuts import render
from django.conf.urls import *
from django.contrib.auth.decorators import user_passes_test
from .forms import ProtocolForm, TopicFormSet
def can_add_protocols(user):
return user.is_authenticated() and user.has_perm('protocols.add_protocol')
@user_passes_test(can_add_protoco... | from django.shortcuts import render
from django.conf.urls import *
from django.contrib.auth.decorators import user_passes_test
from .forms import ProtocolForm, TopicFormSet
def can_add_protocols(user):
return user.is_authenticated() and user.has_perm('protocols.add_protocol')
@user_passes_test(can_add_protoco... | Add method listing all the protocols | Add method listing all the protocols
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum |
93c4039bff64b86e203f8ae3c3c576343cc146c0 | stock_request_picking_type/models/stock_request_order.py | stock_request_picking_type/models/stock_request_order.py | # Copyright 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockRequestOrder(models.Model):
_inherit = 'stock.request.order'
@api.model
def _get_default_picking_type(self):
return self.env['stock.picki... | # Copyright 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockRequestOrder(models.Model):
_inherit = 'stock.request.order'
@api.model
def _get_default_picking_type(self):
return self.env['stock.picki... | Set Picking Type in Create | [IMP] Set Picking Type in Create
[IMP] Flake8
| Python | agpl-3.0 | OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse |
dc54aad6813f5ef1828f4706d87eab9f91af1c5a | pronto/serializers/obo.py | pronto/serializers/obo.py | import io
from typing import BinaryIO, ClassVar
from ..term import Term, TermData
from ..relationship import Relationship, RelationshipData
from ._fastobo import FastoboSerializer
from .base import BaseSerializer
class OboSerializer(FastoboSerializer, BaseSerializer):
format = "obo"
def dump(self, file):
... | import io
from typing import BinaryIO, ClassVar
from ..term import Term, TermData
from ..relationship import Relationship, RelationshipData
from ._fastobo import FastoboSerializer
from .base import BaseSerializer
class OboSerializer(FastoboSerializer, BaseSerializer):
format = "obo"
def dump(self, file):
... | Fix OBO serializer assuming `Ontology._terms` is properly ordered | Fix OBO serializer assuming `Ontology._terms` is properly ordered
| Python | mit | althonos/pronto |
47d329691e11ea332c17931ca40a822de788acfb | sanic_sentry.py | sanic_sentry.py | import logging
import sanic
import raven
import raven_aiohttp
from raven.handlers.logging import SentryHandler
class SanicSentry:
def __init__(self, app=None):
self.app = None
self.handler = None
self.client = None
if app is not None:
self.init_app(app)
def init_... | import logging
import sanic
from sanic.log import logger
import raven
import raven_aiohttp
from raven.handlers.logging import SentryHandler
class SanicSentry:
def __init__(self, app=None):
self.app = None
self.handler = None
self.client = None
if app is not None:
self... | Fix to work on Sanic 0.7 | Fix to work on Sanic 0.7
Sanic 0.7 changed the logger name and is now using the 'root' logger (instead of 'sanic').
I think it is better to import it directly from Sanic than to use `logging.getLogger` to avoid this kind of problem in the future... | Python | mit | serathius/sanic-sentry |
aee26ebb12ddcc410ad1b0eccf8fd740c6b9b39a | demo.py | demo.py | if __name__ == '__main__':
from NeuroIO import NeuroIO
from PreProcess import PreProcess
from Cluster import Cluster
neuroread = NeuroIO(r"C:\Users\USERNAME\Downloads\Brainbow-demo.tif")
img_data = neuroread.img_data_return()[0]
img_path = neuroread.img_data_return()[1]
pre_processed_data =... | if __name__ == '__main__':
from NeuroIO import NeuroIO
from PreProcess import PreProcess
from Cluster import Cluster
neuroread = NeuroIO(r"C:\Users\USERNAME\Downloads\Brainbow-demo.tif")
img_data = neuroread.img_data_return()[0]
img_path = neuroread.img_data_return()[1]
pre_processed_data =... | Enable support for the parallel dbscan. | Enable support for the parallel dbscan.
| Python | apache-2.0 | aluo-x/GRIDFIRE |
8c2db8786a0dd08c7ca039f491260f9407eb946c | dodo.py | dodo.py | # coding: utf8
DOIT_CONFIG = {'default_tasks': []}
CITEULIKE_GROUP = 19073
BIBFILE = 'docs/pyfssa.bib'
def task_download_bib():
"""Download bibliography from CiteULike group"""
return {
'actions': [' '.join([
'wget', '-O', BIBFILE,
'"http://www.citeulike.org/bibtex/group/{}?... | # coding: utf8
import os
DOIT_CONFIG = {'default_tasks': []}
CITEULIKE_GROUP = 19073
BIBFILE = 'docs/pyfssa.bib'
def task_download_bib():
"""Download bibliography from CiteULike group"""
return {
'actions': [' '.join([
'wget', '-O', BIBFILE,
'"http://www.citeulike.org/bibte... | Add task to upload documentation to github pages | Add task to upload documentation to github pages
| Python | isc | andsor/pyfssa,andsor/pyfssa |
49645ca7f579e5499f21e2192d16f4eed1271e82 | tests/integration/cli/sync_test.py | tests/integration/cli/sync_test.py | from mock import patch
from ...testcases import DustyIntegrationTestCase
from ...fixtures import busybox_single_app_bundle_fixture
class TestSyncCLI(DustyIntegrationTestCase):
def setUp(self):
super(TestSyncCLI, self).setUp()
busybox_single_app_bundle_fixture()
self.run_command('bundles ac... | from ...testcases import DustyIntegrationTestCase
from ...fixtures import busybox_single_app_bundle_fixture
class TestSyncCLI(DustyIntegrationTestCase):
def setUp(self):
super(TestSyncCLI, self).setUp()
busybox_single_app_bundle_fixture()
self.run_command('bundles activate busyboxa')
... | Clean up after sync integration tests | Clean up after sync integration tests
| Python | mit | gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty |
2a9406968552de04c5b3fdd5796dc3693af08a07 | src/engine/file_loader.py | src/engine/file_loader.py | import os
import json
'''
data_dir = os.path.join(
os.path.split(
os.path.split(os.path.dirname(__file__))[0])[0], 'data')
'''
data_dir = os.path.join(os.environ['PORTER'], 'data')
def read_and_parse_json(data_type):
sub_dir = os.path.join(data_dir, data_type)
elements = []
def full_path(fil... | import os
import json
data_dir = os.path.join(os.environ['PORTER'], 'data')
def read_and_parse_json(data_type):
sub_dir = os.path.join(data_dir, data_type)
elements = []
def full_path(file_name):
return os.path.join(sub_dir, file_name)
def only_json(file_name):
return file_name.ends... | Remove commented file loading code | Remove commented file loading code
| Python | mit | Tactique/game_engine,Tactique/game_engine |
0c593e993cb8fb4ea6b3031454ac359efa6aaf5c | states-pelican.py | states-pelican.py | import salt.exceptions
import subprocess
def build_site(name, output="/srv/www"):
# /srv/salt/_states/pelican.py
# Generates static site with pelican -o $output $name
# Sorry.
# -- Jadon Bennett, 2015
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# I don't know how to ma... | import salt.exceptions
import subprocess
def build_site(name, output="/srv/www"):
# /srv/salt/_states/pelican.py
# Generates static site with pelican -o $output $name
# Sorry.
# -- Jadon Bennett, 2015
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
current_state = __salt__... | Move subprocess stuff to an execution module for Pelican. | Move subprocess stuff to an execution module for Pelican.
| Python | mit | lvl1/salt-formulas |
4530325e460d38086201573d85a9ae95fc877a4c | webvtt/exceptions.py | webvtt/exceptions.py |
class MalformedFileError(Exception):
"""Error raised when the file is not well formatted"""
|
class MalformedFileError(Exception):
"""Error raised when the file is not well formatted"""
class MalformedCaptionError(Exception):
"""Error raised when a caption is not well formatted"""
| Add new exception for malformed captions | Add new exception for malformed captions
| Python | mit | glut23/webvtt-py,sampattuzzi/webvtt-py |
7d9c4a9f173b856e92e5586d1b961d876fb212a4 | test/dependencies_test.py | test/dependencies_test.py | import luigi
import sciluigi as sl
import os
TESTFILE_PATH = '/tmp/test.out'
class TestTask(sl.Task):
def out_data(self):
return sl.TargetInfo(self, TESTFILE_PATH)
def run(self):
with self.out_data().open('w') as outfile:
outfile.write('File written by luigi\n')
class TestRunTas... | import luigi
import sciluigi as sl
import os
TESTFILE_PATH = '/tmp/test.out'
class TestTask(sl.Task):
def out_data(self):
return sl.TargetInfo(self, TESTFILE_PATH)
def run(self):
with self.out_data().open('w') as outfile:
outfile.write('File written by luigi\n')
class TestRunTas... | Make sure test works with new API | Make sure test works with new API
| Python | mit | pharmbio/sciluigi,pharmbio/sciluigi,samuell/sciluigi |
321258a01b735d432fcc103e17c7eb3031c6153f | scheduler.py | scheduler.py | from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import warner
import archiver
import announcer
import flagger
import os
logging.basicConfig()
sched = BlockingScheduler()
@sched.scheduled_job("cron", hour=4)
#@sched.scheduled_job("cron", hour="*", minute="*/10") # for testing
def destalina... | from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import warner
import archiver
import announcer
import flagger
import os
# When testing changes, set the "TEST_SCHEDULE" envvar to run more often
if os.getenv("TEST_SCHEDULE"):
schedule_kwargs = {"hour": "*", "minute": "*/10"}
else:
s... | Switch to a test schedule based on the environment | Switch to a test schedule based on the environment
Switching an environment variable and kicking the `clock` process feels
like a neater solution than commenting out one line, uncommenting
another, and redeploying.
| Python | apache-2.0 | randsleadershipslack/destalinator,TheConnMan/destalinator,royrapoport/destalinator,underarmour/destalinator,royrapoport/destalinator,TheConnMan/destalinator,randsleadershipslack/destalinator |
a7e1b1961d14306f16c97e66982f4aef5b203e0a | tests/test_acf.py | tests/test_acf.py | import io
import pytest
from steamfiles import acf
test_file_name = 'tests/test_data/appmanifest_202970.acf'
@pytest.yield_fixture
def acf_data():
with open(test_file_name, 'rt') as f:
yield f.read()
@pytest.mark.usefixtures('acf_data')
def test_loads_dumps(acf_data):
assert acf.dumps(acf.loads(acf... | import io
import os
import pytest
from steamfiles import acf
test_file_name = os.path.join(os.path.dirname(__file__), 'test_data/appmanifest_202970.acf')
@pytest.yield_fixture
def acf_data():
with open(test_file_name, 'rt') as f:
yield f.read()
@pytest.mark.usefixtures('acf_data')
def test_loads_dumps(a... | Fix relative path not working properly 50% of the time… | Fix relative path not working properly 50% of the time…
| Python | mit | leovp/steamfiles |
e1bdfbb226795f4dd15fefb109ece2aa9659f421 | tests/test_ssl.py | tests/test_ssl.py | from nose.tools import assert_true, assert_false, assert_equal, \
assert_list_equal, raises
import datajoint as dj
from . import CONN_INFO
from pymysql.err import OperationalError
class TestSSL:
@staticmethod
def test_secure_connection():
result = dj.conn(**CONN_INFO, reset=Tr... | from nose.tools import assert_true, assert_false, assert_equal, \
assert_list_equal, raises
import datajoint as dj
from . import CONN_INFO
from pymysql.err import OperationalError
class TestSSL:
# @staticmethod
# def test_secure_connection():
# result = dj.conn(**CONN_INFO, re... | Disable secure test until new test rig complete. | Disable secure test until new test rig complete.
| Python | lgpl-2.1 | eywalker/datajoint-python,datajoint/datajoint-python,dimitri-yatsenko/datajoint-python |
96469afbd9d01b0e4f43e93a0edfd3dc84bfa2f3 | Monstr/Core/Config.py | Monstr/Core/Config.py | import ConfigParser
Config = ConfigParser.ConfigParser()
import os
print os.getcwd()
try:
Config.read('/opt/monstr/current.cfg')
except Exception as e:
print 'WARNING! Configuration is missing. Using test_conf.cfg'
Config.read('test.cfg')
def get_section(section):
result = {}
if section in Con... | import ConfigParser
import os
CONFIG_PATH = '/opt/monstr/current.cfg'
Config = ConfigParser.ConfigParser()
print os.getcwd()
if os.path.isfile(CONFIG_PATH):
Config.read(CONFIG_PATH)
else:
print 'WARNING! Configuration is missing. Using test_conf.cfg'
Config.read('test.cfg')
def get_section(section):... | Check whether current config exists usinf os and if | FIX: Check whether current config exists usinf os and if
| Python | apache-2.0 | tier-one-monitoring/monstr,tier-one-monitoring/monstr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.