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 |
|---|---|---|---|---|---|---|---|---|---|---|
4336a5d3eaf5500a6f3041b30c7887361dea5737 | tests/test_formatting.py | tests/test_formatting.py | # -*- coding: utf-8 -*-
import click
def test_basic_functionality(runner):
@click.command()
def cli():
"""First paragraph.
This is a very long second
paragraph and not correctly
wrapped but it will be rewrapped.
\b
This is
a paragraph
without r... | # -*- coding: utf-8 -*-
import click
def test_basic_functionality(runner):
@click.command()
def cli():
"""First paragraph.
This is a very long second
paragraph and not correctly
wrapped but it will be rewrapped.
\b
This is
a paragraph
without r... | Add failing test for formatting | Add failing test for formatting
| Python | bsd-3-clause | her0e1c1/click,MakerDAO/click,Akasurde/click,scalp42/click,khwilson/click,polinom/click,amjith/click,hellodk/click,jvrsantacruz/click,naoyat/click,lucius-feng/click,dastergon/click,TomRegan/click,hackebrot/click,cbandera/click,oss6/click,GeoffColburn/click,willingc/click,pallets/click,pgkelley4/click,glorizen/click,mit... | ---
+++
@@ -48,3 +48,37 @@
'Options:',
' --help Show this message and exit.',
]
+
+
+def test_wrapping_long_options_strings(runner):
+ @click.group()
+ def cli():
+ """Top level command
+ """
+
+ @cli.group()
+ def a_very_long():
+ """Second level
+ """... |
cb2dec164b18dc671dabdafe221bfd6aac4fc01e | onitu/drivers/local_storage/tests/driver.py | onitu/drivers/local_storage/tests/driver.py | import os
import sh
from path import path
from tests.utils.testdriver import TestDriver
from tests.utils import files
from tests.utils.tempdirs import dirs
class Driver(TestDriver):
SPEED_BUMP = 1
def __init__(self, *args, **options):
if 'root' not in options:
options['root'] = dirs.cre... | import os
from path import path
from tests.utils.testdriver import TestDriver
from tests.utils import files
from tests.utils.tempdirs import dirs
class Driver(TestDriver):
SPEED_BUMP = 1
def __init__(self, *args, **options):
if 'root' not in options:
options['root'] = dirs.create()
... | Remove dependency to sh in the tests | LocalStorage: Remove dependency to sh in the tests
| Python | mit | onitu/onitu,onitu/onitu,onitu/onitu | ---
+++
@@ -1,6 +1,5 @@
import os
-import sh
from path import path
from tests.utils.testdriver import TestDriver
@@ -26,7 +25,15 @@
dirs.delete(self.root)
def mkdir(self, subdirs):
- return sh.mkdir('-p', self.root / subdirs)
+ (self.root / subdirs).makedirs_p()
+
+ # Give ... |
219f67e3e15c548b81211b0baff475621f66a7fa | scripts/dbutil/compute_asos_sts.py | scripts/dbutil/compute_asos_sts.py | # Look into the ASOS database and figure out the start time of various
# sites for a given network.
import sys
sys.path.insert(0, '../lib')
import db, network
asos = db.connect('asos')
mesosite = db.connect('mesosite')
net = sys.argv[1]
table = network.Table( net )
ids = `tuple(table.sts.keys())`
rs = asos.query("... | # Look into the ASOS database and figure out the start time of various
# sites for a given network.
import iemdb, network, sys
asos = iemdb.connect('asos', bypass=True)
acursor = asos.cursor()
mesosite = iemdb.connect('mesosite')
mcursor = mesosite.cursor()
net = sys.argv[1]
table = network.Table( net )
ids = `tup... | Make the output less noisey, more informative | Make the output less noisey, more informative
| Python | mit | akrherz/iem,akrherz/iem,akrherz/iem,akrherz/iem,akrherz/iem | ---
+++
@@ -1,20 +1,30 @@
# Look into the ASOS database and figure out the start time of various
# sites for a given network.
-import sys
-sys.path.insert(0, '../lib')
-import db, network
-asos = db.connect('asos')
-mesosite = db.connect('mesosite')
+
+import iemdb, network, sys
+asos = iemdb.connect('asos', byp... |
9ea29573841307ffe24b597dd8d1e0b783f81a2a | tests/app/views/test_application.py | tests/app/views/test_application.py | import mock
from nose.tools import assert_equal, assert_true
from ...helpers import BaseApplicationTest
class TestApplication(BaseApplicationTest):
def setup(self):
super(TestApplication, self).setup()
def test_should_have_analytics_on_page(self):
res = self.client.get('/')
assert_equ... | import mock
from nose.tools import assert_equal, assert_true
from ...helpers import BaseApplicationTest
class TestApplication(BaseApplicationTest):
def setup(self):
super(TestApplication, self).setup()
def test_analytics_code_should_be_in_javascript(self):
res = self.client.get('/static/javas... | Correct test to point at application.js | Correct test to point at application.js
The JS to search was previously in the page rather
than concatenated into the main JavaScript file.
| Python | mit | alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,mtekel/digitalmarketplace-buyer-frontend,mtekel/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalm... | ---
+++
@@ -7,8 +7,8 @@
def setup(self):
super(TestApplication, self).setup()
- def test_should_have_analytics_on_page(self):
- res = self.client.get('/')
+ def test_analytics_code_should_be_in_javascript(self):
+ res = self.client.get('/static/javascripts/application.js')
... |
e0adf4df50dcb366e7977f46e1f09ca04dd48cf2 | blockbuster/bb_logging.py | blockbuster/bb_logging.py | import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotat... | import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotat... | Update log output so that it works more nicely with ELK | Update log output so that it works more nicely with ELK
| Python | mit | mattstibbs/blockbuster-server,mattstibbs/blockbuster-server | ---
+++
@@ -9,7 +9,7 @@
# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotatingFileHandler('./logs/app.log', when='midnight', delay=False, encoding=None,
- backupCount=5)
+ backupCount=7... |
f7a1a849161007e3703b41758e99dd45609c9753 | renovation_tax_be/models/account_invoice.py | renovation_tax_be/models/account_invoice.py | from odoo import models, api
class AccountInvoice(models.Model):
_inherit = "account.invoice"
@api.onchange('fiscal_position_id')
def somko_update_tax(self):
for line in self.invoice_line_ids:
line._onchange_product_id()
| from odoo import models, api
class AccountInvoice(models.Model):
_inherit = "account.invoice"
@api.onchange('fiscal_position_id')
def somko_update_tax(self):
for line in self.invoice_line_ids:
price = line.unit_price
line._onchange_product_id()
line.unit_price ... | Fix loss of unit price if edited | Fix loss of unit price if edited
| Python | agpl-3.0 | Somko/Odoo-Public,Somko/Odoo-Public | ---
+++
@@ -7,4 +7,6 @@
@api.onchange('fiscal_position_id')
def somko_update_tax(self):
for line in self.invoice_line_ids:
+ price = line.unit_price
line._onchange_product_id()
+ line.unit_price = price |
a9e9705e6963569cb0c88135ce539320aef77ed6 | examples/explorer/settings.py | examples/explorer/settings.py | import os
from rororo import GET, static
# Debug settings
DEBUG = True
# Explorer settings
ROOT_DIR = os.path.expanduser('~')
SHOW_HIDDEN_ITEMS = True
# List of available routes
ROUTES = ('',
GET('/{path:path}', 'views.explorer', name='explorer',
renderer='explorer.html'),
)
| import os
from rororo import GET
# Debug settings
DEBUG = True
# Explorer settings
ROOT_DIR = os.path.expanduser('~')
SHOW_HIDDEN_ITEMS = True
# List of available routes
ROUTES = ('',
GET('/{path:path}', 'views.explorer', name='explorer',
renderer='explorer.html'),
)
| Remove unnecessary import in explorer example. | Remove unnecessary import in explorer example. | Python | bsd-3-clause | playpauseandstop/rororo,playpauseandstop/rororo | ---
+++
@@ -1,6 +1,6 @@
import os
-from rororo import GET, static
+from rororo import GET
# Debug settings |
c22c7a63c85b52c4e05ac0fe6a9f05960705872b | tests/test_application.py | tests/test_application.py | # Copyright 2013 Donald Stufft
#
# 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, so... | # Copyright 2013 Donald Stufft
#
# 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, so... | Test the cli instantiation a bit better | Test the cli instantiation a bit better
| Python | apache-2.0 | techtonik/warehouse,robhudson/warehouse,mattrobenolt/warehouse,robhudson/warehouse,techtonik/warehouse,mattrobenolt/warehouse,mattrobenolt/warehouse | ---
+++
@@ -39,6 +39,11 @@
)
-def test_cli_instantiation():
+def test_cli_instantiation(capsys):
with pytest.raises(SystemExit):
Warehouse.from_cli(["-h"])
+
+ out, err = capsys.readouterr()
+
+ assert "usage: warehouse" in out
+ assert not err |
84c4aa73e6792dad6853866c66c756073df71f27 | tests/test_replace_all.py | tests/test_replace_all.py | import unittest, os, sys
from custom_test_case import CustomTestCase
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.append(os.path.join(PROJECT_ROOT, ".."))
from CodeConverter import CodeConverter
class TestReplaceAll(unittest.TestCase, CustomTestCase):
# All replacement
def test_replace_objc(self):
... | import unittest, os, sys
from custom_test_case import CustomTestCase
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.append(os.path.join(PROJECT_ROOT, ".."))
from CodeConverter import CodeConverter
class TestReplaceAll(unittest.TestCase, CustomTestCase):
# All replacement
def test_replace_objc(self):
... | Test for block with multi args | Test for block with multi args
| Python | mit | kyamaguchi/SublimeObjC2RubyMotion,kyamaguchi/SublimeObjC2RubyMotion | ---
+++
@@ -14,5 +14,10 @@
expected = 'aWindow = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)'
self.assertSentence(CodeConverter(source).result(), expected)
+ def test_block_with_two_args_in_one_line(self):
+ source = """[aSet enumerateObjectsUsingBlock:^(id obj, BOOL *stop... |
a47b5506476f9d0e4dbb2eb24cd22da61f42eb65 | bixi/api.py | bixi/api.py | from tastypie.resources import ModelResource
from models import Station
class StationResource(ModelResource):
class Meta:
allowed_methods = ['get']
queryset = Station.objects.all()
resource_name = 'station'
| from tastypie.resources import ModelResource
from models import Station, Update
class StationResource(ModelResource):
def dehydrate(self, bundle):
update = Update.objects.filter(station__id=bundle.data['id']).latest()
bundle.data['nb_bikes'] = update.nb_bikes
bundle.data['nb_empty_docks']... | Include the number of available bikes and docks from the latest update. | Include the number of available bikes and docks from the latest update.
| Python | bsd-3-clause | flebel/django-bixi | ---
+++
@@ -1,9 +1,15 @@
from tastypie.resources import ModelResource
-from models import Station
+from models import Station, Update
class StationResource(ModelResource):
+ def dehydrate(self, bundle):
+ update = Update.objects.filter(station__id=bundle.data['id']).latest()
+ bundle.data['nb... |
5fc0854f54f2946c2b38a8b3c03a553c8a838aed | shale/webdriver.py | shale/webdriver.py | from selenium import webdriver
from selenium.webdriver.remote.switch_to import SwitchTo
from selenium.webdriver.remote.mobile import Mobile
from selenium.webdriver.remote.errorhandler import ErrorHandler
from selenium.webdriver.remote.remote_connection import RemoteConnection
class ResumableRemote(webdriver.Remote):
... | from selenium import webdriver
from selenium.webdriver.remote.switch_to import SwitchTo
from selenium.webdriver.remote.mobile import Mobile
from selenium.webdriver.remote.errorhandler import ErrorHandler
from selenium.webdriver.remote.remote_connection import RemoteConnection
class ResumableRemote(webdriver.Remote):
... | Fix a string type-checking bug. | Fix a string type-checking bug.
| Python | mit | cardforcoin/shale,mhluongo/shale,mhluongo/shale,cardforcoin/shale | ---
+++
@@ -8,10 +8,13 @@
class ResumableRemote(webdriver.Remote):
def __init__(self, command_executor='http://127.0.0.1:4444/wd/hub',
session_id=None, **kwargs):
- #desired_capabilities=None, browser_profile=None, proxy=None, keep_alive=False):
if session_id is not None:
... |
6c999c654e1fffe067592067bd4314cff011cda5 | permuta/math/counting.py | permuta/math/counting.py |
def factorial(n):
res = 1
for i in range(2, n+1):
res *= i
return res
def binomial(n,k):
if k > n:
return 0
if n-k < k:
k = n-k
res = 1
for i in range(1,k+1):
res = res * (n - (k - i)) // i
return res
def catalan(n):
return binomial(2*n,n)//n+1
|
def factorial(n):
res = 1
for i in range(2, n+1):
res *= i
return res
def binomial(n,k):
if k > n:
return 0
if n-k < k:
k = n-k
res = 1
for i in range(1,k+1):
res = res * (n - (k - i)) // i
return res
def catalan(n):
return binomial(2*n,n)//(n+1)
| Fix catalan since me is dumb | Fix catalan since me is dumb
| Python | bsd-3-clause | PermutaTriangle/Permuta | ---
+++
@@ -16,4 +16,4 @@
return res
def catalan(n):
- return binomial(2*n,n)//n+1
+ return binomial(2*n,n)//(n+1) |
37740e4b965a59fc1508b897d791900017daae42 | PublicWebServicesAPI_AND_servercommandScripts/addInfoToCSVreport.py | PublicWebServicesAPI_AND_servercommandScripts/addInfoToCSVreport.py | #!/usr/bin/env python3
from csv import reader
from sys import stdin
from xmlrpc.client import ServerProxy
from ssl import create_default_context, Purpose
# Script to add user account notes to account_configurations.csv
host="https://localhost:9192/rpc/api/xmlrpc" # If not localhost then this address will need to ... | #!/usr/bin/env python3
from csv import reader
from sys import stdin
from xmlrpc.client import ServerProxy
from ssl import create_default_context, Purpose
# Script to user account notes to the Shared account configuration report(account_configurations.csv)
host="https://localhost:9192/rpc/api/xmlrpc" # If not loca... | Change comment to reflect a shared account report | Update: Change comment to reflect a shared account report
| Python | mit | PaperCutSoftware/PaperCutExamples,PaperCutSoftware/PaperCutExamples,PaperCutSoftware/PaperCutExamples,PaperCutSoftware/PaperCutExamples,PaperCutSoftware/PaperCutExamples,PaperCutSoftware/PaperCutExamples | ---
+++
@@ -7,7 +7,7 @@
from ssl import create_default_context, Purpose
-# Script to add user account notes to account_configurations.csv
+# Script to user account notes to the Shared account configuration report(account_configurations.csv)
host="https://localhost:9192/rpc/api/xmlrpc" # If not localhost then ... |
023568228dc2ffcf772edb4d5335c0c755a7e37c | revel/setup.py | revel/setup.py | import subprocess
import sys
import os
import setup_util
import time
def start(args):
setup_util.replace_text("revel/src/benchmark/conf/app.conf", "tcp\(.*:3306\)", "tcp(" + args.database_host + ":3306)")
subprocess.call("go get github.com/robfig/revel/cmd", shell=True, cwd="revel")
subprocess.call("go build -o ... | import subprocess
import sys
import os
import setup_util
import time
def start(args):
setup_util.replace_text("revel/src/benchmark/conf/app.conf", "tcp\(.*:3306\)", "tcp(" + args.database_host + ":3306)")
subprocess.call("go get -u github.com/robfig/revel/revel", shell=True, cwd="revel")
subprocess.call("go buil... | Update start process to reflect new path for /cmd | Update start process to reflect new path for /cmd
| Python | bsd-3-clause | raziel057/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,sxend/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,fabianmurariu/Framework... | ---
+++
@@ -6,8 +6,8 @@
def start(args):
setup_util.replace_text("revel/src/benchmark/conf/app.conf", "tcp\(.*:3306\)", "tcp(" + args.database_host + ":3306)")
- subprocess.call("go get github.com/robfig/revel/cmd", shell=True, cwd="revel")
- subprocess.call("go build -o bin/revel github.com/robfig/revel/cmd"... |
1cfd8618931da76fc83745a45206df08f058c453 | pog_absolute_pointing.py | pog_absolute_pointing.py | import numpy as np
from Chandra.Time import DateTime
import plot_aimpoint
# Get 99th percential absolute pointing radius
plot_aimpoint.opt = plot_aimpoint.get_opt()
asols = plot_aimpoint.get_asol()
# Last six months of data
asols = asols[asols['time'] > DateTime(-183).secs]
# center of box of range of data
mid_dy = (... | import numpy as np
from Chandra.Time import DateTime
import plot_aimpoint
# Get 99th percential absolute pointing radius
plot_aimpoint.opt = plot_aimpoint.get_opt()
asols = plot_aimpoint.get_asol()
# Last six months of data
asols = asols[asols['time'] > DateTime(-183).secs]
# center of box of range of data
mid_dy = (... | Use print as a function and tweak output text | Use print as a function and tweak output text
| Python | bsd-2-clause | sot/aimpoint_mon,sot/aimpoint_mon | ---
+++
@@ -15,4 +15,4 @@
dr = np.sqrt((asols['dy'] - mid_dy) ** 2 + (asols['dz'] - mid_dz) ** 2)
dr_99 = np.percentile(dr, 99)
dr_99_arcsec = dr_99 * 20
-print "99th percentile radius of 6m data is {} arcsec".format(dr_99_arcsec)
+print("99th percentile radius of 6-month data is {} arcsec".format(dr_99_arcsec)) |
999ff373d40dd98f3ffccb2478ac6d464e3332e3 | flask_gzip.py | flask_gzip.py | import gzip
import StringIO
from flask import request
class Gzip(object):
def __init__(self, app, compress_level=6):
self.app = app
self.compress_level = compress_level
self.app.after_request(self.after_request)
def after_request(self, response):
accept_encoding = request.head... | import gzip
import StringIO
from flask import request
class Gzip(object):
def __init__(self, app, compress_level=6, minimum_size=500):
self.app = app
self.compress_level = compress_level
self.minimum_size = minimum_size
self.app.after_request(self.after_request)
def after_requ... | Fix Accept-Encoding match (split would result in ' gzip', which doesn't match. | Fix Accept-Encoding match (split would result in ' gzip', which doesn't match.
Add minimum_size attribute.
| Python | mit | libwilliam/flask-compress,libwilliam/flask-compress,saymedia/flask-compress,libwilliam/flask-compress,saymedia/flask-compress,wichitacode/flask-compress,wichitacode/flask-compress | ---
+++
@@ -4,23 +4,21 @@
class Gzip(object):
- def __init__(self, app, compress_level=6):
+ def __init__(self, app, compress_level=6, minimum_size=500):
self.app = app
self.compress_level = compress_level
+ self.minimum_size = minimum_size
self.app.after_request(self.afte... |
c878a67815ef47abdb0bf4203a23ac0ece4feda6 | src/CameraImage.py | src/CameraImage.py | import gtk, gobject
import numpy as N
class CameraImage(gtk.Image):
__gproperties__ = {
'data' : (gobject.TYPE_PYOBJECT,
'Image data',
'NumPy ndarray containing the data',
gobject.PARAM_READWRITE)
}
def __init__(self):
gtk.Image.__gobject_init__... | import gtk, gobject
import numpy as N
class CameraImage(gtk.Image):
__gproperties__ = {
'data' : (gobject.TYPE_PYOBJECT,
'Image data',
'NumPy ndarray containing the data',
gobject.PARAM_READWRITE)
}
def __init__(self):
gtk.Image.__gobject_init__... | Convert data to unsigned 8-bit when displaying | Convert data to unsigned 8-bit when displaying
| Python | mit | ptomato/Beams | ---
+++
@@ -23,6 +23,11 @@
def do_set_property(self, property, value):
if property.name == 'data':
+ # Convert to 8-bit RGB data
+ if value.dtype is not N.uint8:
+ value = N.array(value, dtype=N.uint8)
+ if len(value.shape) != 3:
+ val... |
837f25cd2606da70130b21109e0c03d6055622cd | dvol_python/__init__.py | dvol_python/__init__.py | import os
from hypothesis import settings, Verbosity
settings.register_profile("ci", settings(max_examples=1000))
settings.register_profile("dev", settings(max_examples=5))
settings.register_profile("debug", settings(max_examples=10, verbosity=Verbosity.verbose))
settings.load_profile(os.environ.get(u'HYPOTHESIS_PROF... | Address review feedback: set hypothesis settings depending on env. Default to dev. | Address review feedback: set hypothesis settings depending on env. Default to dev.
| Python | apache-2.0 | ClusterHQ/dvol,ClusterHQ/dvol,ClusterHQ/dvol | ---
+++
@@ -0,0 +1,8 @@
+import os
+from hypothesis import settings, Verbosity
+
+settings.register_profile("ci", settings(max_examples=1000))
+settings.register_profile("dev", settings(max_examples=5))
+settings.register_profile("debug", settings(max_examples=10, verbosity=Verbosity.verbose))
+
+settings.load_profil... | |
4a65dacb992ef48dbbaf9ca168f0b4e5567abe90 | falmer/content/models/selection_grid.py | falmer/content/models/selection_grid.py | from wagtail.core import blocks
from wagtail.core.blocks import RichTextBlock
from wagtail.core.fields import StreamField
from wagtail.admin.edit_handlers import TabbedInterface, StreamFieldPanel, ObjectList
from falmer.content.blocks import HeroImageBlock, FalmerImageChooserBlock
from falmer.content.models.core impor... | from wagtail.core import blocks
from wagtail.core.blocks import RichTextBlock
from wagtail.core.fields import StreamField
from wagtail.admin.edit_handlers import TabbedInterface, StreamFieldPanel, ObjectList
from falmer.content import components
from falmer.content.blocks import HeroImageBlock, FalmerImageChooserBlock... | Add text to selection grid | Add text to selection grid
| Python | mit | sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer | ---
+++
@@ -3,6 +3,7 @@
from wagtail.core.fields import StreamField
from wagtail.admin.edit_handlers import TabbedInterface, StreamFieldPanel, ObjectList
+from falmer.content import components
from falmer.content.blocks import HeroImageBlock, FalmerImageChooserBlock
from falmer.content.models.core import Page
... |
ecd0c00766304f1e5b12e6067a846033a4ee36d5 | txlege84/topics/admin.py | txlege84/topics/admin.py | from django.contrib import admin
from topics.models import Issue, StoryPointer, Stream, Topic
admin.site.register(Topic)
admin.site.register(Issue)
admin.site.register(Stream)
admin.site.register(StoryPointer)
| from django.contrib import admin
from topics.models import Issue, StoryPointer, Stream, Topic
@admin.register(Issue)
class IssueAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
admin.site.register(Topic)
admin.site.register(Stream)
admin.site.register(StoryPointer)
| Move Issue ModelAdmin to new register syntax | Move Issue ModelAdmin to new register syntax
| Python | mit | texastribune/txlege84,texastribune/txlege84,texastribune/txlege84,texastribune/txlege84 | ---
+++
@@ -2,7 +2,11 @@
from topics.models import Issue, StoryPointer, Stream, Topic
+
+@admin.register(Issue)
+class IssueAdmin(admin.ModelAdmin):
+ prepopulated_fields = {'slug': ('name',)}
+
admin.site.register(Topic)
-admin.site.register(Issue)
admin.site.register(Stream)
admin.site.register(StoryPoin... |
d76cbdd768964a2583cf28ab9efaf46964c815ae | swf/core.py | swf/core.py | # -*- coding:utf-8 -*-
from boto.swf.layer1 import Layer1
AWS_CREDENTIALS = {
'aws_access_key_id': None,
'aws_secret_access_key': None
}
def set_aws_credentials(aws_access_key_id, aws_secret_access_key):
"""Set default credentials."""
AWS_CREDENTIALS.update({
'aws_access_key_id': aws_access_... | # -*- coding:utf-8 -*-
from boto.swf.layer1 import Layer1
AWS_CREDENTIALS = {
#'aws_access_key_id': AWS_ACCESS_KEY_ID,
#'aws_secret_access_key': AWS_SECRET_ACCESS_KEY,
}
def set_aws_credentials(aws_access_key_id, aws_secret_access_key):
"""Set default credentials."""
AWS_CREDENTIALS.update({
... | Update ConnectedSWFObject: raise KeyError if credentials are not set | Update ConnectedSWFObject: raise KeyError if credentials are not set
| Python | mit | botify-labs/python-simple-workflow,botify-labs/python-simple-workflow | ---
+++
@@ -3,8 +3,8 @@
from boto.swf.layer1 import Layer1
AWS_CREDENTIALS = {
- 'aws_access_key_id': None,
- 'aws_secret_access_key': None
+ #'aws_access_key_id': AWS_ACCESS_KEY_ID,
+ #'aws_secret_access_key': AWS_SECRET_ACCESS_KEY,
}
@@ -23,16 +23,12 @@
into the child, adding a `connection... |
abb1d2db9052391c78fb09952b58a5331046aae5 | pylinks/links/tests.py | pylinks/links/tests.py | from django.test import TestCase
from .models import Category, Link
class CategoryModelTests(TestCase):
def test_category_sort(self):
Category(title='Test 2', slug='test2').save()
Category(title='Test 1', slug='test1').save()
self.assertEqual(['Test 1', 'Test 2'], map(str, Category.objec... | from django.test import Client, TestCase
from .models import Category, Link
class CategoryModelTests(TestCase):
def test_category_sort(self):
Category(title='Test 2', slug='test2').save()
Category(title='Test 1', slug='test1').save()
self.assertEqual(['Test 1', 'Test 2'], map(str, Catego... | Add test for link redirect | Add test for link redirect
| Python | mit | michaelmior/pylinks,michaelmior/pylinks,michaelmior/pylinks | ---
+++
@@ -1,4 +1,4 @@
-from django.test import TestCase
+from django.test import Client, TestCase
from .models import Category, Link
@@ -23,3 +23,11 @@
def test_link_title(self):
self.assertEqual(str(self.link), 'GitHub')
+
+ def test_increment_visits(self):
+ self.link.save()
+ ... |
045574a936df26798962f230568de33458495c09 | spacy/about.py | spacy/about.py | # inspired from:
# https://python-packaging-user-guide.readthedocs.org/en/latest/single_source_version/
# https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
__title__ = 'spacy'
__version__ = '2.0.0a0'
__summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython'
__uri__... | # inspired from:
# https://python-packaging-user-guide.readthedocs.org/en/latest/single_source_version/
# https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
__title__ = 'spacy-nightly'
__version__ = '2.0.0a1'
__summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython'... | Update package name and increment version | Update package name and increment version
| Python | mit | aikramer2/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,aikramer2/spaCy,honnibal/spaCy,explosion/spaCy,aikramer2/spaCy,recognai/spaCy,recognai/spaCy,recognai/spaCy,spacy-io/spaCy,aikramer2/spaCy,spacy-io/sp... | ---
+++
@@ -2,8 +2,8 @@
# https://python-packaging-user-guide.readthedocs.org/en/latest/single_source_version/
# https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
-__title__ = 'spacy'
-__version__ = '2.0.0a0'
+__title__ = 'spacy-nightly'
+__version__ = '2.0.0a1'
__summary__ = 'Industrial-stren... |
4f1bbe6435f2c899915ab72d990a649d4e494553 | grum/views.py | grum/views.py | from grum import app, db
from grum.models import User
from flask import render_template, request
@app.route("/")
def main():
# # Login verification code
# username = request.form('username')
# password = request.form('password')
#
# user = User.query.filter_by(username=username).first_or_404()
... | from grum import app, db
from grum.models import User
from flask import render_template, request, redirect
@app.route("/", methods=['GET', 'POST'])
def main():
if request.method == "POST":
# Login verification code
username = request.form['username']
password = request.form['password']
... | Fix register and login y0 | Fix register and login y0
| Python | mit | Grum-Hackdee/grum-web,Grum-Hackdee/grum-web,Grum-Hackdee/grum-web,Grum-Hackdee/grum-web | ---
+++
@@ -1,18 +1,19 @@
from grum import app, db
from grum.models import User
-from flask import render_template, request
+from flask import render_template, request, redirect
-@app.route("/")
+@app.route("/", methods=['GET', 'POST'])
def main():
- # # Login verification code
- # username = request.for... |
89d13cdf811d7ab499303380b549fbc4c9877076 | confu/recipes/googlebenchmark.py | confu/recipes/googlebenchmark.py | #!/usr/bin/env python
def setup(root_dir):
import confu.git
repo = confu.git.clone("https://github.com/google/benchmark.git", root_dir)
from os import path
recipes_dir = path.dirname(path.abspath(__file__))
import shutil
shutil.copyfile(
path.join(recipes_dir, "googlebenchmark.yaml")... | #!/usr/bin/env python
def setup(root_dir):
import confu.git
repo = confu.git.clone("https://github.com/google/benchmark.git", root_dir)
from os import path
recipes_dir = path.dirname(path.abspath(__file__))
import shutil
shutil.copyfile(
path.join(recipes_dir, "googlebenchmark.yaml")... | Update recipe for Google Benchmark | Update recipe for Google Benchmark
| Python | mit | Maratyszcza/confu,Maratyszcza/confu | ---
+++
@@ -33,6 +33,7 @@
"json_reporter.cc",
"reporter.cc",
"sleep.cc",
+ "statistics.cc",
"string_util.cc",
"sysinfo.cc",
"timers.cc", |
252cfa3baa7973a923952ecb3c83cdfb9f28ab67 | l10n_br_account/models/fiscal_document.py | l10n_br_account/models/fiscal_document.py | # Copyright (C) 2009 - TODAY Renato Lima - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import api, models
class FiscalDocument(models.Model):
_inherit = 'l10n_br_fiscal.document'
@api.multi
def unlink(self):
invoices = self.env['account.invoice'].search(
... | # Copyright (C) 2009 - TODAY Renato Lima - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import _, api, models
from odoo.exceptions import UserError
from odoo.addons.l10n_br_fiscal.constants.fiscal import (
SITUACAO_EDOC_EM_DIGITACAO,
)
class FiscalDocument(models.Model):
... | Allow delete only fiscal documents with draft state | [REF] Allow delete only fiscal documents with draft state
| Python | agpl-3.0 | OCA/l10n-brazil,akretion/l10n-brazil,akretion/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil | ---
+++
@@ -1,7 +1,12 @@
# Copyright (C) 2009 - TODAY Renato Lima - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
-from odoo import api, models
+from odoo import _, api, models
+from odoo.exceptions import UserError
+
+from odoo.addons.l10n_br_fiscal.constants.fiscal import (
+ SITU... |
21f6d03449217952cb981719345eccfbb1ec84b3 | isogram/isogram.py | isogram/isogram.py | from string import ascii_lowercase
LOWERCASE = set(ascii_lowercase)
def is_isogram(s):
chars = [c for c in s.lower() if c in LOWERCASE]
return len(chars) == len(set(chars))
| from string import ascii_lowercase
LOWERCASE = set(ascii_lowercase)
def is_isogram(s):
chars = [c for c in s.lower() if c in LOWERCASE]
return len(chars) == len(set(chars))
# You could also achieve this using "c.isalpha()" instead of LOWERCASE
# You would then not need to import from `string`, but it's ma... | Add note about str.isalpha() method as an alternative | Add note about str.isalpha() method as an alternative
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -7,3 +7,7 @@
def is_isogram(s):
chars = [c for c in s.lower() if c in LOWERCASE]
return len(chars) == len(set(chars))
+
+
+# You could also achieve this using "c.isalpha()" instead of LOWERCASE
+# You would then not need to import from `string`, but it's marginally slower |
54a1f1774517faf377ae43f1bad4a4f5c0b0c562 | accelerator/tests/contexts/judging_round_context.py | accelerator/tests/contexts/judging_round_context.py | from accelerator.tests.factories import (
JudgingFormFactory,
JudgingFormElementFactory,
JudgingRoundFactory,
)
from accelerator_abstract.models import FORM_ELEM_OVERALL_RECOMMENDATION
class JudgingRoundContext:
def __init__(self, **kwargs):
if kwargs.get("is_active") is True:
shoul... | from accelerator.tests.factories import (
JudgingFormFactory,
JudgingFormElementFactory,
JudgingRoundFactory,
)
from accelerator_abstract.models import FORM_ELEM_OVERALL_RECOMMENDATION
class JudgingRoundContext:
def __init__(self, **kwargs):
if kwargs.get("is_active") is True:
shoul... | Add some values to the default judging_form_element | [AC-7310] Add some values to the default judging_form_element
| Python | mit | masschallenge/django-accelerator,masschallenge/django-accelerator | ---
+++
@@ -28,7 +28,9 @@
judging_form = JudgingFormFactory()
JudgingFormElementFactory(
element_name=FORM_ELEM_OVERALL_RECOMMENDATION,
- form_type=judging_form)
+ form_type=judging_form,
+ mandatory=True,
+ element_type="feedback")
r... |
dfeccf96499584d6b19c0734e6041e0d4b5947a1 | knowledge/admin.py | knowledge/admin.py |
from django.contrib import admin
from knowledge.models import Question, Response, Category
from portalpractices.models import Company, Author
class CategoryAdmin(admin.ModelAdmin):
list_display = [f.name for f in Category._meta.fields]
prepopulated_fields = {'slug': ('title', )}
admin.site.register(Category... |
from django.contrib import admin
from knowledge.models import Question, Response, Category
class CategoryAdmin(admin.ModelAdmin):
list_display = [f.name for f in Category._meta.fields]
prepopulated_fields = {'slug': ('title', )}
admin.site.register(Category, CategoryAdmin)
class QuestionAdmin(admin.ModelA... | Update to remove references to Portal Practices | Update to remove references to Portal Practices | Python | isc | CantemoInternal/django-knowledge,CantemoInternal/django-knowledge,CantemoInternal/django-knowledge | ---
+++
@@ -2,7 +2,6 @@
from django.contrib import admin
from knowledge.models import Question, Response, Category
-from portalpractices.models import Company, Author
class CategoryAdmin(admin.ModelAdmin):
@@ -17,18 +16,6 @@
raw_id_fields = ['user']
admin.site.register(Question, QuestionAdmin)
-class... |
a8bbe98f07e00cc6a9e9d076c6ed39c5d3136658 | aldryn_apphooks_config/models.py | aldryn_apphooks_config/models.py | # -*- coding: utf-8 -*-
from app_data import AppDataField
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class AppHookConfig(models.Model):
"""
This is the generic (abstract) model ... | # -*- coding: utf-8 -*-
from app_data import AppDataField
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class AppHookConfig(models.Model):
"""
This is the generic (abstract) model ... | Add shortcut to get configuration data | Add shortcut to get configuration data
| Python | bsd-3-clause | aldryn/aldryn-apphooks-config,aldryn/aldryn-apphooks-config,aldryn/aldryn-apphooks-config | ---
+++
@@ -33,3 +33,15 @@
return _(u'%s / %s') % (self.cmsapp.name, self.namespace)
else:
return _(u'%s / %s') % (self.type, self.namespace)
+
+ def __getattr__(self, item):
+ """
+ This allows to access config form attribute as normal model fields
+
+ :para... |
2f280e34762ad4910ff9e5041c2bf24f8283368c | src-backend/registration/tests/test_user.py | src-backend/registration/tests/test_user.py | from django.test import TestCase
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.authtoken.models import Token
class UserTest(TestCase):
def setUp(self):
self.test_user = User.objects.create_user('username', 'test@test.com', 'password')... | from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from nose.tools import assert_false
class UserTest(TestCase):
def setUp(self):
self.test_user = User.objects.create_user('username', 'test@test.com', 'password')
self.test... | Use nose test tools for the user test | Use nose test tools for the user test
| Python | bsd-3-clause | SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder | ---
+++
@@ -1,7 +1,7 @@
from django.test import TestCase
from django.contrib.auth.models import User
-from django.core.exceptions import ObjectDoesNotExist
from rest_framework.authtoken.models import Token
+from nose.tools import assert_false
class UserTest(TestCase):
@@ -10,8 +10,5 @@
self.test_user... |
40c9c762ce65e0e231a14745cdc274be6c927a74 | byceps/services/shop/storefront/models.py | byceps/services/shop/storefront/models.py | """
byceps.services.shop.storefront.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from ....database import db
from ....util.instances import ReprBuilder
from ..sequence.transfer.models import NumberSequenceID
from ..shop.... | """
byceps.services.shop.storefront.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from ....database import db
from ....util.instances import ReprBuilder
from ..sequence.transfer.models import NumberSequenceID
from ..shop.... | Add index for storefront's shop ID | Add index for storefront's shop ID
DDL:
CREATE INDEX ix_shop_storefronts_shop_id ON shop_storefronts (shop_id);
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps | ---
+++
@@ -24,7 +24,7 @@
__tablename__ = 'shop_storefronts'
id = db.Column(db.UnicodeText, primary_key=True)
- shop_id = db.Column(db.UnicodeText, db.ForeignKey('shops.id'), nullable=False)
+ shop_id = db.Column(db.UnicodeText, db.ForeignKey('shops.id'), index=True, nullable=False)
order_numbe... |
4e3773d96a47b88529a01fa4c4a0f25bf1b77b1c | lib/github_test.py | lib/github_test.py | import unittest
import github
class TestGithub(unittest.TestCase):
def setUp(self):
pass
def test_user(self):
u = github.user()
u1 = github.user()
self.assertTrue(u)
# make sure hash works
self.assertTrue(u is u1)
def test_has_issues(self):
... | import unittest
import github
class TestGithub(unittest.TestCase):
def setUp(self):
pass
def test_user(self):
u = github.user()
u1 = github.user()
self.assertTrue(u)
# make sure hash works
self.assertTrue(u is u1)
def test_has_issues(self):
... | Remove old repo_from_path tests. This is a very hard functionality to test | Remove old repo_from_path tests. This is a very hard functionality to
test
| Python | mit | jonmorehouse/vimhub | ---
+++
@@ -22,10 +22,5 @@
self.assertTrue(github.has_issues(("jonmorehouse/vim-github")))
self.assertFalse(github.has_issues(("jonmorehouse/github-issues.vim")))
- def test_repo_from_path(self):
-
- up = "/Users/MorehouseJ09/Desktop/github-issues.vim"
- self.assertTrue(github.rep... |
76282391f35725ee42ac0671a9a77b68e1f34081 | rest_tester/test_info.py | rest_tester/test_info.py | class TestInfo(object):
"""Read test information from JSON data."""
PATH_API = 'api'
PATH_API_URL = 'url'
PATH_API_PARAMS = 'params'
PATH_API_TIMEOUT = 'timeout'
PATH_TESTS = 'tests'
DEFAULT_TIME_OUT = 10
@classmethod
def read(cls, json_data):
"""Read test information fro... | class TestInfo(object):
"""Read test information from JSON data."""
PATH_API = 'api'
PATH_API_URL = 'url'
PATH_API_PARAMS = 'params'
PATH_API_TIMEOUT = 'timeout'
PATH_TESTS = 'tests'
DEFAULT_TIME_OUT = 10
@classmethod
def read(cls, json_data):
"""Read test information fro... | Use get for params and timeout. | Use get for params and timeout.
| Python | mit | ridibooks/lightweight-rest-tester,ridibooks/lightweight-rest-tester | ---
+++
@@ -13,11 +13,12 @@
@classmethod
def read(cls, json_data):
"""Read test information from JSON data."""
+ """Use get for only 'params' and 'timeout' to raise KeyError if keys do not exist."""
api_data = json_data[cls.PATH_API]
url = api_data[cls.PATH_API_URL]
- ... |
fecb9624379057a98aeaf2bb5cf42d7e526bbf0a | vumi/blinkenlights/heartbeat/__init__.py | vumi/blinkenlights/heartbeat/__init__.py |
from vumi.blinkenlights.heartbeat.publisher import (HeartBeatMessage,
HeartBeatPublisher)
__all__ = ["HeartBeatMessage", "HeartBeatPublisher"]
| """Vumi worker heartbeating."""
from vumi.blinkenlights.heartbeat.publisher import (HeartBeatMessage,
HeartBeatPublisher)
__all__ = ["HeartBeatMessage", "HeartBeatPublisher"]
| Add module docstring from vumi.blinkenlights.heartbeat. | Add module docstring from vumi.blinkenlights.heartbeat.
| Python | bsd-3-clause | vishwaprakashmishra/xmatrix,harrissoerja/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,harrissoerja/vumi,harrissoerja/vumi,TouK/vumi,TouK/vumi | ---
+++
@@ -1,3 +1,4 @@
+"""Vumi worker heartbeating."""
from vumi.blinkenlights.heartbeat.publisher import (HeartBeatMessage,
HeartBeatPublisher) |
fbf2a59d9cf25c3d3a041afa839d0d44f6f385a5 | win_unc/internal/utils.py | win_unc/internal/utils.py | """
Contains generic helper funcitons to aid in parsing.
"""
import itertools
def take_while(predicate, items):
return list(itertools.takewhile(predicate, items))
def drop_while(predicate, items):
return list(itertools.dropwhile(predicate, items))
def not_(func):
return lambda *args, **kwargs: not fu... | """
Contains generic helper funcitons to aid in parsing.
"""
import itertools
def take_while(predicate, items):
return list(itertools.takewhile(predicate, items))
def drop_while(predicate, items):
return list(itertools.dropwhile(predicate, items))
def not_(func):
return lambda *args, **kwargs: not fu... | Return None explicitly instead of implicitly | Return None explicitly instead of implicitly
| Python | mit | CovenantEyes/py_win_unc,nithinphilips/py_win_unc | ---
+++
@@ -37,3 +37,4 @@
func(*args, **kwargs)
except Exception as error:
return error
+ return None |
62a6b78b62631c0b1de7d0497250aa3d0310d47d | winthrop/common/models.py | winthrop/common/models.py | from django.db import models
# abstract models with common fields to be
# used as mix-ins
class Named(models.Model):
'''Abstract model with a 'name' field; by default, name is used as
the string display.'''
name = models.CharField(max_length=255, unique=True)
class Meta:
abstract = True
... | from django.db import models
# abstract models with common fields to be
# used as mix-ins
class Named(models.Model):
'''Abstract model with a 'name' field; by default, name is used as
the string display.'''
name = models.CharField(max_length=255, unique=True)
class Meta:
abstract = True
... | Add alpha ordering on Named abstract class | Add alpha ordering on Named abstract class
| Python | apache-2.0 | Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django | ---
+++
@@ -10,6 +10,7 @@
class Meta:
abstract = True
+ ordering = ['name']
def __str__(self):
return self.name
@@ -46,8 +47,3 @@
date_parts = [self.start_year, '-', self.end_year]
return ''.join([str(dp) for dp in date_parts if dp is not None])
-
-
-
-
- |
09506e7ae8dbc1ad06b35c075e15946dd2c6092b | examples/my_test_suite.py | examples/my_test_suite.py | from seleniumbase import BaseCase
class MyTestSuite(BaseCase):
def test_1(self):
self.open("http://xkcd.com/1663/")
for p in xrange(4):
self.click('a[rel="next"]')
self.find_text("Algorithms", "div#ctitle", timeout=3)
def test_2(self):
# This test will fail
... | from seleniumbase import BaseCase
class MyTestSuite(BaseCase):
def test_1(self):
self.open("http://xkcd.com/1663/")
self.find_text("Garden", "div#ctitle", timeout=3)
for p in xrange(4):
self.click('a[rel="next"]')
self.find_text("Algorithms", "div#ctitle", timeout=3)
... | Update the example test suite | Update the example test suite
| Python | mit | possoumous/Watchers,mdmintz/SeleniumBase,possoumous/Watchers,seleniumbase/SeleniumBase,mdmintz/seleniumspot,ktp420/SeleniumBase,mdmintz/seleniumspot,mdmintz/SeleniumBase,ktp420/SeleniumBase,ktp420/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,ktp420/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/Sele... | ---
+++
@@ -5,6 +5,7 @@
def test_1(self):
self.open("http://xkcd.com/1663/")
+ self.find_text("Garden", "div#ctitle", timeout=3)
for p in xrange(4):
self.click('a[rel="next"]')
self.find_text("Algorithms", "div#ctitle", timeout=3) |
5aca109f486786266164f4ac7a10e4d76f0730e4 | scrappyr/scraps/forms.py | scrappyr/scraps/forms.py | from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django import forms
from .models import Scrap
class ScrapForm(forms.ModelForm):
class Meta:
model = Scrap
fields = ['raw_title']
def __init__(self, *args, **kwargs):
super(ScrapForm, self).__init_... | from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django import forms
from .models import Scrap
class ScrapForm(forms.ModelForm):
class Meta:
model = Scrap
fields = ['raw_title']
def __init__(self, *args, **kwargs):
super(ScrapForm, self).__init_... | Make add-scrap title user friendly | Make add-scrap title user friendly
| Python | mit | tonysyu/scrappyr-app,tonysyu/scrappyr-app,tonysyu/scrappyr-app,tonysyu/scrappyr-app | ---
+++
@@ -13,6 +13,7 @@
def __init__(self, *args, **kwargs):
super(ScrapForm, self).__init__(*args, **kwargs)
+ self.fields['raw_title'].label = 'New scrap title'
self.helper = FormHelper()
self.helper.form_class = 'col-md-4'
self.helper.add_input(Submit('submit', '... |
bdb38a935dbbe6b70b0b960ba132dc6870455ceb | validate.py | validate.py | """Check for inconsistancies in the database."""
from server.db import (
BuildingBuilder, BuildingRecruit, BuildingType, load, UnitType
)
def main():
load()
for name in UnitType.resource_names():
if UnitType.count(getattr(UnitType, name) >= 1):
continue
else:
print... | """Check for inconsistancies in the database."""
from server.db import (
BuildingBuilder, BuildingRecruit, BuildingType, load, UnitType, setup,
options
)
def main():
load()
setup()
for name in UnitType.resource_names():
if UnitType.count(getattr(UnitType, name) >= 1):
continue... | Check that start building can recruit something. | Check that start building can recruit something.
| Python | mpl-2.0 | chrisnorman7/pyrts,chrisnorman7/pyrts,chrisnorman7/pyrts | ---
+++
@@ -1,12 +1,14 @@
"""Check for inconsistancies in the database."""
from server.db import (
- BuildingBuilder, BuildingRecruit, BuildingType, load, UnitType
+ BuildingBuilder, BuildingRecruit, BuildingType, load, UnitType, setup,
+ options
)
def main():
load()
+ setup()
for name... |
15efe5ecd3f17ec05f3dc9054cd823812c4b3743 | utils/http.py | utils/http.py | import requests
def retrieve_json(url):
r = requests.get(url)
r.raise_for_status()
return r.json()
| import requests
DEFAULT_TIMEOUT = 10
def retrieve_json(url, timeout=DEFAULT_TIMEOUT):
r = requests.get(url, timeout=timeout)
r.raise_for_status()
return r.json()
| Add a default timeout parameter to retrieve_json | Add a default timeout parameter to retrieve_json
| Python | bsd-3-clause | tebriel/dd-agent,jyogi/purvar-agent,pmav99/praktoras,gphat/dd-agent,manolama/dd-agent,pmav99/praktoras,gphat/dd-agent,Wattpad/dd-agent,brettlangdon/dd-agent,cberry777/dd-agent,pmav99/praktoras,brettlangdon/dd-agent,tebriel/dd-agent,tebriel/dd-agent,Wattpad/dd-agent,jyogi/purvar-agent,cberry777/dd-agent,manolama/dd-agen... | ---
+++
@@ -1,6 +1,10 @@
import requests
-def retrieve_json(url):
- r = requests.get(url)
+
+DEFAULT_TIMEOUT = 10
+
+
+def retrieve_json(url, timeout=DEFAULT_TIMEOUT):
+ r = requests.get(url, timeout=timeout)
r.raise_for_status()
return r.json() |
fe89b50d87c37c83170de74e5f88f59d88ba2c89 | vispy/visuals/tests/test_arrows.py | vispy/visuals/tests/test_arrows.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
import numpy as np
from vispy.visuals.line.arrow import ARROW_TYPES
from vispy.scene import visuals, transforms
from vispy.testing import (requires_application, TestingCanvas... | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
import numpy as np
from vispy.visuals.line.arrow import ARROW_TYPES
from vispy.scene import visuals, transforms
from vispy.testing import (requires_application, TestingCanvas... | Add 0.33 to the vertices to prevent misalignment | Add 0.33 to the vertices to prevent misalignment
| Python | bsd-3-clause | michaelaye/vispy,ghisvail/vispy,QuLogic/vispy,jdreaver/vispy,Eric89GXL/vispy,srinathv/vispy,dchilds7/Deysha-Star-Formation,jay3sh/vispy,sbtlaarzc/vispy,jay3sh/vispy,julienr/vispy,sbtlaarzc/vispy,michaelaye/vispy,jay3sh/vispy,bollu/vispy,drufat/vispy,RebeccaWPerry/vispy,julienr/vispy,Eric89GXL/vispy,bollu/vispy,jdreaver... | ---
+++
@@ -23,6 +23,8 @@
[75, 75]
]).astype('f32')
+ vertices += 0.33
+
arrows = np.array([
vertices[:2],
vertices[3:1:-1], |
a75ca43b3035f3f391b39393802ea46d440b22c5 | bookvoyage-backend/core/admin.py | bookvoyage-backend/core/admin.py | from leaflet.admin import LeafletGeoAdmin
from django.contrib import admin
from import_export import resources
from import_export.admin import ImportExportModelAdmin
# Register your models here.
from .models import Author, Book, BookInstance, BookHolding, BookOwning, BookBatch
class BookResource(resources.ModelResour... | from leaflet.admin import LeafletGeoAdmin
from django.contrib import admin
from import_export import resources
from import_export.admin import ImportExportModelAdmin
# Register models
from .models import Author, Book, BookInstance, BookHolding, BookOwning, BookBatch
from django.contrib.auth.models import User
class B... | Add option to bulk-add users | Add option to bulk-add users
Warning: excel import is shaky with importing groups; json import is recommended. | Python | mit | edushifts/book-voyage,edushifts/book-voyage,edushifts/book-voyage,edushifts/book-voyage | ---
+++
@@ -3,8 +3,9 @@
from import_export import resources
from import_export.admin import ImportExportModelAdmin
-# Register your models here.
+# Register models
from .models import Author, Book, BookInstance, BookHolding, BookOwning, BookBatch
+from django.contrib.auth.models import User
class BookResource... |
3e1f8a567e9d7fa7bb7ac5acf8fe336b88faeeaa | expressions/python/setup.py | expressions/python/setup.py | from setuptools import setup, find_packages
def _is_requirement(line):
"""Returns whether the line is a valid package requirement."""
line = line.strip()
return line and not (line.startswith("-r") or line.startswith("#"))
def _read_requirements(filename):
"""Returns a list of package requirements re... | from setuptools import setup, find_packages
def _is_requirement(line):
"""Returns whether the line is a valid package requirement."""
line = line.strip()
return line and not (line.startswith("-r") or line.startswith("#"))
def _read_requirements(filename):
"""Returns a list of package requirements re... | Declare package_data to ensure month.aliases is included | Declare package_data to ensure month.aliases is included
| Python | bsd-3-clause | rapidpro/flows | ---
+++
@@ -38,6 +38,7 @@
keywords='rapidpro templating',
packages=find_packages(),
+ package_data={'expressions': ['month.aliases']},
install_requires=required_packages,
test_suite='nose.collector', |
a8b0a1f20264506beec9ffc1299b82277a339556 | chipy_org/apps/profiles/views.py | chipy_org/apps/profiles/views.py | from django.contrib.auth.models import User
from django.views.generic import ListView, UpdateView
from .forms import ProfileForm
from .models import UserProfile
class ProfilesList(ListView):
context_object_name = "profiles"
template_name = "profiles/list.html"
queryset = User.objects.filter(profile__show... | from django.contrib.auth.models import User
from django.views.generic import ListView, UpdateView
from .forms import ProfileForm
from .models import UserProfile
class ProfilesList(ListView):
context_object_name = "profiles"
template_name = "profiles/list.html"
queryset = User.objects.filter(profile__show... | Add ordering for profiles by name | Add ordering for profiles by name
| Python | mit | chicagopython/chipy.org,chicagopython/chipy.org,chicagopython/chipy.org,chicagopython/chipy.org | ---
+++
@@ -15,6 +15,7 @@
context_object_name = "organizers"
template_name = "profiles/organizers.html"
queryset = UserProfile.user_organizers()
+ ordering = ["profile__display_name"]
class ProfileEdit(UpdateView): |
fbe4761d2d679a983d2625c4969dab53500634b7 | fases/rodar_fase_exemplo.py | fases/rodar_fase_exemplo.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from atores import PassaroAmarelo, PassaroVermelho, Obstaculo, Porco
from fase import Fase
from placa_grafica_tkinter import rodar_fase
if __name__=='__main__':
fase = Fase(intervalo_de_colisao=10)
# Adicionar Pássaros Vermelhos
for i in ra... | # -*- coding: utf-8 -*-
from os import path
import sys
project_dir = path.dirname(__file__)
project_dir = path.join('..')
sys.path.append(project_dir)
from atores import PassaroAmarelo, PassaroVermelho, Obstaculo, Porco
from fase import Fase
from placa_grafica_tkinter import rodar_fase
if __name__ == '__main__':
... | Refactor para funfar via linha de comando | Refactor para funfar via linha de comando
| Python | mit | guoliveer/pythonbirds,deniscampos/pythonbirds,renzon/pythonbirds-fatec,giovaneliberato/python_birds_fp,pythonprobr/pythonbirds,jvitorlb/pythonbirds,evertongoncalves/pythonbirds,renzon/python-birds-t5,Cleitoon1/pythonbirds,gomesfelipe/pythonbirds,igorlimasan/pythonbirds | ---
+++
@@ -1,11 +1,16 @@
# -*- coding: utf-8 -*-
+from os import path
+import sys
-from __future__ import unicode_literals
+project_dir = path.dirname(__file__)
+project_dir = path.join('..')
+sys.path.append(project_dir)
+
from atores import PassaroAmarelo, PassaroVermelho, Obstaculo, Porco
from fase import Fa... |
a0df14a38bcc4f71cf073298e078160488b143ca | sheldon/basic_classes.py | sheldon/basic_classes.py | # -*- coding: utf-8 -*-
"""
Declaration of classes needed for bot working:
Adapter class, Plugin class
@author: Lises team
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from time import sleep
class Adapter:
"""
Adapter class contains information about adapter:
name, ... | # -*- coding: utf-8 -*-
"""
Declaration of classes needed for bot working:
Adapter class, Plugin class
@author: Lises team
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from time import sleep
class Adapter:
"""
Adapter class contains information about adapter:
name, ... | Change docs of send_message method | Change docs of send_message method
| Python | mit | lises/sheldon | ---
+++
@@ -52,8 +52,8 @@
"""
Send message with adapter
- :param message: Message object or string with message text
- :return:
+ :param message: Message object
+ :return: True or False - result of sending
"""
pass
|
07ccbc36fd5148db2efc5f676fd13d4b24aa004f | hackasmlexer/hacklexer.py | hackasmlexer/hacklexer.py | import re
from pygments.lexer import RegexLexer, include
from pygments.token import *
class HackAsmLexer(RegexLexer):
name = 'Hack Assembler'
aliases = ['hack_asm']
filenames = ['*.asm']
identifier = r'[a-zA-Z$._?][a-zA-Z0-9$._?]*'
flags = re.IGNORECASE | re.MULTILINE
tokens = {
'root... | import re
from pygments.lexer import RegexLexer, include
from pygments.token import *
class HackAsmLexer(RegexLexer):
name = 'Hack Assembler'
aliases = ['hack_asm']
filenames = ['*.asm']
identifier = r'[a-zA-Z$._?][a-zA-Z0-9$._?]*'
flags = re.IGNORECASE | re.MULTILINE
tokens = {
'root... | Add register and IO addresses | Add register and IO addresses
| Python | mit | cprieto/pygments_hack_asm | ---
+++
@@ -19,6 +19,9 @@
(r'[\r\n]+', Text),
(r'@[A-Za-z][A-Za-z0-9]+', Name.Variable),
(r'\b(JGT|JEQ|JGE|JLT|JNE|JLE|JMP)\b', Keyword),
+ (r'\b@(SCREEN|KBD)\b', Name.Builtin.Pseudo), # I/O addresses
+ (r'\b@(R0|R1|R2|R3|R4|R5|R6|R7|R8|R9|R10|R11|R12|R13|R... |
6b07710ae8c7681f58060c15c74bf5bd3dda4f3b | handroll/composers/txt.py | handroll/composers/txt.py | # Copyright (c) 2014, Matt Layman
import textile
from handroll import logger
from handroll.composers import GenericHTMLComposer
class TextileComposer(GenericHTMLComposer):
"""Compose HTML from Textile files (``.textile``).
The first line of the file will be used as the ``title`` data for the
template. ... | # Copyright (c) 2014, Matt Layman
import sys
try:
import textile
except ImportError:
# FIXME: textile not supported on Python 3.
pass
from handroll import logger
from handroll.composers import GenericHTMLComposer
class TextileComposer(GenericHTMLComposer):
"""Compose HTML from Textile files (``.tex... | Revert "Textile is working with Python 3 now." | Revert "Textile is working with Python 3 now."
This reverts commit 849316dd5bffa9132608cc9eeac63b08188f31c0.
Textile is still having issues with Python 3.2 so rollback the support until it
is fixed.
| Python | bsd-2-clause | handroll/handroll | ---
+++
@@ -1,6 +1,12 @@
# Copyright (c) 2014, Matt Layman
-import textile
+import sys
+
+try:
+ import textile
+except ImportError:
+ # FIXME: textile not supported on Python 3.
+ pass
from handroll import logger
from handroll.composers import GenericHTMLComposer
@@ -14,5 +20,13 @@
template as t... |
ff89cb8216168beb9c79028080fbccbe91c13000 | masters/master.chromium.infra/master_site_config.py | masters/master.chromium.infra/master_site_config.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class Infra(Master.Master1):
project_name = 'Infra'
master_port_id= 1
buildbot_url... | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class Infra(Master.Master1):
project_name = 'Infra'
master_port_id = 11
buildbot_u... | Use 11 as master_port_id for labs convenience. | Use 11 as master_port_id for labs convenience.
R=phajdan.jr@chromium.org
BUG=449961
Review URL: https://codereview.chromium.org/935813002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@294106 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build | ---
+++
@@ -8,6 +8,6 @@
class Infra(Master.Master1):
project_name = 'Infra'
- master_port_id= 1
+ master_port_id = 11
buildbot_url = 'https://build.chromium.org/p/chromium.infra/'
service_account_file = 'service-account-infra.json' |
20224987f7c1ac34b13587a6dc7c1241e0466663 | dataset/dataset/spiders/dataset_spider.py | dataset/dataset/spiders/dataset_spider.py | from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from dataset import DatasetItem
class DatasetSpider(CrawlSpider):
name = 'dataset'
allowed_domains = ['data.gc.ca/data/en']
start_urls = ['http://data.... | from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from .. import items
class DatasetSpider(CrawlSpider):
name = 'dataset'
allowed_domains = ['data.gc.ca/data/en']
start_urls = ['http://data.gc.ca/data/... | Fix import post merge to project directory | Fix import post merge to project directory
| Python | mit | MaxLikelihood/CODE | ---
+++
@@ -1,7 +1,7 @@
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
-from dataset import DatasetItem
+from .. import items
class DatasetSpider(CrawlSpider):
@@ -13,7 +13,7 @@
def parse_dataset... |
6c0287a3ba1c98d9f4879c4f2ec95a3d6406b6ae | meinberlin/apps/dashboard/filtersets.py | meinberlin/apps/dashboard/filtersets.py | import django_filters
from django.utils.translation import ugettext_lazy as _
from adhocracy4.filters import widgets as filters_widgets
from adhocracy4.filters.filters import DefaultsFilterSet
from adhocracy4.filters.filters import FreeTextFilter
from adhocracy4.projects.models import Project
from meinberlin.apps.proj... | import django_filters
from django.utils.translation import ugettext_lazy as _
from adhocracy4.filters import widgets as filters_widgets
from adhocracy4.filters.filters import DefaultsFilterSet
from adhocracy4.filters.filters import FreeTextFilter
from adhocracy4.projects.models import Project
from meinberlin.apps.proj... | Remove typ filter from dashboard | Remove typ filter from dashboard
| Python | agpl-3.0 | liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin | ---
+++
@@ -41,10 +41,6 @@
widget=views.YearWidget,
)
- typ = django_filters.CharFilter(
- widget=views.TypeWidget,
- )
-
class Meta:
model = Project
- fields = ['search', 'is_archived', 'created', 'typ']
+ fields = ['search', 'is_archived', 'created'] |
8f6a19bade1a0591f3feba4521fdf42c157c179d | skyline_path/algorithms/growing_graph.py | skyline_path/algorithms/growing_graph.py | class GrowingGraph:
def __init__(self, neighbors_table, start_nodes):
self.neighbors_table = neighbors_table
self.outer_nodes = set(start_nodes)
self.inner_nodes = set()
def growing(self):
for old_node in self.outer_nodes.copy():
self._update_nodes(old_node)
def... | class GrowingGraph:
def __init__(self, neighbors_table, start_nodes):
self.neighbors_table = neighbors_table
self.outer_nodes = set(start_nodes)
self.inner_nodes = set()
def all_nodes(self):
return self.outer_nodes | self.inner_nodes
def growing(self, times=1):
for ... | Add all_nodes and growing times param | Add all_nodes and growing times param
| Python | mit | shadow3x3x3/renew-skyline-path-query | ---
+++
@@ -4,9 +4,13 @@
self.outer_nodes = set(start_nodes)
self.inner_nodes = set()
- def growing(self):
- for old_node in self.outer_nodes.copy():
- self._update_nodes(old_node)
+ def all_nodes(self):
+ return self.outer_nodes | self.inner_nodes
+
+ def growing... |
776814f7c5ef5b54167adbe3cce29b8e8381fd69 | scripts/cluster/craq/start_craq_server.py | scripts/cluster/craq/start_craq_server.py | #!/usr/bin/python
import sys
import subprocess
import time
import socket
def main():
if (not socket.gethostname() in ['meru28', 'meru29', 'meru30']):
return 0
subprocess.Popen('/home/meru/bmistree/new-craq-dist/craq-32 -d meru -p 10333 -z 192.168.1.7:9888', shell=True)
return 0
i... | #!/usr/bin/python
import sys
import subprocess
import time
import socket
def main():
if (not socket.gethostname() in ['meru27', 'meru29', 'meru30']):
return 0
subprocess.Popen('/home/meru/bmistree/new-craq-dist/craq-32 -d meru -p 10333 -z 192.168.1.7:9888', shell=True)
return 0
i... | Use servers for craq that are actually alive. | Use servers for craq that are actually alive.
| Python | bsd-3-clause | sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata | ---
+++
@@ -6,7 +6,7 @@
import socket
def main():
- if (not socket.gethostname() in ['meru28', 'meru29', 'meru30']):
+ if (not socket.gethostname() in ['meru27', 'meru29', 'meru30']):
return 0
subprocess.Popen('/home/meru/bmistree/new-craq-dist/craq-32 -d meru -p 10333 -z 192... |
2aab3167f70fa736fafb3507e71a6233a02363eb | space-age/space_age.py | space-age/space_age.py | class SpaceAge(object):
def __init__(self, seconds):
self.seconds = seconds
@property
def years(self):
return self.seconds/31557600
def on_earth(self):
return round(self.years, 2)
def on_mercury(self):
return round(self.years/0.2408467, 2)
def on_venus(self):
... | class SpaceAge(object):
YEARS = {"on_earth": 1,
"on_mercury": 0.2408467,
"on_venus": 0.61519726,
"on_mars": 1.8808158,
"on_jupiter": 11.862615,
"on_saturn": 29.447498,
"on_uranus": 84.016846,
"on_neptune": 164.79132}
def... | Implement __getattr__ to reduce code | Implement __getattr__ to reduce code
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -1,4 +1,13 @@
class SpaceAge(object):
+ YEARS = {"on_earth": 1,
+ "on_mercury": 0.2408467,
+ "on_venus": 0.61519726,
+ "on_mars": 1.8808158,
+ "on_jupiter": 11.862615,
+ "on_saturn": 29.447498,
+ "on_uranus": 84.016846,
+ ... |
47c50f9e3f8c0643e0e76cd60fa5694701e73afe | scanner/ScannerApplication.py | scanner/ScannerApplication.py | from Cura.Application import Application
class ScannerApplication(Application):
def __init__(self):
super(ScannerApplication, self).__init__()
self._plugin_registry.loadPlugin("STLReader")
self._plugin_registry.loadPlugin("STLWriter")
self._plugin_registry.loadPlugin("MeshV... | from Cura.WxApplication import WxApplication
class ScannerApplication(WxApplication):
def __init__(self):
super(ScannerApplication, self).__init__()
self._plugin_registry.loadPlugin("STLReader")
self._plugin_registry.loadPlugin("STLWriter")
self._plugin_registry.loadPlugin(... | Use WxApplication as base class for the scanner | Use WxApplication as base class for the scanner
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | ---
+++
@@ -1,6 +1,6 @@
-from Cura.Application import Application
+from Cura.WxApplication import WxApplication
-class ScannerApplication(Application):
+class ScannerApplication(WxApplication):
def __init__(self):
super(ScannerApplication, self).__init__()
@@ -11,3 +11,4 @@
de... |
e3804c302df761a4ebf7f2c7ed3e3c0bc8d079e7 | grader/grader/__init__.py | grader/grader/__init__.py | import argparse
import importlib
import logging
import os
logger = logging.getLogger(__name__)
description = "An automated grading tool for programming assignments."
subcommands = {
"init": "grader.init",
"new": "grader.new",
"image": "grader.image",
"grade": "grader.grade"
}
def run():
# Confi... | import argparse
import importlib
import logging
import os
logger = logging.getLogger(__name__)
description = "An automated grading tool for programming assignments."
subcommands = {
"init": "grader.init",
"new": "grader.new",
"image": "grader.image",
"grade": "grader.grade"
}
def run():
"""Scri... | Add a todo item to run() | Add a todo item to run()
| Python | mit | redkyn/grader,grade-it/grader,redkyn/grader | ---
+++
@@ -16,6 +16,12 @@
def run():
+ """Script entry point
+
+ .. todo::
+
+ Add a "verbose" flag
+ """
# Configure logging
logging.basicConfig(level=logging.INFO)
|
6bef0dc50470bc71c15e0fb7c86f03e69c416e67 | scrapi/harvesters/datacite.py | scrapi/harvesters/datacite.py | '''
Harvester for the DataCite MDS for the SHARE project
Example API call: http://oai.datacite.org/oai?verb=ListRecords&metadataPrefix=oai_dc
'''
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
from scrapi.base.helpers import updated_schema, oai_extract_dois
class DataciteHarvester(OAIH... | '''
Harvester for the DataCite MDS for the SHARE project
Example API call: http://oai.datacite.org/oai?verb=ListRecords&metadataPrefix=oai_dc
'''
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
from scrapi.base.helpers import updated_schema, oai_extract_dois
class DataciteHarvester(OAIH... | Add docstring explaiing why to take the second description | Add docstring explaiing why to take the second description
| Python | apache-2.0 | CenterForOpenScience/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi,ostwald/scrapi,erinspace/scrapi,mehanig/scrapi,felliott/scrapi,fabianvf/scrapi,erinspace/scrapi,alexgarciac/scrapi,felliott/scrapi,mehanig/scrapi,jeffreyliu3230/scrapi | ---
+++
@@ -30,6 +30,10 @@
def get_second_description(descriptions):
+ ''' In the DataCite OAI PMH api, there are often 2 descriptions: A type and
+ a longer kind of abstract. If there are two options, pick the second one which
+ is almost always the longer abstract
+ '''
if descriptions:
... |
40af3e546a9024f7bb7786828d22534f8dff103a | neutron_fwaas/common/fwaas_constants.py | neutron_fwaas/common/fwaas_constants.py | # Copyright 2015 Cisco Systems, Inc
# 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 requir... | # Copyright 2015 Cisco Systems, Inc
# 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 requir... | Remove unused constant for topics | Remove unused constant for topics
While reading the code, I found "L3_AGENT" topic is defined
but never be used.
Change-Id: I9b6da61f9fe5224d2c25bbe7cc55fd508b4e240f
| Python | apache-2.0 | openstack/neutron-fwaas,openstack/neutron-fwaas | ---
+++
@@ -18,6 +18,5 @@
# Constants for "topics"
FIREWALL_PLUGIN = 'q-firewall-plugin'
-L3_AGENT = 'l3_agent'
FW_AGENT = 'firewall_agent'
FIREWALL_RULE_LIST = 'firewall_rule_list' |
5055e01bb7ea340ef96204a360002907c43fac91 | tsserver/models.py | tsserver/models.py | from tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
timestamp = db.Column(db.DateTime, primary_key=True)
temperature = db.Column(db.Float)
"""Tempe... | from tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
timestamp = db.Column(db.DateTime, primary_key=True)
temperature = db.Column(db.Float)
"""Tempe... | Remove Telemetry.__init__ as not necessary | Remove Telemetry.__init__ as not necessary
| Python | mit | m4tx/techswarm-server | ---
+++
@@ -14,11 +14,6 @@
pressure = db.Column(db.Float)
"""Air pressure in hPa."""
- def __init__(self, timestamp, temperature, pressure):
- self.timestamp = timestamp
- self.temperature = temperature
- self.pressure = pressure
-
def as_dict(self):
return {'timestam... |
9f42cd231375475d27c6fe298ec862065c34f8ca | armstrong/core/arm_sections/views.py | armstrong/core/arm_sections/views.py | from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.views.generic import TemplateView
from django.utils.translation import ugettext as _
from django.contrib.syndication.views import Feed
from django.shortcuts import get_object_or_404
from .models import Sect... | from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.views.generic import DetailView
from django.utils.translation import ugettext as _
from django.contrib.syndication.views import Feed
from django.shortcuts import get_object_or_404
from .models import Sectio... | Refactor SimpleSectionView to inherit DetailView | Refactor SimpleSectionView to inherit DetailView | Python | apache-2.0 | armstrong/armstrong.core.arm_sections,texastribune/armstrong.core.tt_sections,armstrong/armstrong.core.arm_sections,texastribune/armstrong.core.tt_sections,texastribune/armstrong.core.tt_sections | ---
+++
@@ -1,6 +1,6 @@
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
-from django.views.generic import TemplateView
+from django.views.generic import DetailView
from django.utils.translation import ugettext as _
from django.contrib.syndication.views import F... |
2ca5ccb861962a021f81b6e794f5372d8079216f | fml/generatechangedfilelist.py | fml/generatechangedfilelist.py | import sys
import os
import commands
import fnmatch
import re
import subprocess, shlex
def cmdsplit(args):
if os.sep == '\\':
args = args.replace('\\', '\\\\')
return shlex.split(args)
def main():
md5dir = os.path.abspath(sys.argv[1])
list_file = os.path.abspath(sys.argv[2])
prelist = os.p... | import sys
import os
import commands
import fnmatch
import re
import subprocess, shlex
mcp_root = os.path.abspath(sys.argv[1])
sys.path.append(os.path.join(mcp_root,"runtime"))
from filehandling.srgshandler import parse_srg
def cmdsplit(args):
if os.sep == '\\':
args = args.replace('\\', '\\\\')
retur... | Tweak file list script to print obf names | Tweak file list script to print obf names
| Python | lgpl-2.1 | Zaggy1024/MinecraftForge,luacs1998/MinecraftForge,simon816/MinecraftForge,karlthepagan/MinecraftForge,jdpadrnos/MinecraftForge,bonii-xx/MinecraftForge,mickkay/MinecraftForge,dmf444/MinecraftForge,Theerapak/MinecraftForge,ThiagoGarciaAlves/MinecraftForge,blay09/MinecraftForge,shadekiller666/MinecraftForge,Mathe172/Minec... | ---
+++
@@ -5,21 +5,33 @@
import re
import subprocess, shlex
+mcp_root = os.path.abspath(sys.argv[1])
+sys.path.append(os.path.join(mcp_root,"runtime"))
+from filehandling.srgshandler import parse_srg
+
def cmdsplit(args):
if os.sep == '\\':
args = args.replace('\\', '\\\\')
return shlex.split... |
18332cdac7c7dcb2ef64e3a9ad17b8b229387af8 | spraakbanken/s5/spr_local/reconstruct_corpus.py | spraakbanken/s5/spr_local/reconstruct_corpus.py | #!/usr/bin/env python3
import argparse
import collections
import random
import sys
def reconstruct(f_in, f_out):
sentence_starts = []
contexts = {}
for line in f_in:
parts = line.split()
words = parts[:-1]
count = int(parts[-1])
if words[0] == "<s>" and words[-1] == "<... | #!/usr/bin/env python3
from __future__ import print_function
import argparse
import collections
import random
import sys
def reconstruct(f_in, f_out):
sentence_starts = []
contexts = {}
for line in f_in:
parts = line.split()
words = parts[:-1]
count = int(parts[-1])
i... | Add reconstruct corpus as a test | Add reconstruct corpus as a test
| Python | apache-2.0 | psmit/kaldi-recipes,phsmit/kaldi-recipes,psmit/kaldi-recipes,psmit/kaldi-recipes,phsmit/kaldi-recipes | ---
+++
@@ -1,4 +1,6 @@
#!/usr/bin/env python3
+
+from __future__ import print_function
import argparse
import collections |
1301f5c5d5b9087ec32e3cf78f93ab9a4e708426 | geokey_dataimports/__init__.py | geokey_dataimports/__init__.py | """Main initialisation for extension."""
VERSION = (0, 4, 1)
__version__ = '.'.join(map(str, VERSION))
try:
from geokey.extensions.base import register
register(
'geokey_dataimports',
'Data Imports',
display_admin=True,
superuser=False,
version=__version__
)
excep... | """Main initialisation for extension."""
VERSION = (0, 5, 0)
__version__ = '.'.join(map(str, VERSION))
try:
from geokey.extensions.base import register
register(
'geokey_dataimports',
'Data Imports',
display_admin=True,
superuser=False,
version=__version__
)
excep... | Increment minor version number ahead of release | Increment minor version number ahead of release | Python | mit | ExCiteS/geokey-dataimports,ExCiteS/geokey-dataimports,ExCiteS/geokey-dataimports | ---
+++
@@ -1,6 +1,6 @@
"""Main initialisation for extension."""
-VERSION = (0, 4, 1)
+VERSION = (0, 5, 0)
__version__ = '.'.join(map(str, VERSION))
|
29c5391078aaa9e3c18356a18ca1c5d6f3bf82e9 | src/temp_functions.py | src/temp_functions.py | def k_to_c(temp):
return temp - 273.15
def f_to_k(temp):
return ((temp - 32) * (5 / 9)) + 273.15
| def k_to_c(temp):
return temp - 273.15
def f_to_k(temp):
return ((temp - 32) * (5 / 9)) + 273.15
def f_to_c(temp):
temp_k = f_to_k(temp)
result = k_to_c(temp_k)
return result
| Write a function covert far to cesis | Write a function covert far to cesis
| Python | mit | xykang/2015-05-12-BUSM-git,xykang/2015-05-12-BUSM-git | ---
+++
@@ -3,3 +3,8 @@
def f_to_k(temp):
return ((temp - 32) * (5 / 9)) + 273.15
+
+def f_to_c(temp):
+ temp_k = f_to_k(temp)
+ result = k_to_c(temp_k)
+ return result |
5b6f4f51eb761b87881d99148e7dae013af09eb6 | zgres/utils.py | zgres/utils.py | import sys
import time
import asyncio
import logging
def pg_lsn_to_int(pos):
# http://www.postgresql.org/docs/9.4/static/datatype-pg-lsn.html
# see http://eulerto.blogspot.com.es/2011/11/understanding-wal-nomenclature.html
logfile, offset = pos.split('/')
return 0xFF000000 * int(logfile, 16) + int(offs... | import sys
import time
import asyncio
import logging
def pg_lsn_to_int(pos):
# http://www.postgresql.org/docs/9.4/static/datatype-pg-lsn.html
# see http://eulerto.blogspot.com.es/2011/11/understanding-wal-nomenclature.html
logfile, offset = pos.split('/')
return 0xFF000000 * int(logfile, 16) + int(offs... | Remove sleep time as it appeared to hang forever | Remove sleep time as it appeared to hang forever
| Python | mit | jinty/zgres,jinty/zgres | ---
+++
@@ -10,14 +10,9 @@
return 0xFF000000 * int(logfile, 16) + int(offset, 16)
def exception_handler(loop, context):
- sleep_time = 10
- try:
- loop.default_exception_handler(context)
- logging.error('Unexpected exception, exiting...')
- # TODO: can we do some kind of backoff?
- ... |
06c3f0c5d4764b745d87bb814cbd87213bb7f747 | infrastructure/aws/attach-index-volume.py | infrastructure/aws/attach-index-volume.py | # Creates an EBS volume for the index and attaches it to a given instance as /dev/xvdf.
# Prints the volume ID on stdout.
# Usage: attach-index-volume.py <channel> <instance-id>
import sys
import boto3
import awslib
from datetime import datetime
channel = sys.argv[1]
instanceId = sys.argv[2]
ec2 = boto3.resource('ec... | # Creates an EBS volume for the index and attaches it to a given instance as /dev/xvdf.
# Prints the volume ID on stdout.
# Usage: attach-index-volume.py <channel> <instance-id>
import sys
import boto3
import awslib
from datetime import datetime
channel = sys.argv[1]
instanceId = sys.argv[2]
ec2 = boto3.resource('ec... | Use a bigger volume so it doesn't fill up | Use a bigger volume so it doesn't fill up
| Python | mpl-2.0 | bill-mccloskey/searchfox,bill-mccloskey/searchfox,bill-mccloskey/searchfox,bill-mccloskey/searchfox,bill-mccloskey/searchfox,bill-mccloskey/searchfox | ---
+++
@@ -18,7 +18,7 @@
instance = list(instances)[0]
r = client.create_volume(
- Size=100,
+ Size=200,
VolumeType='gp2',
AvailabilityZone=instance.placement['AvailabilityZone'],
) |
f284a1487551850c23d251a1d501e88025261369 | readthedocs/rtd_tests/tests/test_hacks.py | readthedocs/rtd_tests/tests/test_hacks.py | from django.test import TestCase
from core import hacks
class TestHacks(TestCase):
fixtures = ['eric.json', 'test_data.json']
def setUp(self):
hacks.patch_meta_path()
def tearDown(self):
hacks.unpatch_meta_path()
def test_hack_failed_import(self):
import boogy
self.as... | from django.test import TestCase
from core import hacks
class TestHacks(TestCase):
fixtures = ['eric.json', 'test_data.json']
def setUp(self):
hacks.patch_meta_path()
def tearDown(self):
hacks.unpatch_meta_path()
def test_hack_failed_import(self):
import boogy
self.as... | Comment out known failing test for now (code not in prod). | Comment out known failing test for now (code not in prod).
| Python | mit | atsuyim/readthedocs.org,Tazer/readthedocs.org,espdev/readthedocs.org,VishvajitP/readthedocs.org,kdkeyser/readthedocs.org,nyergler/pythonslides,kenshinthebattosai/readthedocs.org,clarkperkins/readthedocs.org,VishvajitP/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,mrshoki/readthedocs.org,asampat3090/readthed... | ---
+++
@@ -14,6 +14,6 @@
import boogy
self.assertTrue(str(boogy), "<Silly Human, I'm not real>")
- def test_hack_correct_import(self):
- import itertools
- self.assertFalse(str(itertools), "<Silly Human, I'm not real>")
+ #def test_hack_correct_import(self):
+ #import i... |
475d39b9af464649dbab27349180b286f0042fa8 | dthm4kaiako/utils/get_upload_filepath.py | dthm4kaiako/utils/get_upload_filepath.py | """Helper functions for determining file paths for uploads."""
from os.path import join
from datetime import datetime
from pytz import timezone
# This is duplicated here to avoid circular dependency with settings file
TIME_ZONE = 'NZ'
def get_upload_path_for_date(category):
"""Create upload path for file by dat... | """Helper functions for determining file paths for uploads."""
from os.path import join
from datetime import datetime
from pytz import timezone
# This is duplicated here to avoid circular dependency with settings file
TIME_ZONE = 'NZ'
def get_upload_path_for_date(category):
"""Create upload path for file by dat... | Fix typo in resource media path | Fix typo in resource media path
| Python | mit | uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers | ---
+++
@@ -32,4 +32,4 @@
Returns:
String of path and filename for upload.
"""
- return join('resources`', str(component.resource.pk), filename)
+ return join('resources', str(component.resource.pk), filename) |
02420b89671cf7a90c357efe24997d3142353a18 | bokeh/command/tests/test_bootstrap.py | bokeh/command/tests/test_bootstrap.py | import pytest
from bokeh.command.bootstrap import main
def test_no_subcommand(capsys):
with pytest.raises(SystemExit):
main(["bokeh"])
out, err = capsys.readouterr()
assert err == "ERROR: Must specify subcommand, one of: html, json or serve\n"
assert out == ""
| Test running `bokeh` with no subcommand | Test running `bokeh` with no subcommand
| Python | bsd-3-clause | dennisobrien/bokeh,clairetang6/bokeh,azjps/bokeh,KasperPRasmussen/bokeh,msarahan/bokeh,draperjames/bokeh,stonebig/bokeh,phobson/bokeh,dennisobrien/bokeh,ptitjano/bokeh,draperjames/bokeh,KasperPRasmussen/bokeh,ptitjano/bokeh,Karel-van-de-Plassche/bokeh,percyfal/bokeh,Karel-van-de-Plassche/bokeh,schoolie/bokeh,percyfal/b... | ---
+++
@@ -0,0 +1,10 @@
+import pytest
+
+from bokeh.command.bootstrap import main
+
+def test_no_subcommand(capsys):
+ with pytest.raises(SystemExit):
+ main(["bokeh"])
+ out, err = capsys.readouterr()
+ assert err == "ERROR: Must specify subcommand, one of: html, json or serve\n"
+ assert out ==... | |
34fe6e4f499385cc437a720db0f54db0f0ba07d2 | tests/tests_twobody/test_mean_elements.py | tests/tests_twobody/test_mean_elements.py | import pytest
from poliastro.twobody.mean_elements import get_mean_elements
def test_get_mean_elements_raises_error_if_invalid_body():
body = "Sun"
with pytest.raises(ValueError) as excinfo:
get_mean_elements(body)
assert f"The input body is invalid." in excinfo.exconly()
| import pytest
from poliastro.twobody.mean_elements import get_mean_elements
def test_get_mean_elements_raises_error_if_invalid_body():
body = "Sun"
with pytest.raises(ValueError) as excinfo:
get_mean_elements(body)
assert f"The input body '{body}' is invalid." in excinfo.exconly()
| Add test for error check | Add test for error check
| Python | mit | poliastro/poliastro | ---
+++
@@ -1,9 +1,11 @@
import pytest
+
from poliastro.twobody.mean_elements import get_mean_elements
+
def test_get_mean_elements_raises_error_if_invalid_body():
body = "Sun"
with pytest.raises(ValueError) as excinfo:
get_mean_elements(body)
- assert f"The input body is invalid." in exc... |
dddf89e519e40ce118509dcb5823ad932fea88f8 | chainer/training/triggers/__init__.py | chainer/training/triggers/__init__.py | from chainer.training.triggers import interval_trigger # NOQA
from chainer.training.triggers import minmax_value_trigger # NOQA
# import class and function
from chainer.training.triggers.interval_trigger import IntervalTrigger # NOQA
from chainer.training.triggers.manual_schedule_trigger import ManualScheduleTrigg... | from chainer.training.triggers import interval_trigger # NOQA
from chainer.training.triggers import minmax_value_trigger # NOQA
# import class and function
from chainer.training.triggers.early_stopping_trigger import EarlyStoppingTrigger # NOQA
from chainer.training.triggers.interval_trigger import IntervalTrigger... | Fix the order of importing | Fix the order of importing
| Python | mit | niboshi/chainer,wkentaro/chainer,ktnyt/chainer,keisuke-umezawa/chainer,jnishi/chainer,hvy/chainer,chainer/chainer,niboshi/chainer,wkentaro/chainer,hvy/chainer,okuta/chainer,anaruse/chainer,keisuke-umezawa/chainer,tkerola/chainer,keisuke-umezawa/chainer,wkentaro/chainer,okuta/chainer,ktnyt/chainer,keisuke-umezawa/chaine... | ---
+++
@@ -3,9 +3,9 @@
# import class and function
+from chainer.training.triggers.early_stopping_trigger import EarlyStoppingTrigger # NOQA
from chainer.training.triggers.interval_trigger import IntervalTrigger # NOQA
from chainer.training.triggers.manual_schedule_trigger import ManualScheduleTrigger # NO... |
6469a486847823d36a8e804755c6165d0f2fd670 | bpython/__init__.py | bpython/__init__.py | # The MIT License
#
# Copyright (c) 2008 Bob Farrell
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, mer... | # The MIT License
#
# Copyright (c) 2008 Bob Farrell
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, mer... | Set version to mercurial in trunk | Set version to mercurial in trunk
| Python | mit | 5monkeys/bpython | ---
+++
@@ -22,7 +22,7 @@
import os.path
-__version__ = '0.11'
+__version__ = 'mercurial'
package_dir = os.path.abspath(os.path.dirname(__file__))
|
d128b13e9c05516dcba587c684ef2f54884d6bb6 | api/migrations/0001_create_application.py | api/migrations/0001_create_application.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-26 20:29
from __future__ import unicode_literals
from django.db import migrations
from oauth2_provider.models import Application
class Migration(migrations.Migration):
def add_default_application(apps, schema_editor):
Application.objects.cre... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-26 20:29
from __future__ import unicode_literals
from django.db import migrations
from oauth2_provider.models import Application
class Migration(migrations.Migration):
def add_default_application(apps, schema_editor):
Application.objects.cre... | Add an additional default redirect_uri | Add an additional default redirect_uri
(runserver's default port)
| Python | bsd-3-clause | hotosm/osm-export-tool2,hotosm/osm-export-tool2,hotosm/osm-export-tool2,hotosm/osm-export-tool2 | ---
+++
@@ -11,7 +11,7 @@
Application.objects.create(
name="OSM Export Tool UI",
redirect_uris=
- "http://localhost/authorized http://localhost:8080/authorized",
+ "http://localhost/authorized http://localhost:8080/authorized http://localhost:8000/authorized",
... |
e885f0557037d2df03453961acd1c40b7c44c069 | timesheet_activity_report/__openerp__.py | timesheet_activity_report/__openerp__.py | # -*- coding: utf-8 -*-
# © 2015 Elico corp (www.elico-corp.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'Timesheet Activities Report',
'version': '8.0.1.1.0',
'category': 'Human Resources',
'depends': [
'project_timesheet',
'project_issue_... | # -*- coding: utf-8 -*-
# © 2015 Elico corp (www.elico-corp.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'Timesheet Activities Report',
'version': '8.0.1.1.0',
'category': 'Human Resources',
'depends': [
'project_timesheet',
'project_issue_... | Add support key for Travis LINT check | Add support key for Travis LINT check
| Python | agpl-3.0 | Elico-Corp/odoo-addons,Elico-Corp/odoo-addons,Elico-Corp/odoo-addons | ---
+++
@@ -13,6 +13,7 @@
'project_task_category'
],
'author': 'Elico Corp',
+ 'support': 'support@elico-corp.com',
'license': 'AGPL-3',
'website': 'https://www.elico-corp.com',
'data': [ |
60d6f3ea5495503584220c60353df833304aff53 | linkedin_scraper/parsers/base.py | linkedin_scraper/parsers/base.py | from os import path
import linkedin_scraper
class BaseParser:
@staticmethod
def get_data_dir():
return path.abspath(path.join(linkedin_scraper.__file__,
'../..', 'data'))
@staticmethod
def normalize_lines(lines):
return set(line.lower().strip() for line in... | import logging
from os import path
import linkedin_scraper
logger = logging.getLogger(__name__)
class BaseParser:
@staticmethod
def get_data_dir():
return path.abspath(path.join(linkedin_scraper.__file__,
'../..', 'data'))
@staticmethod
def normalize_lines(lines)... | Handle non existing data files in BaseParser. | Handle non existing data files in BaseParser.
| Python | mit | nihn/linkedin-scraper,nihn/linkedin-scraper | ---
+++
@@ -1,6 +1,9 @@
+import logging
from os import path
import linkedin_scraper
+
+logger = logging.getLogger(__name__)
class BaseParser:
@@ -18,8 +21,12 @@
Get and normalize lines from datafile.
:param name: name of the file in package data directory
"""
- with open(pat... |
5dacf6d2e2e74b783e39641674fc0f8e718618b3 | imager/ImagerProfile/models.py | imager/ImagerProfile/models.py | from django.db import models
# from django.conf import settings
# Create your models here.
class ImagerProfile(models.Model):
profile_picture = models.ImageField()
# user = models.OneToOneField(settings.AUTH_USER_MODEL)
phone_number = models.CharField(max_length=15) # X(XXX) XXX-XXXX
birthday = mod... | from django.db import models
from django.contrib.auth.models import User
# class ImagerProfile(models.Manager):
# pass
class ImagerProfile(models.Model):
user = models.OneToOneField(User)
# objects = ImagerProfile()
profile_picture = models.ImageField(null=True)
phone_number = models.CharField(... | Change ImagerProfile model privacy booleans to default of False, profile_picture to nullable | Change ImagerProfile model privacy booleans to default of False, profile_picture to nullable
| Python | mit | nbeck90/django-imager,nbeck90/django-imager | ---
+++
@@ -1,17 +1,21 @@
from django.db import models
-# from django.conf import settings
+from django.contrib.auth.models import User
-# Create your models here.
+
+# class ImagerProfile(models.Manager):
+# pass
class ImagerProfile(models.Model):
+ user = models.OneToOneField(User)
+ # objects = I... |
1f03af4a3ceda754dc0196c49f295fc683bd6e5a | opps/core/cache/models.py | opps/core/cache/models.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db import models
class ModelCaching(models.Model):
pass
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db import models
from django.core.cache import cache
from .managers import CacheManager
ModelBase = type(models.Model)
class MetaCaching(ModelBase):
def __new__(*args, **kwargs):
new_class = ModelBase.__new__(*args, **kwargs)
new_manager... | Create MetaCaching, ModelBase for core cache | Create MetaCaching, ModelBase for core cache
| Python | mit | YACOWS/opps,williamroot/opps,opps/opps,YACOWS/opps,jeanmask/opps,opps/opps,williamroot/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps,opps/opps,jeanmask/opps,williamroot/opps,opps/opps | ---
+++
@@ -1,7 +1,19 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db import models
+from django.core.cache import cache
+
+from .managers import CacheManager
-class ModelCaching(models.Model):
- pass
+ModelBase = type(models.Model)
+
+
+class MetaCaching(ModelBase):
+ def __new__(*args, ... |
8b6d10e8339510bbc745a3167fd1d5a60422b370 | tests/test_planner.py | tests/test_planner.py | import cutplanner
import unittest
class TestPlanner(unittest.TestCase):
def setUp(self):
sizes = [50, 80, 120]
needed = [10, 25, 75]
loss = 0.25
self.planner = cutplanner.Planner(sizes, needed, loss)
def test_largest_stock(self):
largest = self.planner.largest_stock
... | import cutplanner
import unittest
class TestPlanner(unittest.TestCase):
def setUp(self):
sizes = [50, 80, 120]
needed = [10, 25, 75]
loss = 0.25
self.planner = cutplanner.Planner(sizes, needed, loss)
def test_init_pieces(self):
self.assertEqual(len(self.planner.pieces_... | Add tests for planner init | Add tests for planner init
| Python | mit | alanc10n/py-cutplanner | ---
+++
@@ -8,6 +8,14 @@
needed = [10, 25, 75]
loss = 0.25
self.planner = cutplanner.Planner(sizes, needed, loss)
+
+ def test_init_pieces(self):
+ self.assertEqual(len(self.planner.pieces_needed), 3)
+ self.assertEqual(self.planner.pieces_needed[0].length, 75)
+
+ def t... |
88245d2cd66c75e1096eec53882a2750826f03be | zerver/migrations/0108_fix_default_string_id.py | zerver/migrations/0108_fix_default_string_id.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-24 02:39
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def fix_realm_string_ids(apps, schema_editor):
# type: (StateApps, DatabaseSchem... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-24 02:39
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def fix_realm_string_ids(apps, schema_editor):
# type: (StateApps, DatabaseSchem... | Fix deactivated realm corner cases with 0108. | migrations: Fix deactivated realm corner cases with 0108.
Previously the default-string-id migration would not correctly handle
ignoring deactivated realms.
| Python | apache-2.0 | hackerkid/zulip,dhcrzf/zulip,tommyip/zulip,jackrzhang/zulip,kou/zulip,brockwhittaker/zulip,hackerkid/zulip,brainwane/zulip,andersk/zulip,mahim97/zulip,brainwane/zulip,punchagan/zulip,rht/zulip,timabbott/zulip,mahim97/zulip,punchagan/zulip,synicalsyntax/zulip,brainwane/zulip,synicalsyntax/zulip,brockwhittaker/zulip,rht/... | ---
+++
@@ -8,12 +8,12 @@
def fix_realm_string_ids(apps, schema_editor):
# type: (StateApps, DatabaseSchemaEditor) -> None
Realm = apps.get_model('zerver', 'Realm')
- if Realm.objects.count() != 2:
+ if Realm.objects.filter(deactivated=False).count() != 2:
return
zulip_realm = Realm.o... |
464fc1e9a905df25b12975422d5b48cf8286306c | custom/icds_reports/utils/migrations.py | custom/icds_reports/utils/migrations.py | from __future__ import absolute_import
from __future__ import unicode_literals
from corehq.sql_db.operations import RawSQLMigration
def get_view_migrations():
sql_views = [
'awc_location_months.sql',
'agg_awc_monthly.sql',
'agg_ccs_record_monthly.sql',
'agg_child_health_monthly.sq... | from __future__ import absolute_import
from __future__ import unicode_literals
from corehq.sql_db.operations import RawSQLMigration
def get_view_migrations():
sql_views = [
'awc_location_months.sql',
'agg_awc_monthly.sql',
'agg_ccs_record_monthly.sql',
'agg_child_health_monthly.sq... | Add aww_incentive report view to migration util | Add aww_incentive report view to migration util
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -17,6 +17,7 @@
'ccs_record_monthly_view.sql',
'agg_ls_monthly.sql',
'service_delivery_monthly.sql',
+ 'aww_incentive_report_monthly.sql',
]
migrator = RawSQLMigration(('custom', 'icds_reports', 'migrations', 'sql_templates', 'database_views'))
operations = [... |
4c50bcf29dc397405b21322c6115a00c1df56559 | indico/modules/events/views.py | indico/modules/events/views.py | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | Add view for the events modules | Add view for the events modules
| Python | mit | indico/indico,ThiefMaster/indico,ThiefMaster/indico,pferreir/indico,DirkHoffmann/indico,indico/indico,indico/indico,DirkHoffmann/indico,DirkHoffmann/indico,OmeGak/indico,mvidalgarcia/indico,indico/indico,OmeGak/indico,pferreir/indico,mic4ael/indico,mic4ael/indico,ThiefMaster/indico,OmeGak/indico,pferreir/indico,OmeGak/... | ---
+++
@@ -18,7 +18,18 @@
from MaKaC.webinterface.pages.admins import WPAdminsBase
from MaKaC.webinterface.pages.base import WPJinjaMixin
+from MaKaC.webinterface.pages.conferences import WPConferenceDefaultDisplayBase
class WPReferenceTypes(WPJinjaMixin, WPAdminsBase):
template_prefix = 'events/'
+
+
... |
2dda63a9a71764c5f4b5e6d15372dd2eb296ef4b | nflpool/services/activeplayers_service.py | nflpool/services/activeplayers_service.py | import requests
from nflpool.data.dbsession import DbSessionFactory
from nflpool.data.activeplayers import ActiveNFLPlayers
import nflpool.data.secret as secret
from requests.auth import HTTPBasicAuth
from nflpool.data.seasoninfo import SeasonInfo
class ActivePlayersService:
@classmethod
def add_active_nflpla... | import requests
from nflpool.data.dbsession import DbSessionFactory
from nflpool.data.activeplayers import ActiveNFLPlayers
import nflpool.data.secret as secret
from requests.auth import HTTPBasicAuth
from nflpool.data.seasoninfo import SeasonInfo
class ActivePlayersService:
@classmethod
def add_active_nflpla... | Remove TODO - complete as of last commit | Remove TODO - complete as of last commit
Season object is passed to the table update
| Python | mit | prcutler/nflpool,prcutler/nflpool | ---
+++
@@ -33,8 +33,6 @@
except KeyError:
continue
- # TODO Update season='2017' below to a variable
-
active_players = ActiveNFLPlayers(firstname=firstname, lastname=lastname, player_id=player_id,
team_id=team_id,... |
7e97ddd43b8b388091e62f29d8a31875d8637d71 | tinman/__init__.py | tinman/__init__.py | #!/usr/bin/env python
"""
Core Tinman imports
"""
__author__ = 'Gavin M. Roy'
__email__ = '<gmr@myyearbook.com>'
__since__ = '2011-03-14'
__version__ = "0.2.5
__all__ = ['tinman.application',
'tinman.cache',
'tinman.cli',
'tinman.clients',
'tinman.utils',
'tinman.... | #!/usr/bin/env python
"""
Core Tinman imports
"""
__author__ = 'Gavin M. Roy'
__email__ = '<gmr@myyearbook.com>'
__since__ = '2011-03-14'
__version__ = "0.2.5"
__all__ = ['tinman.application',
'tinman.cache',
'tinman.cli',
'tinman.clients',
'tinman.utils',
'tinman... | Fix a small release bug | Fix a small release bug
| Python | bsd-3-clause | lucius-feng/tinman,gmr/tinman,lucius-feng/tinman,gmr/tinman,lucius-feng/tinman | ---
+++
@@ -5,7 +5,7 @@
__author__ = 'Gavin M. Roy'
__email__ = '<gmr@myyearbook.com>'
__since__ = '2011-03-14'
-__version__ = "0.2.5
+__version__ = "0.2.5"
__all__ = ['tinman.application',
'tinman.cache', |
1b68bd3c5cb81f06ccc4dcf69baeafca1104ed37 | nirikshak/workers/files/ini.py | nirikshak/workers/files/ini.py | # Copyright 2017 <thenakliman@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 agreed to... | # Copyright 2017 <thenakliman@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 agreed to... | Support for python3.5 has been added for configparser | Support for python3.5 has been added for configparser
| Python | apache-2.0 | thenakliman/nirikshak,thenakliman/nirikshak | ---
+++
@@ -13,7 +13,10 @@
# under the License.
import logging
-import configparser
+try:
+ import configparser
+except ImportError:
+ import ConfigParser as configparser
from nirikshak.common import plugins
from nirikshak.workers import base |
7a1056e7c929b07220fdefb45e282104ee192836 | github3/__init__.py | github3/__init__.py | """
github3
=======
See http://github3py.rtfd.org/ for documentation.
:copyright: (c) 2012 by Ian Cordasco
:license: Modified BSD, see LICENSE for more details
"""
__title__ = 'github3'
__author__ = 'Ian Cordasco'
__license__ = 'Modified BSD'
__copyright__ = 'Copyright 2012 Ian Cordasco'
__version__ = '0.1a3'
from... | """
github3
=======
See http://github3py.rtfd.org/ for documentation.
:copyright: (c) 2012 by Ian Cordasco
:license: Modified BSD, see LICENSE for more details
"""
__title__ = 'github3'
__author__ = 'Ian Cordasco'
__license__ = 'Modified BSD'
__copyright__ = 'Copyright 2012 Ian Cordasco'
__version__ = '0.1a3'
from... | Add more objects to the default namespace. | Add more objects to the default namespace.
Ease of testing, I'm not exactly a fan of polluting it though. Might rework
this later.
| Python | bsd-3-clause | wbrefvem/github3.py,itsmemattchung/github3.py,christophelec/github3.py,sigmavirus24/github3.py,icio/github3.py,h4ck3rm1k3/github3.py,krxsky/github3.py,jim-minter/github3.py,ueg1990/github3.py,agamdua/github3.py,degustaf/github3.py,balloob/github3.py | ---
+++
@@ -18,8 +18,12 @@
from .api import *
from .github import GitHub
from .models import GitHubError
-
from .event import Event
from .gist import Gist, GistComment, GistFile
from .git import Blob, GitData, Commit, Reference, GitObject, Tag, Tree, Hash
from .issue import Issue, IssueComment, IssueEvent, Lab... |
689980daec94683557113163d0b7384c33904bbf | app/aandete/model/model.py | app/aandete/model/model.py | from google.appengine.ext import db
class Recipe(db.Model):
title = db.StringProperty(required=True)
text = db.TextProperty()
ingredients = db.TextProperty()
tags = db.StringListProperty()
photo = db.BlobProperty()
owner = db.UserProperty(auto_current_user_add=True, required=True)
class Cookb... | from google.appengine.ext import db
class Recipe(db.Model):
title = db.StringProperty(required=True)
text = db.TextProperty()
ingredients = db.TextProperty()
tags = db.StringListProperty()
photo = db.BlobProperty()
owner = db.UserProperty(auto_current_user_add=True, required=True)
@classm... | Allow string IDs in get_by_id. | Allow string IDs in get_by_id.
| Python | bsd-3-clause | stefanv/aandete,stefanv/aandete | ---
+++
@@ -9,6 +9,12 @@
owner = db.UserProperty(auto_current_user_add=True, required=True)
+ @classmethod
+ def get_by_id(cls, id):
+ id = int(id)
+ key = db.Key.from_path('Recipe', id)
+ return db.Model.get(key)
+
class Cookbook(db.Model):
title = db.StringProperty(required... |
932e3d8b00768b1b3c103d3d44f714db5bb3a3e6 | examples/field_example.py | examples/field_example.py | import graphene
class Person(graphene.Interface):
name = graphene.String()
age = graphene.ID()
class Patron(Person):
id = graphene.ID()
class Query(graphene.ObjectType):
patron = graphene.Field(Patron)
def resolve_patron(self, args, info):
return Patron(id=1, name='Demo')
schema = grap... | import graphene
class Person(graphene.Interface):
name = graphene.String()
age = graphene.ID()
class Patron(Person):
id = graphene.ID()
class Query(graphene.ObjectType):
patron = graphene.Field(Patron)
def resolve_patron(self, args, info):
return Patron(id=1, name='Demo')
schema = g... | Fix flake8 issues in field example | Fix flake8 issues in field example
| Python | mit | Globegitter/graphene,graphql-python/graphene,Globegitter/graphene,sjhewitt/graphene,graphql-python/graphene,sjhewitt/graphene | ---
+++
@@ -1,11 +1,14 @@
import graphene
+
class Person(graphene.Interface):
name = graphene.String()
age = graphene.ID()
+
class Patron(Person):
id = graphene.ID()
+
class Query(graphene.ObjectType):
@@ -26,5 +29,3 @@
result = schema.execute(query)
# Print the result
print result.data[... |
d60c7e9471c442112d66a9b15838bd22fdd76600 | libraries/encryption.py | libraries/encryption.py | from Crypto.Cipher import Blowfish
from django.conf import settings
from random import choice
from base64 import encodestring as encode
from base64 import decodestring as decode
import base64
import hashlib
import string
import os
def sha_password(password):
salt = os.urandom(4)
h = hashlib.sha1(password)
... | from Crypto.Cipher import Blowfish
from django.conf import settings
from random import choice
from base64 import encodestring as encode
from base64 import decodestring as decode
import base64
import hashlib
import string
import os
def sha_password(password):
salt = os.urandom(4)
h = hashlib.sha1(password)
... | Exclude the salt from the returned decrypted password | Exclude the salt from the returned decrypted password
| Python | agpl-3.0 | dastergon/identity.gentoo.org,gentoo/identity.gentoo.org,dastergon/identity.gentoo.org,gentoo/identity.gentoo.org | ---
+++
@@ -29,7 +29,7 @@
def decrypt_password(password):
obj = Blowfish.new(settings.BLOWFISH_KEY)
original_password = obj.decrypt(base64.b64decode(password + settings.SECRET_KEY[:8]))
- return original_password
+ return original_password[:-8]
def random_string(length, type = None):
if type ... |
a047fe167a598adfccc70268a01829b8bcdb11e1 | python/test/clienttest.py | python/test/clienttest.py | import molequeue
client = molequeue.Client()
client.connect_to_server('MoleQueue')
job_request = molequeue.JobRequest()
job_request.queue = 'salix'
job_request.program = 'sleep (testing)'
client.submit_job_request(job_request) | import unittest
import molequeue
class TestClient(unittest.TestCase):
def test_submit_job_request(self):
client = molequeue.Client()
client.connect_to_server('MoleQueue')
job_request = molequeue.JobRequest()
job_request.queue = 'salix'
job_request.program = 'sleep (testing)'
client.submit... | Convert test case to Python unittest.TestCase | Convert test case to Python unittest.TestCase
Use Python's testing framework
Change-Id: I924f329c43294bb1fbb395a7bb19bcaf06ea9385
| Python | bsd-3-clause | OpenChemistry/molequeue,OpenChemistry/molequeue,OpenChemistry/molequeue | ---
+++
@@ -1,10 +1,18 @@
+import unittest
+
import molequeue
-client = molequeue.Client()
-client.connect_to_server('MoleQueue')
+class TestClient(unittest.TestCase):
-job_request = molequeue.JobRequest()
-job_request.queue = 'salix'
-job_request.program = 'sleep (testing)'
+ def test_submit_job_request(self):... |
0942ee64b3d84d5ea818a204c16b80d4120e54f2 | st2common/st2common/transport/__init__.py | st2common/st2common/transport/__init__.py | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | Remove some nasty imports to avoid cyclic import issues. | Remove some nasty imports to avoid cyclic import issues.
| Python | apache-2.0 | Plexxi/st2,nzlosh/st2,Plexxi/st2,StackStorm/st2,nzlosh/st2,nzlosh/st2,Plexxi/st2,StackStorm/st2,StackStorm/st2,nzlosh/st2,StackStorm/st2,Plexxi/st2 | ---
+++
@@ -14,7 +14,7 @@
# limitations under the License.
from st2common.transport import liveaction, actionexecutionstate, execution, publishers, reactor
-from st2common.transport import bootstrap_utils, utils, connection_retry_wrapper
+from st2common.transport import utils, connection_retry_wrapper
# TODO(m... |
82b45c3ec1344bed87ac7d572d82f43a4320492c | craigomatic/wsgi.py | craigomatic/wsgi.py | """
WSGI config for craigomatic project.
It exposes the WSGI callable as a module-level variable named ``application``.
"""
import os
from os.path import abspath, dirname
from sys import path
from django.core.wsgi import get_wsgi_application
SITE_ROOT = dirname(dirname(abspath(__file__)))
path.append(SITE_ROOT)
os.... | """
WSGI config for craigomatic project.
It exposes the WSGI callable as a module-level variable named ``application``.
"""
import os
from os.path import abspath, dirname
from sys import path
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
SITE_ROOT = dirname(dirname... | Integrate whitenoise with the Django application | Integrate whitenoise with the Django application
This allows Django to serve static files in production.
| Python | mit | rgreinho/craigomatic,rgreinho/craigomatic,rgreinho/craigomatic,rgreinho/craigomatic | ---
+++
@@ -9,8 +9,11 @@
from django.core.wsgi import get_wsgi_application
+from whitenoise.django import DjangoWhiteNoise
+
SITE_ROOT = dirname(dirname(abspath(__file__)))
path.append(SITE_ROOT)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "craigomatic.settings")
application = get_wsgi_application()
+a... |
61ebf3fd3a80dc5573cb65c4250ede591d161b9e | pyaavso/formats/visual.py | pyaavso/formats/visual.py | from __future__ import unicode_literals
import pyaavso
class VisualFormatWriter(object):
"""
A class responsible for writing observation data in AAVSO
`Visual File Format`_.
The API here mimics the ``csv`` module in Python standard library.
.. _`Visual File Format`: http://www.aavso.org/aavso-v... | from __future__ import unicode_literals
import pyaavso
class VisualFormatWriter(object):
"""
A class responsible for writing observation data in AAVSO
`Visual File Format`_.
The API here mimics the ``csv`` module in Python standard library.
.. _`Visual File Format`: http://www.aavso.org/aavso-v... | Write date format in header. | Write date format in header.
| Python | mit | zsiciarz/pyaavso | ---
+++
@@ -25,3 +25,4 @@
fp.write('#TYPE=Visual\n')
fp.write('#OBSCODE=%s\n' % observer_code)
fp.write("#SOFTWARE=pyaavso %s\n" % pyaavso.get_version())
+ fp.write("#DATE=%s\n" % date_format.upper()) |
81b9a8179ef4db9857b4d133769c92c7b1972ee6 | pysuru/tests/test_base.py | pysuru/tests/test_base.py | # coding: utf-8
from pysuru.base import BaseAPI, ObjectMixin
def test_baseapi_headers_should_return_authorization_header():
api = BaseAPI(None, 'TOKEN')
assert {'Authorization': 'bearer TOKEN'} == api.headers
def test_build_url_should_return_full_api_endpoint():
api = BaseAPI('http://example.com/', None... | # coding: utf-8
from pysuru.base import BaseAPI, ObjectMixin
def test_baseapi_headers_should_return_authorization_header():
api = BaseAPI(None, 'TOKEN')
assert {'Authorization': 'bearer TOKEN'} == api.headers
def test_baseapi_conn_should_return_same_object():
api = BaseAPI(None, None)
obj1 = api.con... | Add test to ensure only one conn object is created | Add test to ensure only one conn object is created
| Python | mit | rcmachado/pysuru | ---
+++
@@ -5,6 +5,13 @@
def test_baseapi_headers_should_return_authorization_header():
api = BaseAPI(None, 'TOKEN')
assert {'Authorization': 'bearer TOKEN'} == api.headers
+
+
+def test_baseapi_conn_should_return_same_object():
+ api = BaseAPI(None, None)
+ obj1 = api.conn
+ obj2 = api.conn
+ ... |
d32710e53b89e1377a64427f934053c3b0d33802 | bin/intake_multiprocess.py | bin/intake_multiprocess.py | import json
import logging
import argparse
import numpy as np
import emission.pipeline.scheduler as eps
if __name__ == '__main__':
try:
intake_log_config = json.load(open("conf/log/intake.conf", "r"))
except:
intake_log_config = json.load(open("conf/log/intake.conf.sample", "r"))
intake_l... | import json
import logging
import argparse
import numpy as np
import emission.pipeline.scheduler as eps
if __name__ == '__main__':
try:
intake_log_config = json.load(open("conf/log/intake.conf", "r"))
except:
intake_log_config = json.load(open("conf/log/intake.conf.sample", "r"))
parser =... | Use a separate log file for the public launcher data | Use a separate log file for the public launcher data
Log files are not thread-safe
| Python | bsd-3-clause | sunil07t/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server | ---
+++
@@ -11,12 +11,6 @@
except:
intake_log_config = json.load(open("conf/log/intake.conf.sample", "r"))
- intake_log_config["handlers"]["file"]["filename"] = intake_log_config["handlers"]["file"]["filename"].replace("intake", "intake_launcher")
- intake_log_config["handlers"]["errors"]["filen... |
454e8203295c7f51e1d660adcaf3d282ded5652f | scripts/cluster/craq/start_craq_router.py | scripts/cluster/craq/start_craq_router.py | #!/usr/bin/python
import sys
import subprocess
import time
def main():
subprocess.Popen('/home/meru/bmistree/new-craq-dist/craq-router-32 -d meru -p 10499 -z 192.168.1.30:9888', shell=True)
subprocess.Popen('/home/meru/bmistree/new-craq-dist/craq-router-32 -d meru -p 10498 -z 192.168.1.30:9888', shell=True)
... | #!/usr/bin/python
import sys
import subprocess
import time
def main():
subprocess.Popen('/home/meru/bmistree/new-craq-dist/craq-router-32 -d meru -p 10499 -z 192.168.1.7:9888', shell=True)
subprocess.Popen('/home/meru/bmistree/new-craq-dist/craq-router-32 -d meru -p 10498 -z 192.168.1.7:9888', shell=True)
r... | Make craq router script point at correct zookeeper node. | Make craq router script point at correct zookeeper node.
| Python | bsd-3-clause | sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata | ---
+++
@@ -5,8 +5,8 @@
import time
def main():
- subprocess.Popen('/home/meru/bmistree/new-craq-dist/craq-router-32 -d meru -p 10499 -z 192.168.1.30:9888', shell=True)
- subprocess.Popen('/home/meru/bmistree/new-craq-dist/craq-router-32 -d meru -p 10498 -z 192.168.1.30:9888', shell=True)
+ subprocess.Popen('/hom... |
f0371f68fc0ece594710ad9dbbdbfdab00a22e49 | migrations/003_add_capped_collections.py | migrations/003_add_capped_collections.py | """
Add capped collections for real time data
"""
import logging
log = logging.getLogger(__name__)
def up(db):
capped_collections = [
"fco_realtime_pay_legalisation_post",
"fco_realtime_pay_legalisation_drop_off",
"fco_realtime_pay_register_birth_abroad",
"fco_realtime_pay_registe... | """
Add capped collections for real time data
"""
import logging
log = logging.getLogger(__name__)
def up(db):
capped_collections = [
"fco_pay_legalisation_post_realtime",
"fco_pay_legalisation_drop_off_realtime",
"fco_pay_register_birth_abroad_realtime",
"fco_pay_register_death_a... | Make realtim fco bucket names match format of others | Make realtim fco bucket names match format of others
| Python | mit | alphagov/backdrop,alphagov/backdrop,alphagov/backdrop | ---
+++
@@ -8,12 +8,12 @@
def up(db):
capped_collections = [
- "fco_realtime_pay_legalisation_post",
- "fco_realtime_pay_legalisation_drop_off",
- "fco_realtime_pay_register_birth_abroad",
- "fco_realtime_pay_register_death_abroad",
- "fco_realtime_pay_foreign_marriage_certi... |
db7583b62aad9eaf10c67e89cd46087b36c77d81 | scikits/image/io/setup.py | scikits/image/io/setup.py | #!/usr/bin/env python
from scikits.image._build import cython
import os.path
base_path = os.path.abspath(os.path.dirname(__file__))
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
config = Configuration('io', parent_package, t... | #!/usr/bin/env python
from scikits.image._build import cython
import os.path
base_path = os.path.abspath(os.path.dirname(__file__))
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
config = Configuration('io', parent_package, t... | Move plugin tests to io/tests. | io: Move plugin tests to io/tests.
| Python | bsd-3-clause | ClinicalGraphics/scikit-image,emmanuelle/scikits.image,juliusbierk/scikit-image,Hiyorimi/scikit-image,almarklein/scikit-image,newville/scikit-image,SamHames/scikit-image,ClinicalGraphics/scikit-image,almarklein/scikit-image,youprofit/scikit-image,jwiggins/scikit-image,Britefury/scikit-image,pratapvardhan/scikit-image,c... | ---
+++
@@ -11,7 +11,6 @@
config = Configuration('io', parent_package, top_path)
config.add_data_dir('tests')
- config.add_data_dir('_plugins/tests')
config.add_data_files('_plugins/*.ini')
# This function tries to create C files from the given .pyx files. If |
459e8ba9ecfd16276d7a623b5f6e61ac9fcedcee | kolibri/plugins/html5_viewer/options.py | kolibri/plugins/html5_viewer/options.py | import logging
logger = logging.getLogger(__name__)
# Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-sandbox
allowable_sandbox_tokens = set(
[
"allow-downloads-without-user-activation",
"allow-forms",
"allow-modals",
"allow-orientation-lock",
... | import logging
logger = logging.getLogger(__name__)
# Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-sandbox
allowable_sandbox_tokens = set(
[
"allow-downloads-without-user-activation",
"allow-forms",
"allow-modals",
"allow-orientation-lock",
... | Fix typo in sandbox attribute name. | Fix typo in sandbox attribute name.
| Python | mit | indirectlylit/kolibri,mrpau/kolibri,mrpau/kolibri,learningequality/kolibri,learningequality/kolibri,mrpau/kolibri,learningequality/kolibri,mrpau/kolibri,indirectlylit/kolibri,indirectlylit/kolibri,learningequality/kolibri,indirectlylit/kolibri | ---
+++
@@ -15,7 +15,7 @@
"allow-presentation",
"allow-same-origin",
"allow-scripts",
- "allow-storage-access-by-user-activation ",
+ "allow-storage-access-by-user-activation",
"allow-top-navigation",
"allow-top-navigation-by-user-activation",
] |
43238d0de9e4d6d4909b4d67c17449a9599e5dac | mygpo/web/templatetags/time.py | mygpo/web/templatetags/time.py | from datetime import time
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from django import template
register = template.Library()
@register.filter
def sec_to_time(sec):
""" Converts seconds to a time object
>>> t = sec_to_time(1000)
>>> (t.hour, t.minu... | from datetime import time
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from django import template
register = template.Library()
@register.filter
def sec_to_time(sec):
""" Converts seconds to a time object
>>> t = sec_to_time(1000)
>>> (t.hour, t.minu... | Format short durations without "0 hours" | Format short durations without "0 hours"
| Python | agpl-3.0 | gpodder/mygpo,gpodder/mygpo,gpodder/mygpo,gpodder/mygpo | ---
+++
@@ -29,10 +29,16 @@
""" Converts seconds into a duration string
>>> format_duration(1000)
- '0h 16m 40s'
+ '16m 40s'
+ >>> format_duration(10009)
+ '2h 46m 49s'
"""
hours = int(sec / 60 / 60)
minutes = int((sec / 60) % 60)
seconds = int(sec % 60)
- return _('{h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.