commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
623c56c14aa1d1c47b081f607701323d00903dc9 | gather/topic/api.py | gather/topic/api.py | # -*- coding:utf-8 -*-
from gather.api import need_auth, EXCLUDE_COLUMNS
from gather.extensions import api_manager
from gather.topic.models import Topic, Reply
bp = api_manager.create_api_blueprint(
Topic,
methods=["GET", "POST"],
preprocessors={
'POST': [need_auth],
},
include_methods=[... | # -*- coding:utf-8 -*-
from flask import g, jsonify
from gather.api import need_auth, EXCLUDE_COLUMNS
from gather.extensions import api_manager
from gather.topic.models import Topic, Reply
bp = api_manager.create_api_blueprint(
Topic,
methods=["GET", "POST"],
preprocessors={
'POST': [need_auth],... | Add API to mark topic as reader | Add API to mark topic as reader
| Python | mit | whtsky/Gather,whtsky/Gather |
1e5c593ef0dc38c12bd987f9b2f37f9bfc3c71e1 | api/base/pagination.py | api/base/pagination.py | from rest_framework import pagination
from rest_framework.response import Response
class JSONAPIPagination(pagination.PageNumberPagination):
def get_paginated_response(self, data):
return Response({
'links': {
'next': self.get_next_link(),
'previous': self.get_p... | from collections import OrderedDict
from rest_framework import pagination
from rest_framework.response import Response
class JSONAPIPagination(pagination.PageNumberPagination):
"""Custom paginator that formats responses in a JSON-API compatible format."""
def get_paginated_response(self, data):
respo... | Make paginated response items ordered | Make paginated response items ordered
| Python | apache-2.0 | wearpants/osf.io,mluke93/osf.io,chennan47/osf.io,mluo613/osf.io,billyhunt/osf.io,monikagrabowska/osf.io,danielneis/osf.io,mluo613/osf.io,dplorimer/osf,jinluyuan/osf.io,cslzchen/osf.io,ZobairAlijan/osf.io,emetsger/osf.io,HarryRybacki/osf.io,emetsger/osf.io,cosenal/osf.io,amyshi188/osf.io,brianjgeiger/osf.io,HarryRybacki... |
69ec6586cd9ce9c8bda5b9c2f6f76ecd4a43baca | chessfellows/chess/models.py | chessfellows/chess/models.py | from django.db import models
from django.contrib.auth.models import User
class Match(models.Model):
white = models.ForeignKey(User, related_name="White")
black = models.ForeignKey(User, related_name="Black")
moves = models.TextField()
class Player(models.Model):
user = models.OneToOneField(User)
... | import os
from django.db import models
from django.contrib.auth.models import User
def get_file_owner_username(instance, filename):
parts = [instance.user.username]
parts.append(os.path.basename(filename))
path = u"/".join(parts)
return path
class Match(models.Model):
white = models.ForeignKey(U... | Add get_file_owner_username() to return a file path for a player's profile picture; add photo attribute to Player() model | Add get_file_owner_username() to return a file path for a player's profile picture; add photo attribute to Player() model
| Python | mit | EyuelAbebe/gamer,EyuelAbebe/gamer |
7d5c43e0c811bc45daee6e478e67e3c33b497033 | core/templatetags/git_revno.py | core/templatetags/git_revno.py | from subprocess import check_output
from django import template
register = template.Library()
@register.simple_tag
def git_revno():
return check_output(['git', 'rev-parse', '--verify', 'HEAD']).strip()[-7:]
| from subprocess import (
PIPE,
Popen,
)
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag
def git_revno():
p = Popen(['git', 'rev-parse', '--verify', 'HEAD'], stdout=PIPE,
cwd=settings.BASE_DIR)
out, _ = p.communicate()
... | Fix git-revno to always run in one dir | Fix git-revno to always run in one dir
| Python | mit | makyo/honeycomb,makyo/honeycomb,OpenFurry/honeycomb,makyo/honeycomb,OpenFurry/honeycomb,OpenFurry/honeycomb,makyo/honeycomb,OpenFurry/honeycomb |
3f0deec0ca0566fb411f98ec5940590b8dc8002a | optimize/py/main.py | optimize/py/main.py | from scipy import optimize as o
import numpy as np
import clean as c
def minimize_scalar(func, options):
bracket = options['bracket']
bounds = options['bounds']
method = options['method']
tol = options['tol']
options = options['options']
try:
return o.minimize_scalar(func, bracke... | from scipy import optimize as o
import numpy as np
import clean as c
def local_minimize(func, options):
bracket = options['bracket']
bounds = options['bounds']
method = options['method']
tol = options['tol']
options = options['options']
try:
return o.minimize_scalar(func, bracket... | Add basinhopping function for global min | Add basinhopping function for global min
| Python | mit | acjones617/scipy-node,acjones617/scipy-node |
ba72f7177a713d4e9b468c005f6c4306cbca5cc5 | dev/__init__.py | dev/__init__.py | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "asn1crypto"
other_packages = [
"oscrypto",
"certbuilder",
"certvalidator",
"crlbuilder",
"csrbuilder",
"ocspbuilder"
]
package_root = os.path.abspath(os.path.join(os.... | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "asn1crypto"
other_packages = [
"oscrypto",
"certbuilder",
"certvalidator",
"crlbuilder",
"csrbuilder",
"ocspbuilder"
]
package_root = os.path.abspath(os.path.join(os.... | Add package dev vars for compat with modularcrypto dev scripts | Add package dev vars for compat with modularcrypto dev scripts
| Python | mit | wbond/asn1crypto |
e96387d98c2b7c4ffd9ccd75fe081a7b54e563d9 | disco/constants.py | disco/constants.py | import re
SPOTIFY_SERVICE = 1
SOUNDCLOUD_SERVICE = 2
VALID_ATTACHMENT_TYPES = ('.ogg',)
# Regular expressions
RE_ATTACHMENT_URI = re.compile('^disco:\/\/(.*)\/(.*)$')
| import re
SPOTIFY_SERVICE = 1
SOUNDCLOUD_SERVICE = 2
VALID_ATTACHMENT_TYPES = ('.opus', '.weba', '.ogg', '.wav', '.mp3', '.flac')
# Regular expressions
RE_ATTACHMENT_URI = re.compile('^disco:\/\/(.*)\/(.*)$')
| Add more valid attachment types | disco: Add more valid attachment types
| Python | mit | pythonology/discobot,chandler14362/disco |
57a3391c391cf55bf70e781453faa69d223161f4 | tests/test_problem.py | tests/test_problem.py | import unittest
import theano.tensor as T
from pymanopt import Problem
from pymanopt.manifolds import Sphere
class TestProblem(unittest.TestCase):
def setUp(self):
self.X = X = T.vector()
self.cost = T.exp(T.sum(X**2))
n = self.n = 15
self.man = Sphere(n)
def test_prepare(... | import unittest
import numpy as np
from numpy import random as rnd
import numpy.testing as np_testing
import theano.tensor as T
from pymanopt import Problem, TheanoFunction
from pymanopt.manifolds import Sphere
class TestProblem(unittest.TestCase):
def setUp(self):
self.X = X = T.vector()
self.c... | Replace failing unit test due to backend changes | Replace failing unit test due to backend changes
Signed-off-by: Niklas Koep <342d5290239d9c5264c8f98185afedb99596601a@gmail.com>
| Python | bsd-3-clause | nkoep/pymanopt,nkoep/pymanopt,nkoep/pymanopt,pymanopt/pymanopt,pymanopt/pymanopt |
2cd4e6f021e576a17a3f8f40122775baee9e8889 | server/run.py | server/run.py | from eve import Eve
app = Eve()
if __name__ == '__main__':
app.run()
| import json
import settings
from flask import request, session
from requests import HTTPError
from requests_oauthlib import OAuth2Session
from eve import Eve
from flask_login import LoginManager
app = Eve()
login_manager = LoginManager(app)
login_manager.login_view = "login"
login_manager.session_protection = "stron... | Add initial views for google login. | Add initial views for google login.
| Python | mit | mattiaslundberg/typer,mattiaslundberg/typer,mattiaslundberg/typer,mattiaslundberg/typer |
154632b0ab27d36b63c302a550589a182a319ef8 | distance_matrix.py | distance_matrix.py | from GamTools import corr
import numpy as np
import argparse
parser = argparse.ArgumentParser(description='Calculate coverage over different window sizes for a list of bam files.')
parser.add_argument('npz_frequencies_file', help='An npz file containing co-segregation frequencies to convert to correlations')
args = p... | from GamTools import corr
import numpy as np
import argparse
parser = argparse.ArgumentParser(description='Calculate coverage over different window sizes for a list of bam files.')
parser.add_argument('npz_frequencies_file', help='An npz file containing co-segregation frequencies to convert to correlations')
args = p... | Change how/where to save the file | Change how/where to save the file
| Python | apache-2.0 | pombo-lab/gamtools,pombo-lab/gamtools |
ee22ba999deb9213445112f4486a6080834ba036 | django/__init__.py | django/__init__.py | VERSION = (1, 0, 'post-release-SVN')
def get_version():
"Returns the version as a human-format string."
v = '.'.join([str(i) for i in VERSION[:-1]])
if VERSION[-1]:
from django.utils.version import get_svn_revision
v = '%s-%s-%s' % (v, VERSION[-1], get_svn_revision())
return v
| VERSION = (1, 1, 0, 'alpha', 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if ... | Update django.VERSION in trunk per previous discussion | Update django.VERSION in trunk per previous discussion
--HG--
extra : convert_revision : svn%3Abcc190cf-cafb-0310-a4f2-bffc1f526a37/django/trunk%409103
| Python | bsd-3-clause | adieu/django-nonrel,adieu/django-nonrel,adieu/django-nonrel |
57fd8c49de7ef6e09a4f0fbd6b39c87127e91f9a | toggle_rspec_focus.py | toggle_rspec_focus.py | import sublime, sublime_plugin, re
class ToggleRspecFocusCommand(sublime_plugin.TextCommand):
def run(self, edit, surplus=False):
for region in self.view.sel():
line = self.view.line(region)
line_contents = self.view.substr(line)
focus_regex = r'.*(?:it|describe|context... | import sublime, sublime_plugin, re
class ToggleRspecFocusCommand(sublime_plugin.TextCommand):
def run(self, edit, surplus=False):
for region in self.view.sel():
line = self.view.line(region)
line_contents = self.view.substr(line)
focus_regex = r'.*(?:it|describe|context... | Add support for 'scenario' blocks | Add support for 'scenario' blocks
| Python | mit | axsuul/sublime-toggle-rspec-focus,axsuul/sublime-toggle-rspec-focus,axsuul/sublime-toggle-rspec-focus |
50889a2d9a70efa8685dbb3ed9c60b05d4ecf4c1 | backend/unpp_api/apps/partner/migrations/0043_auto_20171220_1311.py | backend/unpp_api/apps/partner/migrations/0043_auto_20171220_1311.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-12-20 13:11
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('partner', '0042_auto_20171220_1305'),
]
operations... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-12-20 13:11
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('partner', '0042_auto_20171220_1305'),
]
operations... | Change migration so newly added field is nullable | Change migration so newly added field is nullable
| Python | apache-2.0 | unicef/un-partner-portal,unicef/un-partner-portal,unicef/un-partner-portal,unicef/un-partner-portal |
902b2b0929dad116664d37a13ff325a10b67db7b | catalog/queue/sqs.py | catalog/queue/sqs.py | from Queue import Queue, Empty
import json
from .base import BaseQueue
sqs = None
def do_delayed_imports():
global sqs
from boto import sqs
class SQSQueue(BaseQueue):
_cache = Queue()
def __init__(self):
BaseQueue.__init__(self)
do_delayed_imports()
self.conn = sqs.connect_t... | from multiprocessing import Queue
from Queue import Empty
import json
from .base import BaseQueue
sqs = None
def do_delayed_imports():
global sqs
from boto import sqs
class SQSQueue(BaseQueue):
_cache = Queue()
def __init__(self):
BaseQueue.__init__(self)
do_delayed_imports()
... | Use queue from multiprocessing library instead of Queue | Use queue from multiprocessing library instead of Queue
| Python | mpl-2.0 | mozilla/structured-catalog |
15463168ed715761eaf483a1e53eb74d92b83e04 | tests.py | tests.py | import unittest
import fuckit_commit
class Fuckit_CommitTestCase(unittest.TestCase):
'''
Unit Test cases for fuckit_commit
'''
def setUp(self):
pass
def test_send_sms(self):
pass
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
| import unittest
import json
from twilio.rest import TwilioRestClient
import fuckit_commit
class Fuckit_CommitTestCase(unittest.TestCase):
'''
Unit Test cases for fuckit_commit
'''
def setUp(self):
with open('configuration.json') as f:
self.config = json.load(f)
def test_send_sms(self):
cli... | Add test to send sms | Add test to send sms
| Python | mit | ueg1990/fuckit_commit |
1902ed44f41eabf1c8207e47d5c31dd58471146f | pymunk/transform.py | pymunk/transform.py | from typing import NamedTuple
class Transform(NamedTuple):
"""Type used for 2x3 affine transforms.
See wikipedia for details:
http://en.wikipedia.org/wiki/Affine_transformation
The properties map to the matrix in this way:
= = ==
= = ==
a c tx
b d ty
= = ==
An instance can ... | import math
from typing import NamedTuple
class Transform(NamedTuple):
"""Type used for 2x3 affine transforms.
See wikipedia for details:
http://en.wikipedia.org/wiki/Affine_transformation
The properties map to the matrix in this way:
= = ==
= = ==
a c tx
b d ty
= = ==
An i... | Add some helper methods to create translate, scale and rotate Transforms. | Add some helper methods to create translate, scale and rotate Transforms.
| Python | mit | viblo/pymunk,viblo/pymunk |
feb88aa30b362e02671d51d8b3e03a7194d99646 | kobra/urls.py | kobra/urls.py | # -*- coding: utf-8 -*-
from django.conf.urls import include, url
from django.contrib import admin
from .views import web_client_view
urlpatterns = [
# url(r'^', include('kobra.api.v1.urls', namespace='legacy')),
url(r'^api/v1/', include('kobra.api.v1.urls', namespace='v1')),
url(r'^admin/', include(adm... | # -*- coding: utf-8 -*-
from django.conf.urls import include, url
from django.contrib import admin
from .views import web_client_view
urlpatterns = [
# url(r'^', include('kobra.api.v1.urls', namespace='legacy')),
url(r'^api/v1/', include('kobra.api.v1.urls', namespace='v1')),
url(r'^admin/', include(adm... | Fix for broken static file serving | Fix for broken static file serving
| Python | mit | karservice/kobra,karservice/kobra,karservice/kobra,karservice/kobra |
459916c800f09e7600ae7442bb34236b9f418f53 | feedhq/utils.py | feedhq/utils.py | # -*- coding: utf-8 -*-
from django.conf import settings
from django.core.validators import EmailValidator, ValidationError
import redis
def get_redis_connection():
"""
Helper used for obtain a raw redis client.
"""
from redis_cache.cache import pool
connection_pool = pool.get_connection_pool(
... | # -*- coding: utf-8 -*-
from django.conf import settings
from django.core.validators import EmailValidator, ValidationError
import redis
def get_redis_connection():
"""
Helper used for obtain a raw redis client.
"""
from redis_cache.cache import pool
client = redis.Redis(**settings.REDIS)
cli... | Update method of getting redis connection | Update method of getting redis connection
| Python | bsd-3-clause | feedhq/feedhq,rmoorman/feedhq,rmoorman/feedhq,rmoorman/feedhq,rmoorman/feedhq,feedhq/feedhq,feedhq/feedhq,feedhq/feedhq,feedhq/feedhq,rmoorman/feedhq |
2c1282680bc9d84e37c40923e8ca288bf8547998 | fabfile/daemons.py | fabfile/daemons.py | #!/usr/bin/env python
from time import sleep, time
from fabric.api import execute, task, env
import app_config
import sys
import traceback
def safe_execute(*args, **kwargs):
try:
execute(*args, **kwargs)
except:
print "ERROR [timestamp: %d]: Here's the traceback" % time()
ex_type, ex,... | #!/usr/bin/env python
from time import sleep, time
from fabric.api import execute, task, env
import app_config
import sys
import traceback
def safe_execute(*args, **kwargs):
"""
Wrap execute() so that all exceptions are caught and logged.
"""
try:
execute(*args, **kwargs)
except:
... | Add comment to new safe_execute function | Add comment to new safe_execute function
| Python | mit | nprapps/elections14,nprapps/elections14,nprapps/elections14,nprapps/elections14 |
b89c94cb55db1d8252b75949b5cba919e0b69a6e | skeleton/website/jasyscript.py | skeleton/website/jasyscript.py | import konstrukteur.Konstrukteur
@task
def build(regenerate = False):
"""Generate source (development) version"""
konstrukteur.Konstrukteur.build(regenerate)
| import konstrukteur.Konstrukteur
@task
def build(regenerate = False):
"""Generate source (development) version"""
# Initialize assets
AssetManager.AssetManager(profile, session)
# Build static website
konstrukteur.Konstrukteur.build(regenerate)
| Fix asset loading in skeleton | Fix asset loading in skeleton
| Python | mit | fastner/konstrukteur,fastner/konstrukteur,fastner/konstrukteur |
909f36eecdf38f0915f945144966c892e09670ff | src/logger.py | src/logger.py | #
# License: MIT (doc/LICENSE)
# Author: Todd Gaunt
#
# File: imgfetch/fourchan.py
# This file contains the logging functions for writing to stdout stderr etc...
from sys import stderr
PROGRAM_NAME = "imgfetch: "
def error(level, msg):
global PROGRAM_NAME
if level < 0:
errmsg=PROGRAM_NAME + "error: i... | #
# License: MIT (doc/LICENSE)
# Author: Todd Gaunt
from sys import stderr
PROGRAM_NAME = "imgfetch: "
def error(level, msg):
global PROGRAM_NAME
if level < 0:
quit()
if level >= 0:
errmsg=PROGRAM_NAME + "error: " + msg
print(errmsg, file=stderr)
quit()
def warning(level, msg):
... | Update level checks to allow a verbosity level of 0 or greater | Update level checks to allow a verbosity level of 0 or greater
| Python | isc | toddgaunt/imgfetch |
d1628356c7981748e2446c7b43d33d21cdef7e02 | geoengine_partner/geo_partner.py | geoengine_partner/geo_partner.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Nicolas Bessi
# Copyright 2011-2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# ... | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Nicolas Bessi
# Copyright 2011-2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# ... | Use absolute imports on opnerp.addons | [FIX] Use absolute imports on opnerp.addons
| Python | agpl-3.0 | OCA/geospatial,OCA/geospatial,OCA/geospatial |
2403cbe2aa8f515bdd8f575112478010389ee48b | conan/ConanServerToArtifactory/migrate.py | conan/ConanServerToArtifactory/migrate.py | import os
import subprocess
def run(cmd):
ret = os.system(cmd)
if ret != 0:
raise Exception("Command failed: %s" % cmd)
# Assuming local = conan_server and Artifactory remotes
output = subprocess.check_output("conan search -r=local --raw")
packages = output.splitlines()
for package in packages:
... | import os
import subprocess
def run(cmd):
ret = os.system(cmd)
if ret != 0:
raise Exception("Command failed: %s" % cmd)
# Assuming local = conan_server and Artifactory remotes
output = subprocess.check_output("conan search * --remote=local --raw")
packages = output.decode("utf-8").splitlines()
for p... | Update Conan server migration script | Update Conan server migration script
| Python | apache-2.0 | JFrogDev/artifactory-scripts,JFrogDev/artifactory-scripts,JFrogDev/artifactory-scripts,JFrogDev/artifactory-scripts,JFrogDev/artifactory-scripts,JFrogDev/artifactory-scripts |
fd77e3211e2298457b9778f409c56c70a36bf3db | farmers_api/farmers/views.py | farmers_api/farmers/views.py | from rest_framework import viewsets
from .models import Farmer
from .serializers import FarmerSerializer
class FarmerViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Farmer.objects.all()
serializer_class = FarmerSerializer
filter_fields = ('town',)
| from rest_framework import viewsets, permissions
from .models import Farmer
from .serializers import FarmerSerializer
class FarmerViewSet(viewsets.ModelViewSet):
queryset = Farmer.objects.all()
serializer_class = FarmerSerializer
filter_fields = ('town',)
permissions = permissions.DjangoModelPermissi... | Add permission settings on FarmerViewSet | Add permission settings on FarmerViewSet
| Python | bsd-2-clause | tm-kn/farmers-api |
4cec5250a3f9058fea5af5ef432a5b230ca94963 | images/singleuser/user-config.py | images/singleuser/user-config.py | import os
mylang = 'test'
family = 'wikipedia'
custom_path = os.path.expanduser('~/user-config.py')
if os.path.exists(custom_path):
with open(custom_path, 'rb') as f:
exec(compile(f.read(), custom_path, 'exec'), globals())
del f
# Clean up temp variables, since pwb issues a warning otherwise
# to he... | import os
mylang = 'test'
family = 'wikipedia'
custom_path = os.path.expanduser('~/user-config.py')
if os.path.exists(custom_path):
with open(custom_path, 'rb') as f:
exec(compile(f.read(), custom_path, 'exec'), globals())
del f
# Clean up temp variables, since pwb issues a warning otherwise
# to he... | Update to use newer oauth style | Update to use newer oauth style
| Python | mit | yuvipanda/paws,yuvipanda/paws |
3d3862b0c7ea872e690999f46de88be287598758 | lib/__init__.py | lib/__init__.py | import redis
import json
import time
class DHTStorage():
def __init__(self, key):
self.redis = redis.StrictRedis(host='localhost', port=6379, db=0)
self.key = key
def get_key(self, name):
return "%s:%s" % (self.key, name)
def send(self, name, data):
pushData = {'time': time.time(), 'value': data}
self.r... | import redis
import json
import time
class DHTStorage():
def __init__(self, key):
self.redis = redis.StrictRedis(host='localhost', port=6379, db=0)
self.key = key
def get_key(self, name):
return "%s:%s" % (self.key, name)
def send(self, name, data):
pushData = {'time': time.time(), 'value': data}
self.r... | Remove old entries (~2 months, keep 100000 entries) | Remove old entries (~2 months, keep 100000 entries)
| Python | mit | Ajnasz/pippo,Ajnasz/pippo,Ajnasz/pippo |
e676f59b445157d1cc247ada74e0b7b1fc1afced | demos/burgers_sim.py | demos/burgers_sim.py | from phi.flow import *
domain = Domain([64, 64], boundaries=PERIODIC)
world.add(BurgersVelocity(domain, velocity=lambda s: math.randfreq(s) * 2), physics=Burgers())
show(App('Burgers Equation in %dD' % len(domain.resolution), framerate=5))
| from phi.flow import *
domain = Domain([64, 64], boundaries=PERIODIC, box=box[0:100, 0:100])
world.add(BurgersVelocity(domain, velocity=Noise(channels=domain.rank) * 2), physics=Burgers())
show(App('Burgers Equation in %dD' % len(domain.resolution), framerate=5))
| Use Noise in Burgers demo | Use Noise in Burgers demo
| Python | mit | tum-pbs/PhiFlow,tum-pbs/PhiFlow |
d024177d3b060e6219074bf1500ebc6ae947ad1a | openassessment/fileupload/backends/__init__.py | openassessment/fileupload/backends/__init__.py | """ File Upload backends. """
from django.conf import settings
from . import django_storage, filesystem, s3, swift
def get_backend():
# .. setting_name: ORA2_FILEUPLOAD_BACKEND
# .. setting_default: s3
# .. setting_description: The backend used to upload the ora2 submissions attachments
# the s... | """ File Upload backends. """
from django.conf import settings
from . import django_storage, filesystem, s3, swift
def get_backend():
# .. setting_name: ORA2_FILEUPLOAD_BACKEND
# .. setting_default: 's3'
# .. setting_description: The backend used to upload the ora2 submissions attachments.
# Th... | Fix annotation: The default value should be a string | Fix annotation: The default value should be a string
| Python | agpl-3.0 | edx/edx-ora2,edx/edx-ora2,EDUlib/edx-ora2,EDUlib/edx-ora2,edx/edx-ora2,EDUlib/edx-ora2,EDUlib/edx-ora2,edx/edx-ora2 |
26b1d4f47c742f33c4ecdac68e88dbbc958e5756 | tests/create_minimal_image_test.py | tests/create_minimal_image_test.py | from unittest import TestCase
import create_minimal_image
from create_minimal_image import main
POPEN_COMMAND_LIST = ""
class CreateMinimalImageTest(TestCase):
def setUp(self):
global POPEN_COMMAND_LIST
POPEN_COMMAND_LIST = ""
create_minimal_image._run_popen_command = stubbed_run_popen_... | from unittest import TestCase
import create_minimal_image
from create_minimal_image import main
POPEN_COMMAND_LIST = []
class CreateMinimalImageTest(TestCase):
def setUp(self):
global POPEN_COMMAND_LIST
POPEN_COMMAND_LIST = []
create_minimal_image._run_popen_command = stubbed_run_popen_... | Revert "[TEST] refactor test to get it passing on Travis CI" | Revert "[TEST] refactor test to get it passing on Travis CI"
This reverts commit b92684d252e92a75115ce8617a15c107b5a34b09.
| Python | mit | williamsbdev/minimal-docker-image-maker,williamsbdev/minimal-docker-image-maker |
0ddaed24e0f011ca1bb777af49936f64684a7d4c | bin/scripts/contig_length_filter.py | bin/scripts/contig_length_filter.py | #!/usr/bin/env python
import sys
from Bio import SeqIO
from Bio.SeqRecord import SeqRecord
if len(sys.argv) < 5:
print("Usage: %s <length threshold> <contigs_file> <suffix> <output>" % sys.argv[0])
sys.exit(1)
f_n = sys.argv[2]
suffix = sys.argv[3]
input_seq_iterator = SeqIO.parse(open(f_n, "r"), "fasta")
... | #!/usr/bin/env python
import sys
from Bio import SeqIO
if len(sys.argv) < 4:
print("Usage: %s <length threshold> <contigs_file> <output>" % sys.argv[0])
sys.exit(1)
f_n = sys.argv[2]
input_seq_iterator = SeqIO.parse(open(f_n, "r"), "fasta")
filtered_iterator = (record for record in input_seq_iterator \
... | Revert "length filter script now adds provided suffix to contig names" | Revert "length filter script now adds provided suffix to contig names"
This reverts commit 4d3985f667465eb5564de4fada8820e23607a58b.
| Python | mit | tanaes/snakemake_assemble,tanaes/snakemake_assemble,tanaes/snakemake_assemble |
2dadeef44576ac5ecbb67b929c4190675c449c7f | devops/settings.py | devops/settings.py | DRIVER = 'devops.driver.libvirt.libvirt_driver'
DRIVER_PARAMETERS = {
'connection_string': 'qemu:///system',
}
INSTALLED_APPS = ['devops']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWOR... | import os
DRIVER = 'devops.driver.libvirt.libvirt_driver'
DRIVER_PARAMETERS = {
'connection_string': os.environ.get('CONNECTION_STRING', 'qemu:///system'),
}
INSTALLED_APPS = ['devops']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'postgres',
... | Use environment variable for connection_string driver parameter | Use environment variable for connection_string driver parameter
| Python | apache-2.0 | stackforge/fuel-devops,stackforge/fuel-devops |
0cb41062401670a3e423b610d1f128657a9ce623 | _tests/test_links.py | _tests/test_links.py | #!/usr/bin/env python
# -*- encoding: utf-8
import pytest
import requests
@pytest.mark.parametrize('path', [
# Check pagination is working correctly
'/page/2/', '/page/3/',
])
def test_pages_appear_correctly(path):
resp = requests.get(f'http://localhost:5757/{path}')
assert resp.status_code == 200
... | #!/usr/bin/env python
# -*- encoding: utf-8
import pytest
import requests
@pytest.mark.parametrize('path', [
# Check pagination is working correctly
'/page/2/', '/page/3/',
])
def test_pages_appear_correctly(path):
resp = requests.get(f'http://localhost:5757/{path}')
assert resp.status_code == 200
... | Add a couple of tests for the formatting pieces | Add a couple of tests for the formatting pieces
| Python | mit | alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net |
21af3dbed471c9f6c860db4d2ae84d1e0fed4077 | demo/option_example.py | demo/option_example.py | from sparts.tasks.periodic import PeriodicTask
from sparts.vservice import VService
from sparts.sparts import option
import socket
class HostCheckTask(PeriodicTask):
INTERVAL=5
check_name = option(default=socket.getfqdn(), type=str,
help='Name to check [%(default)s]')
def execute(se... | from sparts.tasks.periodic import PeriodicTask
from sparts.vservice import VService
from sparts.sparts import option, samples, SampleType
import socket
class HostCheckTask(PeriodicTask):
INTERVAL=5
check_name = option(default=socket.getfqdn(), type=str,
help='Name to check [%(default)s]... | Update option example to highlight samples as well | Update option example to highlight samples as well
And overriding samples
| Python | bsd-3-clause | facebook/sparts,fmoo/sparts,bboozzoo/sparts,djipko/sparts,pshuff/sparts,pshuff/sparts,fmoo/sparts,facebook/sparts,djipko/sparts,bboozzoo/sparts |
1661174b80e00ff04a2df245abf73b92825ec01a | libs/qr_tools.py | libs/qr_tools.py | #!/usr/bin/python3
import pyqrcode # sudo pip install pyqrcode
def getQRArray(text, errorCorrection):
""" Takes in text and errorCorrection (letter), returns 2D array of the QR code"""
# White is True (1)
# Black is False (0)
# ECC: L7, M15, Q25, H30
# Create the object
qr = pyqrcode.create(text, error=errorCo... | #!/usr/bin/python3
import pyqrcode # sudo pip install pyqrcode
def getQRArray(text, errorCorrection):
""" Takes in text and errorCorrection (letter), returns 2D array of the QR code"""
# White is True (1)
# Black is False (0)
# ECC: L7, M15, Q25, H30
# Create the object
qr = pyqrcode.create(text, error=errorCo... | Remove print of terminal output for debugging | Remove print of terminal output for debugging
| Python | mit | btcspry/3d-wallet-generator |
b0edec6bc9a4d77a1f0ea0f803ea892f35cc2f4f | text_field.py | text_field.py | # Created On: 2012/01/23
# Copyright 2011 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licenses/bsd_license
class TextFi... | # Created On: 2012/01/23
# Copyright 2011 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licenses/bsd_license
class TextFi... | Make TextField also work with a QLabel view, which doesn't allow editing. | Make TextField also work with a QLabel view, which doesn't allow editing.
| Python | bsd-3-clause | hsoft/qtlib |
b801df9acdc13460ecc5d36bcb6bd300f5de16c3 | flatten-array/flatten_array.py | flatten-array/flatten_array.py | def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
if isinstance(lst, (list, tuple)):
for item in lst:
if item is None:
continue
else:
... | def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
for item in lst:
if isinstance(item, (list, tuple)):
yield from _flatten(item)
elif item is not None:
... | Tidy and simplify generator code | Tidy and simplify generator code
| Python | agpl-3.0 | CubicComet/exercism-python-solutions |
58cbb8b3dbe8d1275743c3fd5d043cfa12914cb3 | data_structures/bitorrent/client.py | data_structures/bitorrent/client.py | from urlparse import urlparse
from torrent import Torrent
from trackers.udp import UDPTracker
class Client(object):
__TORRENTS = {}
@property
def torrents(self):
return self.__TORRENTS
@torrents.setter
def torrents(self, new_torrent):
self.__TORRENTS[new_torrent] = Torrent(new_torrent)
def dow... | import urllib
from random import randint
from urlparse import urlparse
from torrent import Torrent
from trackers.udp import UDPTracker
class Client(object):
__TORRENTS = {}
def __init__(self):
self.peer_id = urllib.quote("-AZ2470-" + "".join([str(randint(0, 9)) for i in xrange(12)]))
@property
def torr... | Use a separate method to get all peers of a torrent | Use a separate method to get all peers of a torrent
| Python | apache-2.0 | vtemian/university_projects,vtemian/university_projects,vtemian/university_projects |
848723c943cfb8995c6f2a68ea19b203c75e4aaa | tests/test_scan.py | tests/test_scan.py | #!/usr/bin/env python
# coding=utf-8
try:
import unittest.mock as mock
except ImportError:
import mock
import unittest
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from nessusapi.scan import Scan
from nessusapi.session import Session
class SessionTestCase(unittest.T... | # coding=utf-8
try:
import unittest.mock as mock
except ImportError:
import mock
import unittest
import nessusapi.scan
class TestScan(unittest.TestCase):
def test_init(self):
fake_nessus = mock.Mock(request_single=
mock.Mock(return_value='e3b4f63f-de03-ec8b'))
... | Update test scan to work for new model | Update test scan to work for new model
| Python | mit | sait-berkeley-infosec/pynessus-api |
1030381f6a22d38fa48222f44858a8396970494e | nucleus/urls.py | nucleus/urls.py | from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.http import HttpResponse
from watchman import views as watchman_views
admin.autodiscover() # Discover admin.py files for the admin interface.
urlpatterns = [
url(r'', include('nucleus.base.ur... | from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.http import HttpResponse
from watchman import views as watchman_views
admin.autodiscover() # Discover admin.py files for the admin interface.
admin.site.site_header = 'Release Notes Administration... | Customize admin site title and header | Customize admin site title and header
| Python | mpl-2.0 | mozilla/nucleus,mozilla/nucleus,mozilla/nucleus,mozilla/nucleus |
d017ca19b6d810387424e388656d5ff63244a1f7 | tests/engine/file_loader_test.py | tests/engine/file_loader_test.py | import unittest
from engine import file_loader
class FileLoaderTest(unittest.TestCase):
def test_load_units(self):
dicts = file_loader.read_and_parse_json('units')
self.assertIsInstance(dicts, list)
self.assertGreater(len(dicts), 0)
for dict_ in dicts:
self.assertIsIns... | import unittest
from engine import file_loader
class FileLoaderTest(unittest.TestCase):
def test_load_units(self):
dicts = file_loader.read_and_parse_json('units')
self.assertIsInstance(dicts, list)
self.assertGreater(len(dicts), 0)
for dict_ in dicts:
self.assertIsIns... | Include tests for file loading helpers | Include tests for file loading helpers
| Python | mit | Tactique/game_engine,Tactique/game_engine |
4f6400e9ecf9bbc1cee62567673c619f9a975f95 | lib/python/opendiamond/bundle.py | lib/python/opendiamond/bundle.py | #
# The OpenDiamond Platform for Interactive Search
# Version 5
#
# Copyright (c) 2011 Carnegie Mellon University
# All rights reserved.
#
# This software is distributed under the terms of the Eclipse Public
# License, Version 1.0 which can be found in the file named LICENSE.
# ANY USE, REPRODUCTION OR DISTRIBUT... | #
# The OpenDiamond Platform for Interactive Search
# Version 5
#
# Copyright (c) 2011 Carnegie Mellon University
# All rights reserved.
#
# This software is distributed under the terms of the Eclipse Public
# License, Version 1.0 which can be found in the file named LICENSE.
# ANY USE, REPRODUCTION OR DISTRIBUT... | Allow make_zipfile() to clobber the destination file | Allow make_zipfile() to clobber the destination file
| Python | epl-1.0 | cmusatyalab/opendiamond,cmusatyalab/opendiamond,cmusatyalab/opendiamond,cmusatyalab/opendiamond,cmusatyalab/opendiamond |
5bb6cc3ffb92736515df94b62d7d1981eadd7c44 | tilequeue/postgresql.py | tilequeue/postgresql.py | from itertools import cycle
from psycopg2.extras import register_hstore, register_json
import psycopg2
import threading
import ujson
class DBAffinityConnectionsNoLimit(object):
# Similar to the db affinity pool, but without keeping track of
# the connections. It's the caller's responsibility to call us
#... | from itertools import cycle
from psycopg2.extras import register_hstore, register_json
import psycopg2
import threading
import ujson
class DBAffinityConnectionsNoLimit(object):
# Similar to the db affinity pool, but without keeping track of
# the connections. It's the caller's responsibility to call us
#... | Use cycle instead of counting an index ourselves | Use cycle instead of counting an index ourselves
| Python | mit | tilezen/tilequeue,mapzen/tilequeue |
648189583d78efef9ec8f65e861e1321c397c1a6 | app/views/main_view.py | app/views/main_view.py | from flask import render_template
from flask_classy import FlaskView
from ..models import PostModel
class Main(FlaskView):
""" Main page view. """
route_base = "/"
def index(self):
posts = PostModel.fetch()
return render_template("index.html", posts=posts)
| from flask import render_template
from flask_classy import FlaskView
from ..models import PostModel
class Main(FlaskView):
""" Main page view. """
route_base = "/"
def index(self):
PostModel.set_query()
PostModel.query.order = ['-updated', 'title']
posts = PostModel.fetch()
... | Set index main view to return post ordered by updated and title field | Set index main view to return post ordered by updated and title field
| Python | mit | oldani/nanodegree-blog,oldani/nanodegree-blog,oldani/nanodegree-blog |
b103c02815a7819e9cb4f1cc0061202cfcfd0fa6 | bidb/api/views.py | bidb/api/views.py | from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from .utils import parse_submission, InvalidSubmission
@csrf_exempt
@require_http_methods(['PUT'])
def submi... | from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from .utils import parse_submission, InvalidSubmission
@csrf_exempt
@require_http_methods(['PUT'])
def submi... | Make it clearer that we are rejecting the submission. | Make it clearer that we are rejecting the submission.
| Python | agpl-3.0 | lamby/buildinfo.debian.net,lamby/buildinfo.debian.net |
e5e61e4d2575a39d585b3c51c082b2b53bade7bb | django_sphinx_db/backend/sphinx/base.py | django_sphinx_db/backend/sphinx/base.py | from django.db.backends.mysql.base import DatabaseWrapper as MySQLDatabaseWrapper
from django.db.backends.mysql.base import DatabaseOperations as MySQLDatabaseOperations
from django.db.backends.mysql.creation import DatabaseCreation as MySQLDatabaseCreation
class SphinxOperations(MySQLDatabaseOperations):
compile... | from django.db.backends.mysql.base import DatabaseWrapper as MySQLDatabaseWrapper
from django.db.backends.mysql.base import DatabaseOperations as MySQLDatabaseOperations
from django.db.backends.mysql.creation import DatabaseCreation as MySQLDatabaseCreation
class SphinxOperations(MySQLDatabaseOperations):
compile... | Speed up unit tests when Sphinx DB is configured | Speed up unit tests when Sphinx DB is configured
| Python | bsd-3-clause | smartfile/django-sphinx-db,rutube/django-sphinx-db,anatoliy-larin/django-sphinx-db,jnormore/django-sphinx-db,petekalo/django-sphinx-db |
88f0c284b01bf5b4545fe63bdd1fde7cc66ad937 | us_ignite/apps/admin.py | us_ignite/apps/admin.py | from django.contrib import admin
from us_ignite.apps.models import (Application, ApplicationURL,
ApplicationImage, Domain, Feature)
class ApplicationURLInline(admin.TabularInline):
model = ApplicationURL
class ApplicationImageInline(admin.TabularInline):
model = Applicati... | from django.contrib import admin
from us_ignite.apps.models import (Application, ApplicationURL,
ApplicationImage, Domain, Feature,
Page, PageApplication)
class ApplicationURLInline(admin.TabularInline):
model = ApplicationURL
class Applicat... | Add admi to add Applications to the Pages. | Add admi to add Applications to the Pages.
https://github.com/madewithbytes/us_ignite/issues/79
The applications can be added to a page and ordered
in the admin.
| Python | bsd-3-clause | us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite |
a9bb32b91e2b742705b6292bd52fc869a8130766 | dymport/import_file.py | dymport/import_file.py | """
Various functions to dynamically import (abitrary names from) arbitrary files.
To import a file like it is a module, use `import_file`.
"""
from importlib.util import module_from_spec, spec_from_file_location
def import_file(name, file):
"""
Import `file` as a module with _name_.
Raises an ImportEr... | """
Various functions to dynamically import (abitrary names from) arbitrary files.
To import a file like it is a module, use `import_file`.
"""
from sys import version_info
def import_file(name, file):
"""
Import `file` as a module with _name_.
Raises an ImportError if it could not be imported.
"""... | Add check for supported Python versions | Add check for supported Python versions
Not all Python versions are supported by this package, because the import
mechanism changes in the different Python versions.
If an unsupported Python version is used, an ImportError is raised.
| Python | mit | ErwinJanssen/dymport.py |
bf5532f405df8869b4869c2d839e6093ebf963bc | wisp/utils.py | wisp/utils.py | import importlib
import importlib.machinery
import sys
from module import Module
import json
def message_to_function(raw_message):
"""
converting json formatted string to a executable module.
Args:
raw_message (str): json formatted.
Returns:
None if raw_message is in wrong format, ... | import importlib
import importlib.machinery
import sys
from module import Module
import json
def message_to_function(raw_message):
"""
converting json formatted string to a executable module.
Args:
raw_message (str): json formatted.
Returns:
None if raw_message is in wrong format, ... | Fix errors cause by key error in sys.modules and wrong type error by uFid. | Fix errors cause by key error in sys.modules and wrong type error by uFid.
| Python | apache-2.0 | hoonkim/rune,hoonkim/rune,hoonkim/rune |
4a5e798fe23d720315a7cab60824b70ce0983f8e | Kane1985/Chapter2/Ex4.1.py | Kane1985/Chapter2/Ex4.1.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Exercise 4.1 from Kane 1985"""
from sympy.physics.mechanics import dot, dynamicsymbols, MechanicsStrPrinter
from sympy.physics.mechanics import ReferenceFrame, Point
from sympy import solve, symbols, pi
from sympy.simplify.simplify import trigsimp
def msprint(expr):
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Exercise 4.1 from Kane 1985"""
from sympy.physics.mechanics import dot, dynamicsymbols, MechanicsStrPrinter
from sympy.physics.mechanics import ReferenceFrame, Point
from sympy import solve, symbols, pi, sin, cos
from sympy.simplify.simplify import trigsimp
def msprint... | Simplify formulation and change from print() to assert() | Simplify formulation and change from print() to assert()
| Python | bsd-3-clause | jcrist/pydy,Shekharrajak/pydy,oliverlee/pydy,jcrist/pydy,jcrist/pydy,oliverlee/pydy,jcrist/pydy,Shekharrajak/pydy,oliverlee/pydy,jcrist/pydy,Shekharrajak/pydy,jcrist/pydy,skidzo/pydy,Shekharrajak/pydy,skidzo/pydy,skidzo/pydy,jcrist/pydy,skidzo/pydy |
d4e3609cf6f749d6ac95bc8332844f63b61b41b1 | oslo/__init__.py | oslo/__init__.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | Remove extraneous vim editor configuration comments | Remove extraneous vim editor configuration comments
Change-Id: I173c838765efd527b3bc652d9b8c32ac89c756b6
Partial-Bug: #1229324
| Python | apache-2.0 | varunarya10/oslo.serialization,openstack/oslo.serialization |
d961c644f74d83150e3f5a3ea9599af0d2b839ae | hash_table.py | hash_table.py | #!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self):
pass
class Hash(object):
def __init__(self):
... | #!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self):
pass
class Hash(object):
def __init__(self, size=1024... | Build out init function of hash table class | Build out init function of hash table class
| Python | mit | jwarren116/data-structures-deux |
0b41bdf6897bb070fc3d90aa5d90228e744dee60 | sunpy/util/map_manager.py | sunpy/util/map_manager.py | import weakref
import sunpy
class MapManager(weakref.WeakSet):
"""Weak referenced set of maps created using functions decorated by manage_maps."""
def __repr__(self):
return str(self.data)
def manage_maps(fn):
"""Maps returned by functions decorated with manage_maps (eg. sunpy.make_map)
will ... | import weakref
import sunpy
class MapManager(weakref.WeakSet):
"""Weak referenced set of maps created using functions decorated by manage_maps."""
pass
def manage_maps(fn):
"""Maps returned by functions decorated with manage_maps (eg. sunpy.make_map)
will be registered in the sunpy.map_manager list.""... | Remove manager repr (user should not need to view contents) | Remove manager repr (user should not need to view contents)
| Python | bsd-2-clause | mjm159/sunpy,dpshelio/sunpy,dpshelio/sunpy,Alex-Ian-Hamilton/sunpy,dpshelio/sunpy,Alex-Ian-Hamilton/sunpy,Alex-Ian-Hamilton/sunpy,mjm159/sunpy |
c4dd6502bc7b9d5970a659c57e6aa2d25cc00fe5 | catwatch/lib/util_datetime.py | catwatch/lib/util_datetime.py | import datetime
def timedelta_months(months, compare_date=None):
"""
Return a JSON response.
:param months: Amount of months to offset
:type months: int
:param compare_date: Date to compare at
:type compare_date: date
:return: Flask response
"""
if compare_date is None:
co... | import datetime
def timedelta_months(months, compare_date=None):
"""
Return a new datetime with a month offset applied.
:param months: Amount of months to offset
:type months: int
:param compare_date: Date to compare at
:type compare_date: date
:return: datetime
"""
if compare_dat... | Update timedelta_months docstring to be accurate | Update timedelta_months docstring to be accurate
| Python | mit | z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask |
4a528978e9a783b9fb4f25d31a32a2ca524d7ce1 | infosystem/subsystem/domain/resource.py | infosystem/subsystem/domain/resource.py | from infosystem.database import db
from infosystem.common.subsystem import entity
class Domain(entity.Entity, db.Model):
attributes = ['name', 'parent_id']
attributes += entity.Entity.attributes
name = db.Column(db.String(60), nullable=False, unique=True)
parent_id = db.Column(
db.CHAR(32), ... | from infosystem.database import db
from infosystem.common.subsystem import entity
class Domain(entity.Entity, db.Model):
attributes = ['name', 'parent_id']
attributes += entity.Entity.attributes
name = db.Column(db.String(60), nullable=False, unique=True)
parent_id = db.Column(
db.CHAR(32), ... | Change attributes order on constructor | Change attributes order on constructor
| Python | apache-2.0 | samueldmq/infosystem |
3ee00fad1965dae23f83da870d7df1cb37727c7a | structlog/migrations/0001_initial.py | structlog/migrations/0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-10 14:33
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-10 14:33
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.postgres.operations import HStoreExtension
class Migration(migrations.Migration):
dependencies = [
]
operations = [
HStoreExten... | Add HStore extension to initial migration. | Add HStore extension to initial migration.
| Python | bsd-2-clause | carlohamalainen/django-struct-log |
8ecf9d95cf7f085b0245b07422ccda007937a5c6 | visu3d/array_dataclass.py | visu3d/array_dataclass.py | # Copyright 2022 The visu3d Authors.
#
# 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 w... | # Copyright 2022 The visu3d Authors.
#
# 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 w... | Add `@dca.dataclass_array` decorator to customize dca params. Change default values | Add `@dca.dataclass_array` decorator to customize dca params. Change default values
PiperOrigin-RevId: 475563717
| Python | apache-2.0 | google-research/visu3d |
fb10e4b8ae37f1442bdb643c27ea0b984da6a374 | cherrypy/test/test_httputil.py | cherrypy/test/test_httputil.py | """Tests for cherrypy/lib/httputil.py."""
import unittest
from cherrypy.lib import httputil
class UtilityTests(unittest.TestCase):
def test_urljoin(self):
# Test all slash+atom combinations for SCRIPT_NAME and PATH_INFO
self.assertEqual(httputil.urljoin('/sn/', '/pi/'), '/sn/pi/')
self.a... | """Tests for ``cherrypy.lib.httputil``."""
import pytest
from cherrypy.lib import httputil
class TestUtility(object):
@pytest.mark.parametrize(
'script_name,path_info,expected_url',
[
('/sn/', '/pi/', '/sn/pi/'),
('/sn/', '/pi', '/sn/pi'),
('/sn/', '/', '/sn/')... | Rewrite httputil test module via pytest | Rewrite httputil test module via pytest
| Python | bsd-3-clause | cherrypy/cherrypy,Safihre/cherrypy,Safihre/cherrypy,cherrypy/cherrypy |
638d7f38a0e22f72680437372b873d69ead973b1 | config/run_distutils/__init__.py | config/run_distutils/__init__.py | from SCons.Script import *
def generate(env):
env.SetDefault(RUN_DISTUTILS = 'python')
env.SetDefault(RUN_DISTUTILSOPTS = 'build')
env['RUN_DISTUTILS'] = 'python'
env['RUN_DISTUTILSOPTS'] = 'build'
bld = Builder(action = '$RUN_DISTUTILS $SOURCE $RUN_DISTUTILSOPTS')
env.Append(BUILDERS = {'Ru... | from SCons.Script import *
import os
def generate(env):
env.SetDefault(RUN_DISTUTILS = 'python')
env.SetDefault(RUN_DISTUTILSOPTS = 'build')
if 'RUN_DISTUTILS' in os.environ:
env['RUN_DISTUTILS'] = os.environ['RUN_DISTUTILS']
if 'RUN_DISTUTILSOPTS' in os.environ:
env['RUN_DISTUTILSOPT... | Allow env vars for RUN_DISTUTILS | Allow env vars for RUN_DISTUTILS
Allow use of env vars RUN_DISTUTILS, RUN_DISTUTILOPTS as defaults.
With this, on macos, macports doesn't need to be in PATH to build FAHControl. One just needs
export RUN_DISTUTILS="/opt/local/bin/python"
or the equivalent in dockbot.json env.
| Python | lgpl-2.1 | CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang |
4da79cbec5880da6fb16b5a474786247a820d09c | nowplaying.py | nowplaying.py | #!/usr/bin/env python
from termcolor import colored
from appscript import *
from track import Track
def main():
print(get_song())
def get_song():
itunes_open = bool(app('System Events').processes[its.name == 'iTunes'].count())
if itunes_open: # check if application open
itunes = app('iTunes')
... | #!/usr/bin/env python
from termcolor import colored
from appscript import *
from track import Track
def main():
print(get_song())
def get_song():
itunes_open = bool(app('System Events').processes[its.name == 'iTunes'].count())
if itunes_open: # check if application open
itunes = app('iTunes')
... | Return error instead of if/else | Return error instead of if/else
| Python | mit | kshvmdn/nowplaying |
54cfb9864256b27b9f4cd411f170cc12d47727e5 | appengine/components/components/machine_provider/dimensions.py | appengine/components/components/machine_provider/dimensions.py | # Copyright 2015 The LUCI Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Dimensions for the Machine Provider."""
from protorpc import messages
class Backend(messages.Enum):
"""Lists valid backends."""
DUMMY = 0
GCE = 1... | # Copyright 2015 The LUCI Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Dimensions for the Machine Provider."""
from protorpc import messages
class Backend(messages.Enum):
"""Lists valid backends."""
DUMMY = 0
GCE = 1... | Add enum field for vSphere backend | Add enum field for vSphere backend
Review-Url: https://codereview.chromium.org/1997903002
| Python | apache-2.0 | luci/luci-py,luci/luci-py,luci/luci-py,luci/luci-py |
020b2518efce2d973093a366e0a9abfadbd602fd | main/forms.py | main/forms.py | from django import forms
class IndexForm(forms.Form):
usos_auth_pin = forms.IntegerField(label='USOS Authorization PIN')
id_list = forms.CharField(
widget=forms.Textarea, label='ID List',
help_text='List of students IDs to query, one per line.')
student_id_regex = forms.CharField(
... | from django import forms
class IndexForm(forms.Form):
usos_auth_pin = forms.IntegerField(
label='USOS Authorization PIN',
help_text='If not filled out, then only the cache is used. Note that '
'this means that some IDs may fail to be looked up.',
required=False)
id_li... | Add help_text and required=False to the PIN field | Add help_text and required=False to the PIN field
| Python | mit | m4tx/usos-id-mapper,m4tx/usos-id-mapper |
3e1408affa823af2ed95decf52b002614d060a26 | pombola/core/tests/test_templatetags.py | pombola/core/tests/test_templatetags.py |
from django.test import TestCase
from ..templatetags.breadcrumbs import breadcrumbs
class BreadcrumbTest(TestCase):
def test_breadcrumbs(self):
"""Check that the breadcrumbs are generated as expected"""
home_li = '<li><a href="/" title="Breadcrumb link to the homepage.">Home</a> <span class="... |
from django.test import TestCase
from ..templatetags.breadcrumbs import breadcrumbs
from ..templatetags.active_class import active_class
class BreadcrumbTest(TestCase):
def test_breadcrumbs(self):
"""Check that the breadcrumbs are generated as expected"""
home_li = '<li><a href="/" title="Bre... | Add tests for active_class templatetag | Add tests for active_class templatetag
| Python | agpl-3.0 | hzj123/56th,geoffkilpin/pombola,hzj123/56th,geoffkilpin/pombola,mysociety/pombola,hzj123/56th,mysociety/pombola,hzj123/56th,geoffkilpin/pombola,hzj123/56th,patricmutwiri/pombola,patricmutwiri/pombola,mysociety/pombola,geoffkilpin/pombola,patricmutwiri/pombola,ken-muturi/pombola,ken-muturi/pombola,mysociety/pombola,ken-... |
1421dd89b74bf753cf0b52a5e6fe200d221922b5 | pirx/utils.py | pirx/utils.py | import os
def setting(name):
return name.upper()
def path(subpath):
project_root = os.path.dirname(os.path.realpath(__file__))
return os.path.join(project_root, subpath)
| import os
def setting(name):
return name.upper()
def path(subpath):
import __main__
project_root = os.path.dirname(os.path.realpath(__main__.__file__))
return os.path.join(project_root, subpath)
| Fix 'path' function: use main's file as project root | Fix 'path' function: use main's file as project root
| Python | mit | piotrekw/pirx |
662046497abfa6f7f6553aeb266a261637ba6407 | numba/postpasses.py | numba/postpasses.py | # -*- coding: utf-8 -*-
"""
Postpasses over the LLVM IR.
The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc
"""
from __future__ import print_function, division, absolute_import
from numba.support.math_support import math_support, libs
default_postpasses = {}
def register_default(name):
d... | # -*- coding: utf-8 -*-
"""
Postpasses over the LLVM IR.
The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc
"""
from __future__ import print_function, division, absolute_import
from numba.support.math_support import linking, libs
default_postpasses = {}
def register_default(name):
def de... | Clean up old test, pass all tests | Clean up old test, pass all tests
| Python | bsd-2-clause | jriehl/numba,jriehl/numba,stefanseefeld/numba,seibert/numba,gdementen/numba,sklam/numba,pitrou/numba,stefanseefeld/numba,stuartarchibald/numba,stonebig/numba,numba/numba,GaZ3ll3/numba,ssarangi/numba,sklam/numba,cpcloud/numba,sklam/numba,ssarangi/numba,stonebig/numba,gdementen/numba,pombredanne/numba,GaZ3ll3/numba,seibe... |
b44b0f68a2dd00df1ec074cf39a66ce81cd0dae2 | nowplaying.py | nowplaying.py | #!/usr/bin/env python
from termcolor import colored
from appscript import *
from track import Track
def main():
print(get_song())
def get_song():
itunes_open = bool(app('System Events').processes[its.name == 'iTunes'].count())
if itunes_open: # check if application open
itunes = app('iTunes')
... | #!/usr/bin/env python
from termcolor import colored
from appscript import *
from track import Track
def main():
print(get_song())
def get_song():
itunes_open = bool(app('System Events').processes[its.name == 'iTunes'].count())
if itunes_open: # check if application open
itunes = app('iTunes')
... | Update error output for app not open/song not playing | Update error output for app not open/song not playing
| Python | mit | kshvmdn/nowplaying |
3c8067a1b8fb3463fa4c45a6f03c8dc0fbf918b3 | organizer/models.py | organizer/models.py | from django.db import models
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Tag(models.Model):
name = models.CharField(
max_length=31, unique=True)
slug = models.SlugField(
max_length=31,
unique=True,
help_text='A label for URL config... | from django.db import models
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Tag(models.Model):
name = models.CharField(
max_length=31, unique=True)
slug = models.SlugField(
max_length=31,
unique=True,
help_text='A label for URL config... | Declare Meta class in Tag model. | Ch03: Declare Meta class in Tag model. [skip ci]
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 |
4858a17940ec4b4425f743813c0c1ecef391d967 | tests/test_file_handling.py | tests/test_file_handling.py | # -*- coding: utf-8 -*-
"""
format-sql
Copyright (c) 2014, Friedrich Paetzke (paetzke@fastmail.fm)
All rights reserved.
"""
import os
from format_sql.file_handling import format_file, load_from_file, main
def get_test_file(filename):
test_data = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
f... | # -*- coding: utf-8 -*-
"""
format-sql
Copyright (c) 2014, Friedrich Paetzke (paetzke@fastmail.fm)
All rights reserved.
"""
import os
import sys
from format_sql.file_handling import format_file, load_from_file, main
try:
from unittest.mock import patch
except ImportError:
from mock import patch
def get_te... | Add test for file iteration | Add test for file iteration
| Python | bsd-2-clause | paetzke/format-sql |
16214545b301aaba4847ffae5efe67782abe993d | toolz/tests/test_curried.py | toolz/tests/test_curried.py | import toolz
import toolz.curried
from toolz.curried import take, first, second, sorted, merge_with, reduce
from operator import add
def test_take():
assert list(take(2)([1, 2, 3])) == [1, 2]
def test_first():
assert first is toolz.itertoolz.first
def test_merge_with():
assert merge_with(sum)({1: 1}, ... | import toolz
import toolz.curried
from toolz.curried import (take, first, second, sorted, merge_with, reduce,
merge)
from collections import defaultdict
from operator import add
def test_take():
assert list(take(2)([1, 2, 3])) == [1, 2]
def test_first():
assert first is toolz.iter... | Add tests for curried merge | Add tests for curried merge
| Python | bsd-3-clause | machinelearningdeveloper/toolz,llllllllll/toolz,jdmcbr/toolz,llllllllll/toolz,pombredanne/toolz,machinelearningdeveloper/toolz,simudream/toolz,jcrist/toolz,cpcloud/toolz,quantopian/toolz,jcrist/toolz,jdmcbr/toolz,pombredanne/toolz,cpcloud/toolz,simudream/toolz,quantopian/toolz |
43d4b6a3ccf49b3a0307da98344b0fe8f61acaf1 | brew/rest.py | brew/rest.py | import json
import time
import jsonschema
from pkg_resources import resource_string
from flask import request, jsonify
from brew import app, controller, machine, mongo
@app.route('/api/recipe', methods=['POST'])
def create_recipe():
schema = resource_string(__name__, 'data/recipe.schema.json').decode('utf-8')
... | import json
import time
import jsonschema
from pkg_resources import resource_string
from flask import request, jsonify
from brew import app, controller, machine, mongo
@app.route('/api/recipe', methods=['POST'])
def create_recipe():
schema = resource_string(__name__, 'data/recipe.schema.json').decode('utf-8')
... | Save malts for future reference | Save malts for future reference
| Python | mit | brewpeople/brewmeister,brewpeople/brewmeister,brewpeople/brewmeister |
344457b498f12dfceb8e687b326ba68064d6bda6 | run-tests.py | run-tests.py |
import os
PROJECT_DIR = os.path.abspath(os.path.dirname( __file__ ))
SRC_DIR = os.path.join(PROJECT_DIR, "src")
TEST_DIR = os.path.join(PROJECT_DIR, "test")
def runtestdir(subdir):
#cwd = os.getcwd()
#subdir = os.path.join(cwd, subdir)
entries = os.listdir(subdir)
total = 0
errs = 0
... |
import os, sys
PROJECT_DIR = os.path.abspath(os.path.dirname( __file__ ))
SRC_DIR = os.path.join(PROJECT_DIR, "src")
TEST_DIR = os.path.join(PROJECT_DIR, "test")
def runtestdir(subdir):
entries = os.listdir(subdir)
total = 0
errs = 0
for f in entries:
if not f.endswith(".py"):
... | Test runner uses current python | Test runner uses current python | Python | mit | divtxt/binder |
e5f00a6a5e71d8f5fe98547732f4c9e15a3efc1e | src/nodeconductor_paas_oracle/apps.py | src/nodeconductor_paas_oracle/apps.py | from django.apps import AppConfig
class OracleConfig(AppConfig):
name = 'nodeconductor_paas_oracle'
verbose_name = 'Oracle'
service_name = 'Oracle'
def ready(self):
from nodeconductor.structure import SupportedServices
from .backend import OracleBackend
SupportedServices.regis... | from django.apps import AppConfig
class OracleConfig(AppConfig):
name = 'nodeconductor_paas_oracle'
verbose_name = 'Oracle'
service_name = 'Oracle'
def ready(self):
from nodeconductor.structure import SupportedServices
from nodeconductor.cost_tracking import CostTrackingRegister
... | Add registration to cost tracking | Add registration to cost tracking
| Python | mit | opennode/nodeconductor-paas-oracle |
d3438e85ab4158d769b0662729a8aff7d143971a | csv_ical/tests/test_convert.py | csv_ical/tests/test_convert.py | import unittest
from csv_ical import convert
class TestConvert(unittest.TestCase):
def setUp(self):
self.convert = convert.Convert()
def test_generate_configs(self):
self.convert._generate_configs_from_default()
| import datetime
import os
import tempfile
import unittest
from syspath import get_git_root
from csv_ical import convert
EXAMPLE_ICS = os.path.join(get_git_root(), 'examples', 'arrive.ics')
EXAMPLE_CSV = os.path.join(get_git_root(), 'examples', 'BostonCruiseTerminalSchedule.csv')
CSV_CONFIGS = {
'HEADER_COLUMNS_T... | Add tests for all methods | Add tests for all methods
| Python | mit | albertyw/csv-to-ical |
f5fd74dac54f657cc64fdaa0b838b00b72ce5ee6 | dev/make-release-notes.py | dev/make-release-notes.py | #! /usr/bin/env python3
import re
import sys
_, VERSION, CHANGELOG, LIST = sys.argv
HEADER_REGEX = fr"# {VERSION} \(\d\d\d\d-\d\d-\d\d\)\n"
notes_list = []
def add_to_release_notes(line):
assert line.endswith("."), line
notes_list.append(f"* {line}\n")
with open(CHANGELOG) as f:
first_line = next(f)
... | #! /usr/bin/env python3
import re
import sys
_, VERSION, CHANGELOG, LIST = sys.argv
HEADER_REGEX = fr"# {VERSION} \(\d\d\d\d-\d\d-\d\d\)\n"
notes_list = []
def add_to_release_notes(line):
assert line.endswith("."), line
with open(CHANGELOG) as f:
first_line = next(f)
if not re.match(HEADER_REGEX, fi... | Allow line breaks in changelog. | Allow line breaks in changelog.
| Python | mit | jendrikseipp/vulture,jendrikseipp/vulture |
c88efde14ea79419a69a3459b5ba9ba19332fffd | python/algorithms/sorting/quicksort.py | python/algorithms/sorting/quicksort.py | import random
def sort(items):
if items is None:
raise TypeError("Collection cannot be of type None")
if len(items) < 2:
return items
pivot = random.randint(0, len(items) - 1)
greater = []
less = []
for index in range(0, len(items)):
if index == pivot:
c... | import random
def sort(items):
if items is None:
raise TypeError("Collection cannot be of type None")
if len(items) < 2:
return items
pivot = random.randint(0, len(items) - 1)
greater = []
less = []
for index in range(0, len(items)):
if index == pivot:
c... | Move redundant check to first point of contact | Move redundant check to first point of contact
| Python | mit | vilisimo/ads,vilisimo/ads |
f9c654a60501ef734de178e7e2e7e89955eb39e0 | jesusmtnez/python/koans/koans/about_list_assignments.py | jesusmtnez/python/koans/koans/about_list_assignments.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutArrayAssignments in the Ruby Koans
#
from runner.koan import *
class AboutListAssignments(Koan):
def test_non_parallel_assignment(self):
names = ["John", "Smith"]
self.assertEqual(__, names)
def test_parallel_assignments(self):
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutArrayAssignments in the Ruby Koans
#
from runner.koan import *
class AboutListAssignments(Koan):
def test_non_parallel_assignment(self):
names = ["John", "Smith"]
self.assertEqual(["John", "Smith"], names)
def test_parallel_assi... | Complete 'About Lists Assignments' koans | [Python] Complete 'About Lists Assignments' koans
| Python | mit | JesusMtnez/devexperto-challenge,JesusMtnez/devexperto-challenge |
7d1c3ca61fb11aae181fb15d4ab825dfe9c2e710 | runtime/__init__.py | runtime/__init__.py | import builtins
import operator
import functools
import importlib
# Choose a function based on the number of arguments.
varary = lambda *fs: lambda *xs: fs[len(xs) - 1](*xs)
builtins.__dict__.update({
# Runtime counterparts of some stuff in `Compiler.builtins`.
'$': lambda f, *xs: f(*xs)
, ':': lambda f, ... | import builtins
import operator
import functools
import importlib
# Choose a function based on the number of arguments.
varary = lambda *fs: lambda *xs: fs[len(xs) - 1](*xs)
builtins.__dict__.update({
# Runtime counterparts of some stuff in `Compiler.builtins`.
'$': lambda f, *xs: f(*xs)
, ':': lambda f, ... | Add support for ... (`Ellipsis`). | Add support for ... (`Ellipsis`).
Note that it is still considered an operator, so stuff like `a ... b` means "call ... with a and b".
| Python | mit | pyos/dg |
ad16e07cce92c0ed23e5e82c60a00f04dabce2a3 | rna-transcription/rna_transcription.py | rna-transcription/rna_transcription.py | DNA = {"A", "C", "T", "G"}
TRANS = {"G": "C", "C":"G", "T":"A", "A":"U"}
def to_rna(dna):
# Check validity - `difference` returns elements in dna not in DNA
if set(dna).difference(DNA):
return ""
return "".join([TRANS[n] for n in dna])
| TRANS = {"G": "C", "C":"G", "T":"A", "A":"U"}
def to_rna(dna):
try:
return "".join([TRANS[n] for n in dna])
except KeyError:
return ""
# Old version: it's slightly slower for valid DNA, but slightly faster for invalid DNA
DNA = {"A", "C", "T", "G"}
TRANS = {"G": "C", "C":"G", "T":"A", "A":"... | Add an exception based version | Add an exception based version
| Python | agpl-3.0 | CubicComet/exercism-python-solutions |
81aa35961ba9552701eecbdb4d8e91448835aba0 | django_autologin/utils.py | django_autologin/utils.py | import urllib
import urlparse
from . import app_settings
def strip_token(url):
bits = urlparse.urlparse(url)
original_query = urlparse.parse_qsl(bits.query)
query = {}
for k, v in original_query:
if k != app_settings.KEY:
query[k] = v
query = urllib.urlencode(query)
retu... | import urllib
import urlparse
from django.conf import settings
from django.contrib import auth
from . import app_settings
def strip_token(url):
bits = urlparse.urlparse(url)
original_query = urlparse.parse_qsl(bits.query)
query = {}
for k, v in original_query:
if k != app_settings.KEY:
... | Make login a utility so it can be re-used elsewhere. | Make login a utility so it can be re-used elsewhere.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@playfire.com>
| Python | bsd-3-clause | playfire/django-autologin |
ac30d4e6434c6c8bbcb949465a3e314088b3fc12 | jsonfield/utils.py | jsonfield/utils.py | import datetime
from decimal import Decimal
from django.core.serializers.json import DjangoJSONEncoder
DATETIME = (datetime.datetime,)
DATE = (datetime.date,)
TIME = (datetime.time,)
try:
import freezegun.api
except ImportError:
pass
else:
DATETIME += (freezegun.api.FakeDatetime,)
DATE += (freezegun.... | import datetime
from decimal import Decimal
from django.core.serializers.json import DjangoJSONEncoder
class TZAwareJSONEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.strftime("%Y-%m-%d %H:%M:%S%z")
return super(TZAwareJSONEncoder,... | Revert changes: freezegun has been updated. | Revert changes: freezegun has been updated.
| Python | bsd-3-clause | SideStudios/django-jsonfield |
a0c0499c3da95e53e99d6386f7970079a2669141 | app/twitter/views.py | app/twitter/views.py | from flask import Blueprint, request, render_template
from ..load import processing_results, api
import string
import tweepy
twitter_mod = Blueprint('twitter', __name__, template_folder='templates', static_folder='static')
ascii_chars = set(string.printable)
ascii_chars.remove(' ')
ascii_chars.add('...')
def takeo... | from flask import Blueprint, request, render_template
from ..load import processing_results, api
import string
import tweepy
twitter_mod = Blueprint('twitter', __name__, template_folder='templates', static_folder='static')
ascii_chars = set(string.printable)
ascii_chars.remove(' ')
ascii_chars.add('...')
def takeout... | Add exception handling in twitter view | Add exception handling in twitter view
| Python | mit | griimick/feature-mlsite,griimick/feature-mlsite,griimick/feature-mlsite |
d26b2fd19b048d3720d757ba850d88b683d4b367 | st2common/st2common/runners/__init__.py | st2common/st2common/runners/__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... | Add functions for retrieving a list of dynamically registered runners. | Add functions for retrieving a list of dynamically registered runners.
Those functions match same functions exposed by the auth backend loading
functionality.
| Python | apache-2.0 | StackStorm/st2,StackStorm/st2,Plexxi/st2,nzlosh/st2,StackStorm/st2,StackStorm/st2,Plexxi/st2,Plexxi/st2,Plexxi/st2,nzlosh/st2,nzlosh/st2,nzlosh/st2 |
b4d3fbb0535074f2153b2b9bad53fdf654ddedd1 | src/python/borg/tools/bench_bellman.py | src/python/borg/tools/bench_bellman.py | """
@author: Bryan Silverthorn <bcs@cargo-cult.org>
"""
if __name__ == "__main__":
from borg.tools.bench_bellman import main
raise SystemExit(main())
def main():
"""
Benchmark the Bellman plan computation code.
"""
# need a place to dump profiling results
from tempfile import NamedTempor... | """
@author: Bryan Silverthorn <bcs@cargo-cult.org>
"""
if __name__ == "__main__":
from borg.tools.bench_bellman import main
raise SystemExit(main())
def main():
"""
Benchmark the Bellman plan computation code.
"""
from borg.portfolio.bellman import compute_bellman_plan
from bo... | Clean up the Bellman benchmarking code. | Clean up the Bellman benchmarking code.
| Python | mit | borg-project/borg |
37eeecd3d4d1e6d2972565961b5c31731ae55ec7 | tests/tester.py | tests/tester.py | import os
from unittest import TestCase
from servequnit.factory import ServerFactory
from servequnit.tester import QunitSeleniumTester, TestFailedError
class QunitSeleniumTesterTestCase(TestCase):
def _make_tester(self, server, suffix=None):
suffix = suffix or "oneshot/"
url = server.url + suffix
... | import os
from unittest import TestCase
from servequnit.factory import ServerFactory
from servequnit.tester import QunitSeleniumTester, TestFailedError
class QunitSeleniumTesterTestCase(TestCase):
def _make_tester(self, server, suffix=None):
suffix = suffix or "oneshot/"
url = server.url + suffix
... | Test the an empty document results in a test failure. | Test the an empty document results in a test failure.
| Python | mit | bnkr/servequnit,bnkr/servequnit,bnkr/servequnit,bnkr/selenit,bnkr/selenit |
4027cccb929308528666e1232eeebfc1988e0ab1 | tests/iam/test_iam_valid_json.py | tests/iam/test_iam_valid_json.py | """Test IAM Policy templates are valid JSON."""
import jinja2
from foremast.iam.construct_policy import render_policy_template
from foremast.utils.templates import LOCAL_TEMPLATES
def test_all_iam_templates():
"""Verify all IAM templates render as proper JSON."""
jinjaenv = jinja2.Environment(loader=jinja2.F... | """Test IAM Policy templates are valid JSON."""
import jinja2
from foremast.iam.construct_policy import render_policy_template
from foremast.utils.templates import LOCAL_TEMPLATES
def iam_templates():
"""Generate list of IAM templates."""
jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TE... | Use generator for IAM template names | test: Use generator for IAM template names
See also: #208
| Python | apache-2.0 | gogoair/foremast,gogoair/foremast |
8f0caecc4accf8258e2cae664181680973e1add6 | hftools/dataset/tests/test_helper.py | hftools/dataset/tests/test_helper.py | # -*- coding: ISO-8859-1 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2014, HFTools Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#---------------------... | # -*- coding: ISO-8859-1 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2014, HFTools Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#---------------------... | Fix to remove DeprecationWarning message from test log | Fix to remove DeprecationWarning message from test log
| Python | bsd-3-clause | hftools/hftools |
f5983348940e3acf937c7ddfded73f08d767c5a1 | j1a/verilator/setup.py | j1a/verilator/setup.py | from distutils.core import setup
from distutils.extension import Extension
from os import system
setup(name='vsimj1a',
ext_modules=[
Extension('vsimj1a',
['vsim.cpp'],
depends=["obj_dir/Vv3__ALL.a"],
extra_objects=["obj_dir/verilated.o", "obj_dir/Vj1a__ALL.a"],
... | from distutils.core import setup
from distutils.extension import Extension
from os import system
setup(name='vsimj1a',
ext_modules=[
Extension('vsimj1a',
['vsim.cpp'],
depends=["obj_dir/Vv3__ALL.a"],
extra_objects=["obj_dir/verilated.o", "obj_dir/Vj1a__ALL.a"],
... | Add vltstd to include path | Add vltstd to include path
| Python | bsd-3-clause | jamesbowman/swapforth,zuloloxi/swapforth,uho/swapforth,uho/swapforth,zuloloxi/swapforth,GuzTech/swapforth,jamesbowman/swapforth,jamesbowman/swapforth,GuzTech/swapforth,uho/swapforth,RGD2/swapforth,zuloloxi/swapforth,RGD2/swapforth,GuzTech/swapforth,zuloloxi/swapforth,GuzTech/swapforth,uho/swapforth,RGD2/swapforth,james... |
0f7732d3ceb67ecd445bb4fe2fee1edf4ce8a2f4 | rock/utils.py | rock/utils.py | from __future__ import unicode_literals
import os
try:
from io import StringIO
except ImportError: # pragma: no cover
from StringIO import StringIO
from rock.exceptions import ConfigError
ROCK_SHELL = (os.environ.get('ROCK_SHELL') or '/bin/bash -c').split()
ROCK_SHELL.insert(1, os.path.basename(ROCK_SHELL[0]... | from __future__ import unicode_literals
import os
try:
from io import StringIO
except ImportError: # pragma: no cover
from StringIO import StringIO
from rock.exceptions import ConfigError
ROCK_SHELL = (os.environ.get('ROCK_SHELL') or '/bin/bash -c').split()
ROCK_SHELL.insert(1, os.path.basename(ROCK_SHELL[0]... | Tweak raw text parameter name | Tweak raw text parameter name
| Python | mit | silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock |
c7b684ebf85e2a80e0acdd44ea91171bc1aa6388 | jarbas/chamber_of_deputies/fields.py | jarbas/chamber_of_deputies/fields.py | from datetime import date
from rows import fields
class IntegerField(fields.IntegerField):
@classmethod
def deserialize(cls, value, *args, **kwargs):
try: # Rows cannot convert values such as '2011.0' to integer
value = int(float(value))
except:
pass
return s... | from rows import fields
class IntegerField(fields.IntegerField):
@classmethod
def deserialize(cls, value, *args, **kwargs):
try: # Rows cannot convert values such as '2011.0' to integer
value = int(float(value))
except:
pass
return super(IntegerField, cls).des... | Make date imports more flexible | Make date imports more flexible
Now ut works with `YYYY-MM-DD HH:MM:SS` and with `YYYY-MM-DDTHH:MM:SS`.
| Python | mit | datasciencebr/serenata-de-amor,datasciencebr/jarbas,marcusrehm/serenata-de-amor,datasciencebr/jarbas,datasciencebr/jarbas,marcusrehm/serenata-de-amor,datasciencebr/jarbas,marcusrehm/serenata-de-amor,datasciencebr/serenata-de-amor,marcusrehm/serenata-de-amor |
7f79e575b9a2b5dc15ed304e2c1cb123ab39b91b | iscc_bench/metaid/shortnorm.py | iscc_bench/metaid/shortnorm.py | # -*- coding: utf-8 -*-
import unicodedata
def shortest_normalization_form():
"""
Find unicode normalization that generates shortest utf8 encoded text.
Result NFKC
"""
s = 'Iñtërnâtiônàlizætiøn☃ and string escaping are ticky   things'
nfc = unicodedata.normalize('NFC', s)
nfd = unico... | # -*- coding: utf-8 -*-
import unicodedata
def shortest_normalization_form():
"""
Find unicode normalization that generates shortest utf8 encoded text.
Result NFKC
"""
s = 'Iñtërnâtiônàlizætiøn☃ and string escaping are ticky   things'
nfc = unicodedata.normalize('NFC', s)
nfd = unico... | Add NFD_NFC to unicode normalization comparison. | Add NFD_NFC to unicode normalization comparison.
| Python | bsd-2-clause | coblo/isccbench |
ab079e05cb0a242235c1f506cb710279bf233ba0 | opps/channels/context_processors.py | opps/channels/context_processors.py | # -*- coding: utf-8 -*-
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import get_current_site
from .models import Channel
def channel_context(request):
""" Channel context processors
"""
site = get_current_site(request)
opps_menu = Channel.objects... | # -*- coding: utf-8 -*-
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import get_current_site
from .models import Channel
def channel_context(request):
""" Channel context processors
"""
site = get_current_site(request)
opps_menu = Channel.objects... | Fix order on opps menu | Fix order on opps menu
| Python | mit | YACOWS/opps,opps/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,williamroot/opps,opps/opps,YACOWS/opps,jeanmask/opps,opps/opps,williamroot/opps,YACOWS/opps,opps/opps |
6281da3b846bfea26ea68e3fe480c738a5181506 | runtests.py | runtests.py | #!/usr/bin/env python
import optparse
import sys
import unittest
from walrus import tests
def runtests(verbose=False, failfast=False, names=None):
if names:
suite = unittest.TestLoader().loadTestsFromNames(names, tests)
else:
suite = unittest.TestLoader().loadTestsFromModule(tests)
runner... | #!/usr/bin/env python
import optparse
import os
import sys
import unittest
def runtests(verbose=False, failfast=False, names=None):
if names:
suite = unittest.TestLoader().loadTestsFromNames(names, tests)
else:
suite = unittest.TestLoader().loadTestsFromModule(tests)
runner = unittest.Text... | Add test-runner option to run zpop* tests. | Add test-runner option to run zpop* tests.
| Python | mit | coleifer/walrus |
cf0110f2b1adc8fbf4b8305841961d67da33f8c7 | pybo/bayesopt/policies/thompson.py | pybo/bayesopt/policies/thompson.py | """
Acquisition functions based on (GP) UCB.
"""
# future imports
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
# use this to simplify (slightly) the Thompson implementation with sampled
# models.
from collections import deque
# local imports
from ..util... | """
Implementation of Thompson sampling for continuous spaces.
"""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from collections import deque
from ..utils import params
__all__ = ['Thompson']
@params('n')
def Thompson(model, n=100, rng=None):
"""
... | Fix Thompson to pay attention to the RNG. | Fix Thompson to pay attention to the RNG.
| Python | bsd-2-clause | mwhoffman/pybo,jhartford/pybo |
c96a2f636b48b065e8404af6d67fbae5986fd34a | tests/basics/subclass_native2_tuple.py | tests/basics/subclass_native2_tuple.py | class Base1:
def __init__(self, *args):
print("Base1.__init__", args)
class Ctuple1(Base1, tuple):
pass
a = Ctuple1()
print(len(a))
a = Ctuple1([1, 2, 3])
print(len(a))
print("---")
class Ctuple2(tuple, Base1):
pass
a = Ctuple2()
print(len(a))
a = Ctuple2([1, 2, 3])
print(len(a))
| class Base1:
def __init__(self, *args):
print("Base1.__init__", args)
class Ctuple1(Base1, tuple):
pass
a = Ctuple1()
print(len(a))
a = Ctuple1([1, 2, 3])
print(len(a))
print("---")
class Ctuple2(tuple, Base1):
pass
a = Ctuple2()
print(len(a))
a = Ctuple2([1, 2, 3])
print(len(a))
a = tuple([1,... | Expand test cases for equality of subclasses. | tests/basics: Expand test cases for equality of subclasses.
| Python | mit | pramasoul/micropython,adafruit/circuitpython,henriknelson/micropython,MrSurly/micropython,bvernoux/micropython,tobbad/micropython,kerneltask/micropython,kerneltask/micropython,tobbad/micropython,tobbad/micropython,pramasoul/micropython,selste/micropython,adafruit/circuitpython,henriknelson/micropython,pozetroninc/micro... |
4d3a0dc3b3b8a11a066f52bc78b1160e194ad64f | wmtexe/cmd/script.py | wmtexe/cmd/script.py | """Launch a WMT simulation using `bash` or `qsub`."""
from __future__ import print_function
import sys
import os
from ..launcher import BashLauncher, QsubLauncher
_LAUNCHERS = {
'bash': BashLauncher,
'qsub': QsubLauncher,
}
def main():
import argparse
parser = argparse.ArgumentParser(description=... | """Launch a WMT simulation using `bash` or `qsub`."""
from __future__ import print_function
import sys
import os
from ..launcher import BashLauncher, QsubLauncher
_LAUNCHERS = {
'bash': BashLauncher,
'qsub': QsubLauncher,
}
def main():
import argparse
parser = argparse.ArgumentParser(description=... | Add 'server-url' command line argument | Add 'server-url' command line argument
Its value is passed to the server_url parameter of the Launcher class.
| Python | mit | csdms/wmt-exe,csdms/wmt-exe,csdms/wmt-exe,csdms/wmt-exe |
f5408c02202a07a1b45019eefb505eb8a0d21852 | swagger2markdown.py | swagger2markdown.py | import argparse, json, os.path
import jinja2, requests
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"-i", "--input",
default="swagger.json",
help="path to or URL of the Swagger JSON file (default: swagger.json)",
metavar="SWAGGER_LOCATION"
)
par... | import argparse, json, os.path
import jinja2, requests
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"-i", "--input",
default="swagger.json",
help="path to or URL of the Swagger JSON file (default: swagger.json)",
metavar="SWAGGER_LOCATION"
)
par... | Fix crash when URL is provided. | Fix crash when URL is provided.
| Python | mit | moigagoo/swagger2markdown |
42326a18132381f0488b587329fe6b9aaea47c87 | normandy/selfrepair/views.py | normandy/selfrepair/views.py | from django.shortcuts import render
from normandy.base.decorators import short_circuit_middlewares
@short_circuit_middlewares
def repair(request, locale):
return render(request, 'selfrepair/repair.html', {
'locale': locale,
})
| from django.conf import settings
from django.shortcuts import render
from django.views.decorators.cache import cache_control
from normandy.base.decorators import short_circuit_middlewares
@short_circuit_middlewares
@cache_control(public=True, max_age=settings.API_CACHE_TIME)
def repair(request, locale):
return r... | Add cache headers to self-repair page | Add cache headers to self-repair page
| Python | mpl-2.0 | Osmose/normandy,Osmose/normandy,mozilla/normandy,Osmose/normandy,mozilla/normandy,Osmose/normandy,mozilla/normandy,mozilla/normandy |
9d541eeebe789d61d915dbbc7fd5792e244bd93f | ibmcnx/doc/DataSources.py | ibmcnx/doc/DataSources.py | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | Create script to save documentation to a file | 4: Create script to save documentation to a file
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 |
0a522863dce6e42bf66c66a56078c00901c64f52 | redash/__init__.py | redash/__init__.py | import json
import urlparse
from flask import Flask, make_response
from flask.ext.restful import Api
from flask_peewee.db import Database
import redis
from redash import settings, utils
__version__ = '0.3.2'
app = Flask(__name__,
template_folder=settings.STATIC_ASSETS_PATH,
static_folder=sett... | import json
import urlparse
from flask import Flask, make_response
from flask.ext.restful import Api
from flask_peewee.db import Database
import redis
from redash import settings, utils
__version__ = '0.3.2'
app = Flask(__name__,
template_folder=settings.STATIC_ASSETS_PATH,
static_folder=sett... | Use database number from redis url if available. | Use database number from redis url if available.
| Python | bsd-2-clause | denisov-vlad/redash,EverlyWell/redash,44px/redash,rockwotj/redash,M32Media/redash,guaguadev/redash,stefanseifert/redash,hudl/redash,easytaxibr/redash,denisov-vlad/redash,ninneko/redash,jmvasquez/redashtest,crowdworks/redash,easytaxibr/redash,getredash/redash,pubnative/redash,rockwotj/redash,crowdworks/redash,stefanseif... |
86418b48ca9bef5d0cd7cbf8468abfad633b56ed | write_csv.py | write_csv.py | """Export all responses from yesterday and save them to a CSV file."""
import sqlite3
import csv
from datetime import datetime, timedelta
import os
today = str(datetime.now().strftime('%Y-%m-%d'))
yesterday = str((datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d'))
export_directory = 'export'
export_filename ... | """Export all responses from yesterday and save them to a .csv file."""
import sqlite3
import csv
from datetime import datetime, timedelta
import os
today = str(datetime.now().strftime('%Y-%m-%d'))
yesterday = str((datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d'))
export_directory = 'export'
export_filename... | Add try/except in case select function fails | Add try/except in case select function fails
| Python | mit | andrewlrogers/srvy |
35a046a61d0acc1d6b7a1c084077bdf9ed7ff720 | tests/utils/parse_worksheet.py | tests/utils/parse_worksheet.py | import unittest
from utils import parse_worksheet
class TestParseWorksheet(unittest.TestCase):
def test_open_worksheet_function_is_defined(self):
if not hasattr(parse_worksheet, '__open_worksheet'):
self.fail('__open_sheet should be defined.')
def test_get_data_function_is_defined(self):
... | import unittest
from unittest.mock import patch
from utils import parse_worksheet
class TestParseWorksheet(unittest.TestCase):
def test_open_worksheet_function_is_defined(self):
if not hasattr(parse_worksheet, '__open_worksheet'):
self.fail('__open_worksheet should be defined.')
def test_g... | Remove testing of private methods (other than that they exist) | Remove testing of private methods (other than that they exist)
| Python | mit | jdgillespie91/trackerSpend,jdgillespie91/trackerSpend |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.