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
b6308afbc33f80b621e68c3d2b635fe64666c51a
wcontrol/conf/config.py
wcontrol/conf/config.py
import os basedir = os.path.abspath(os.path.dirname(__file__)) # forms wtf config WTF_CSRF_ENABLED = True SECRET_KEY = 'impossible-to-guess' # sqlalchemy database config SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db') SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository') SQLALCHEMY...
import os basedir = os.path.abspath(os.path.dirname(__file__)) # forms wtf config WTF_CSRF_ENABLED = True SECRET_KEY = 'impossible-to-guess' # sqlalchemy database config SQLALCHEMY_DATABASE_URI = os.environ.get('WCONTROL_DB', 'sqlite:///wcontrol/db/app.db') SQLALCHEMY_MIGRATE_...
Use a env var to get DB path
Use a env var to get DB path
Python
mit
pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control
58d3efa146f006fe518b02234b4eb0d6708cecc8
examples/web_ws.py
examples/web_ws.py
#!/usr/bin/env python3 """Example for aiohttp.web websocket server """ import os from aiohttp import web WS_FILE = os.path.join(os.path.dirname(__file__), 'websocket.html') async def wshandler(request): resp = web.WebSocketResponse() available = resp.can_prepare(request) if not available: with...
#!/usr/bin/env python3 """Example for aiohttp.web websocket server """ import os from aiohttp import web WS_FILE = os.path.join(os.path.dirname(__file__), 'websocket.html') async def wshandler(request): resp = web.WebSocketResponse() available = resp.can_prepare(request) if not available: with...
Send welcome message at very first of communication channel
Send welcome message at very first of communication channel
Python
apache-2.0
rutsky/aiohttp,arthurdarcet/aiohttp,arthurdarcet/aiohttp,KeepSafe/aiohttp,rutsky/aiohttp,KeepSafe/aiohttp,KeepSafe/aiohttp,rutsky/aiohttp,arthurdarcet/aiohttp
5a4e9d19f75bb02dc359099931310c7e6dd1ac99
web/extras/contentment/components/folder/controller.py
web/extras/contentment/components/folder/controller.py
# encoding: utf-8 """Basic folder controller. Additional views on asset contents. """ import datetime from web.extras.contentment.api import action, view from web.extras.contentment.components.asset.controller import AssetController log = __import__('logging').getLogger(__name__) __all__ = ['FolderController'] ...
# encoding: utf-8 """Basic folder controller. Additional views on asset contents. """ import datetime from web.extras.contentment.api import action, view from web.extras.contentment.components.asset.controller import AssetController log = __import__('logging').getLogger(__name__) __all__ = ['FolderController'] ...
Change default year to maximal available year, not current year.
Change default year to maximal available year, not current year.
Python
mit
marrow/contentment,marrow/contentment
a4f03e82b72287027a57101fe67f7fc26d312801
url_shortener/__init__.py
url_shortener/__init__.py
# -*- coding: utf-8 -*- from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object('url_shortener.default_config') app.config.from_envvar('URL_SHORTENER_CONFIGURATION') db = SQLAlchemy(app)
# -*- coding: utf-8 -*- from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object('url_shortener.default_config') """ From http://flask-sqlalchemy.pocoo.org/2.1/config/: "SQLALCHEMY_TRACK_MODIFICATIONS - If set to True, Flask-SQLAlchemy will track modifications of ...
Set SQLALCHEMY_TRACK_MODIFICATIONS option to False
Set SQLALCHEMY_TRACK_MODIFICATIONS option to False This commit adds code responsible for setting SQLALCHEMY_TRACK_MODIFICATION option to False. This option is provided by Flask-SQLAlchemy extension and relates to event system provided by this extension. This project uses event system provided by SQLAlchemy library, no...
Python
mit
piotr-rusin/url-shortener,piotr-rusin/url-shortener
d9f26a1d2831546517aec163a447dcf83cc80701
decisiontree/tests/urls.py
decisiontree/tests/urls.py
from django.conf.urls import include from django.contrib import admin admin.autodiscover() urlpatterns = [ (r'^admin/', include(admin.site.urls)), (r'^account/', include('rapidsms.urls.login_logout')), (r'^scheduler/', include('rapidsms.contrib.scheduler.urls')), (r'^tree/', include('decisiontree.ur...
from django.conf.urls import include from django.contrib import admin admin.autodiscover() urlpatterns = [ (r'^admin/', include(admin.site.urls)), (r'^account/', include('rapidsms.urls.login_logout')), (r'^tree/', include('decisiontree.urls')), ]
Remove reference to the scheduler, which was removed.
Remove reference to the scheduler, which was removed.
Python
bsd-3-clause
caktus/rapidsms-decisiontree-app,caktus/rapidsms-decisiontree-app,caktus/rapidsms-decisiontree-app
61b4f72045ea683a83a358d5d66bd32f7711598b
services/serializers.py
services/serializers.py
from rest_framework import serializers from .models import Service, Category, ServicePhoto class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name', 'photo', 'order') class ServicePhotoSerializer(serializers.ModelSerializer): """ """ ...
from rest_framework import serializers from .models import Service, Category, ServicePhoto from semillas_backend.users.serializers import UserSerializer class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name', 'photo', 'order') class ServicePho...
Add user serialized to ServiceSerializer
Add user serialized to ServiceSerializer
Python
mit
Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_backend,Semillas/semillas_platform
b5a43a7fdfc69abfa687d2b31a2add0d52ed5235
motobot/core_plugins/ctcp.py
motobot/core_plugins/ctcp.py
from motobot import match, Notice, Eat, __VERSION__ from time import strftime, localtime @match(r'\x01(.+)\x01', priority=Priority.max) def ctcp_match(bot, context, message, match): mapping = { 'VERSION': 'MotoBot Version ' + __VERSION__, 'FINGER': 'Oh you dirty man!', 'TIME': strftime('%a...
from motobot import match, Notice, Eat, Priority, __VERSION__ from time import strftime, localtime @match(r'\x01(.+)\x01', priority=Priority.max) def ctcp_match(bot, context, message, match): ctcp_response = { 'VERSION': 'MotoBot Version ' + __VERSION__, 'FINGER': 'Oh you dirty man!', 'TIM...
Fix CTCP import and naming bug
Fix CTCP import and naming bug
Python
mit
Motoko11/MotoBot
376fcbd76bb2f0de3c738ac66ac5526b6685d18a
plim/extensions.py
plim/extensions.py
from docutils.core import publish_parts import coffeescript from scss import Scss from stylus import Stylus from .util import as_unicode def rst_to_html(source): # This code was taken from http://wiki.python.org/moin/ReStructuredText # You may also be interested in http://www.tele3.cz/jbar/rest/about.html ...
from docutils.core import publish_parts import coffeescript from scss import Scss from stylus import Stylus from .util import as_unicode def rst_to_html(source): # This code was taken from http://wiki.python.org/moin/ReStructuredText # You may also be interested in http://www.tele3.cz/jbar/rest/about.html ...
Fix execjs.ProgramError: Error: Cannot find module 'nib' for -stylus
Fix execjs.ProgramError: Error: Cannot find module 'nib' for -stylus
Python
mit
kxxoling/Plim
db1c0183b3d42c611eaefa77f4b3bc4f33cb8267
django_classified/admin.py
django_classified/admin.py
# -*- coding:utf-8 -*- from django.contrib import admin from sorl.thumbnail.admin import AdminImageMixin from .models import Section, Group, Item, Image, Area class ImageInline(AdminImageMixin, admin.StackedInline): model = Image extra = 5 class ItemAdmin(admin.ModelAdmin): prepopulated_fields = {'slu...
# -*- coding:utf-8 -*- from django.contrib import admin from sorl.thumbnail.admin import AdminImageMixin from .models import Section, Group, Item, Image, Area class ImageInline(AdminImageMixin, admin.StackedInline): model = Image extra = 5 class ItemAdmin(admin.ModelAdmin): prepopulated_fields = {'slu...
Allow to search items by description.
Allow to search items by description.
Python
mit
inoks/dcf,inoks/dcf
33448ac669e192143655560dd52299e7069585ac
django_token/middleware.py
django_token/middleware.py
from django import http from django.contrib import auth from django.core import exceptions class TokenMiddleware(object): """ Middleware that authenticates against a token in the http authorization header. """ get_response = None def __init__(self, get_response=None): sel...
from django import http from django.contrib import auth from django.core import exceptions class TokenMiddleware(object): """ Middleware that authenticates against a token in the http authorization header. """ get_response = None def __init__(self, get_response=None): sel...
Fix for byte literals compatibility.
Fix for byte literals compatibility.
Python
mit
jasonbeverage/django-token
b929573e051f84ecc15020889fde6f6d798daa18
pmxbot/__init__.py
pmxbot/__init__.py
# -*- coding: utf-8 -*- # vim:ts=4:sw=4:noexpandtab from __future__ import absolute_import import socket import logging from .dictlib import ConfigDict config = ConfigDict( bot_nickname = 'pmxbot', database = 'sqlite:pmxbot.sqlite', server_host = 'localhost', server_port = 6667, use_ssl = False, password = No...
# -*- coding: utf-8 -*- # vim:ts=4:sw=4:noexpandtab from __future__ import absolute_import import socket import logging as _logging from .dictlib import ConfigDict config = ConfigDict( bot_nickname = 'pmxbot', database = 'sqlite:pmxbot.sqlite', server_host = 'localhost', server_port = 6667, use_ssl = False, p...
Fix issue with conflated pmxbot.logging
Fix issue with conflated pmxbot.logging
Python
mit
yougov/pmxbot,yougov/pmxbot,yougov/pmxbot
108c11d5187f7ec4647351c924df8cd881020b8a
falmer/matte/views.py
falmer/matte/views.py
from rest_framework import views, serializers from rest_framework.decorators import permission_classes from rest_framework.parsers import FileUploadParser from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from falmer.content.serializers import WagtailImageSerializer fr...
from rest_framework import views, serializers from rest_framework.decorators import permission_classes from rest_framework.parsers import FileUploadParser from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from falmer.content.serializers import WagtailImageSerializer fr...
Return error for image upload
Return error for image upload
Python
mit
sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer
2e9b87a7409f1995f96867270361f23a9fc3d1ab
flaskext/clevercss.py
flaskext/clevercss.py
# -*- coding: utf-8 -*- """ flaskext.clevercss ~~~~~~~~~~~~~ A small Flask extension that makes it easy to use cleverCSS with your Flask application. :copyright: (c) 2010 by Steve Losh. :copyright: (c) 2011 by Sujan Shakya. :license: MIT, see LICENSE for more details. """ import os import...
# -*- coding: utf-8 -*- """ flaskext.clevercss ~~~~~~~~~~~~~ A small Flask extension that makes it easy to use cleverCSS with your Flask application. :copyright: (c) 2010 by Steve Losh. :copyright: (c) 2011 by Sujan Shakya. :license: MIT, see LICENSE for more details. """ import os import...
Fix for specifying the static directory in later versions of flask
Fix for specifying the static directory in later versions of flask
Python
mit
suzanshakya/flask-clevercss,suzanshakya/flask-clevercss
ac31a10d00508ddd354d9c30055d2955b306d516
duct/protocol/sflow/protocol/utils.py
duct/protocol/sflow/protocol/utils.py
import struct, socket def unpack_address(u): addrtype = u.unpack_uint() if self.addrtype == 1: self.address = u.unpack_fopaque(4) if self.addrtype == 2: self.address = u.unpack_fopaque(16) return self.address class IPv4Address(object): def __init__(self, addr_int): ...
import struct, socket def unpack_address(u): addrtype = u.unpack_uint() if addrtype == 1: address = u.unpack_fopaque(4) if addrtype == 2: address = u.unpack_fopaque(16) return address class IPv4Address(object): def __init__(self, addr_int): self.addr_int = addr_int ...
Fix bad transposition of utility function in sflow
Fix bad transposition of utility function in sflow
Python
mit
ducted/duct,ducted/duct,ducted/duct,ducted/duct
2045856aa66cef7b81d9e617fd29fc9ca19276d7
pwned/src/pwned.py
pwned/src/pwned.py
import hashlib, sys, urllib.request def main(): hash = hashlib.sha1(bytes(sys.argv[1], "utf-8")) digest = hash.hexdigest().upper() url = f"https://api.pwnedpasswords.com/range/{digest[:5]}" request = urllib.request.Request(url, headers={"User-Agent":"API-Programming-Exercise"}) page = urllib.request.urlopen(requ...
import hashlib, sys, urllib.request def main(): hash = hashlib.sha1(bytes(sys.argv[1], "utf-8")) digest = hash.hexdigest().upper() url = f"https://api.pwnedpasswords.com/range/{digest[:5]}" request = urllib.request.Request(url, headers={"User-Agent":"API-Programming-Exercise"}) page = urllib.request.urlopen(requ...
Add output when password is not found
Add output when password is not found
Python
agpl-3.0
0x424D/crappy,0x424D/crappy
34c38e0cfe5e880e678704c4d473f082787fca64
rest_framework/authtoken/management/commands/drf_create_token.py
rest_framework/authtoken/management/commands/drf_create_token.py
from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand from rest_framework.authtoken.models import Token UserModel = get_user_model() class Command(BaseCommand): help = 'Create DRF Token for a given user' def create_user_token(self, username): user = User...
from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand, CommandError from rest_framework.authtoken.models import Token UserModel = get_user_model() class Command(BaseCommand): help = 'Create DRF Token for a given user' def create_user_token(self, username): ...
Use self.sdtout and CommandError to print output
Use self.sdtout and CommandError to print output
Python
bsd-2-clause
dmwyatt/django-rest-framework,ossanna16/django-rest-framework,jpadilla/django-rest-framework,tomchristie/django-rest-framework,jpadilla/django-rest-framework,kgeorgy/django-rest-framework,kgeorgy/django-rest-framework,tomchristie/django-rest-framework,tomchristie/django-rest-framework,ossanna16/django-rest-framework,jp...
f7f3907da8ec31cafaec3d7e82755cfa344ed60e
performance/web.py
performance/web.py
class Request: GET = 'get' POST = 'post' def __init__(self, url, type, data=None): self.url = url self.type = type self.data = data class RequestData: def __init__(self, data=None): self.data = data def for_type(self, type=Request.GET): if type is Request....
import requests from time import time class Client: def __init__(self): pass class Request: GET = 'get' POST = 'post' def __init__(self, url, type, data=None): self.url = url self.type = type self.data = data def do(self): try: data = '' ...
Create Error-classes, Client class and do function for Request
Create Error-classes, Client class and do function for Request
Python
mit
BakeCode/performance-testing,BakeCode/performance-testing
7c6a128b707db738d0a89c2897b35ed7d783ade0
plugins/basic_info_plugin.py
plugins/basic_info_plugin.py
import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): name = 'BasicInfoPlugin' short_description = 'Basic info:' default = True description = textwrap.dedent(''' This plugin provides some ba...
import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): name = 'BasicInfoPlugin' short_description = 'Basic info:' default = True description = textwrap.dedent(''' This plugin provides some ba...
Add punctuation to basic info
Add punctuation to basic info
Python
mit
Sakartu/stringinfo
c1f63f381b167d6bfe701a36e998727cf4ed3bec
client/software/resources/modules/hardware_auto_find.py
client/software/resources/modules/hardware_auto_find.py
#I got this code on http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python #So, yeah. I didn't wrote this code :-P import sys import glob import serial def serial_ports(): """ Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list...
#I got this code on http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python #So, yeah. I didn't wrote this code :-P import sys import glob import serial def serial_ports(): """ Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list...
Make hardware search only on USB on Ubuntu Linux
Make hardware search only on USB on Ubuntu Linux
Python
mit
MU-Software/Project_Musica_for_Contest
1bd344a3ccda43f4ac1d4b94b1a18fc816c9b6ae
slurmscale/jobs/jobs.py
slurmscale/jobs/jobs.py
"""Get info about jobs running on this cluster.""" import pyslurm from job import Job class Jobs(object): """A service object to inspect jobs.""" @property def _jobs(self): """Fetch fresh data.""" return pyslurm.job().get() def list(self): """List the current jobs on the clu...
"""Get info about jobs running on this cluster.""" import pyslurm from job import Job class Jobs(object): """A service object to inspect jobs.""" @property def _jobs(self): """Fetch fresh data.""" return pyslurm.job().get() def list(self, states=None): """ List the c...
Add ability to filter job list by job state
Add ability to filter job list by job state
Python
mit
afgane/slurmscale,afgane/slurmscale
d3f73b55dc68ec18fb5f4c43dcff59f3766d752f
mica/starcheck/__init__.py
mica/starcheck/__init__.py
from .starcheck import get_starcheck_catalog, main, get_mp_dir
from .starcheck import get_starcheck_catalog, get_starcheck_catalog_at_date, main, get_mp_dir
Add get_starcheck_catalog_at_date to top level items in mica.starcheck
Add get_starcheck_catalog_at_date to top level items in mica.starcheck
Python
bsd-3-clause
sot/mica,sot/mica
20d1cd153d54f2eab88197c76c201ed5e7814536
modules/urbandictionary.py
modules/urbandictionary.py
"""Looks up a term from urban dictionary @package ppbot @syntax ud <word> """ import requests import json from modules import * class Urbandictionary(Module): def __init__(self, *args, **kwargs): """Constructor""" Module.__init__(self, kwargs=kwargs) self.url = "http://www.urbandictiona...
"""Looks up a term from urban dictionary @package ppbot @syntax ud <word> """ import requests import json from modules import * class Urbandictionary(Module): def __init__(self, *args, **kwargs): """Constructor""" Module.__init__(self, kwargs=kwargs) self.url = "http://www.urbandictiona...
Fix another exception for ud when def isn't found
Fix another exception for ud when def isn't found
Python
mit
billyvg/piebot
137b834f166eea13781311b1f050f0eaf2e1d610
podcasts/management/commands/updatepodcasts.py
podcasts/management/commands/updatepodcasts.py
from django.core.management import BaseCommand from podcasts.models import Podcast class Command(BaseCommand): help = 'Initialize podcasts with data from their RSS feeds' def handle(self, *args, **kwargs): for podcast in Podcast.objects.all(): podcast.update()
from django.core.management import BaseCommand from optparse import make_option from podcasts.models import Podcast class Command(BaseCommand): help = 'Initialize podcasts with data from their RSS feeds' option_list = BaseCommand.option_list + ( make_option( '--only-new', actio...
Make it optional to only update metadata of new podcasts
Make it optional to only update metadata of new podcasts
Python
mit
matachi/sputnik,matachi/sputnik,matachi/sputnik,matachi/sputnik
aee157ce27aa4f00a798b87e07583dc795265eb4
methodAndKnottiness/reliability.py
methodAndKnottiness/reliability.py
import sys count = 0 for line in sys.stdin: if count == 0: B = int(line) elif count == 1: N = int(line) else: c, r = line.rstrip().split(' ') cost = int(c) reliability = float(r) count+=1 print("Fin")
import sys, math count = 0 cost=[] reliability=[] # Read input. Budget, number of machines, cost and reliability for line in sys.stdin: if count == 0: B = int(line) elif count == 1: N = int(line) else: c, r = line.rstrip().split(' ') cost.append(int(c)) reliability....
Save point, got code written but need to figure out the base probabilities
Save point, got code written but need to figure out the base probabilities
Python
mit
scrasmussen/ProsaicOeuvre,scrasmussen/ProsaicOeuvre,scrasmussen/ProsaicOeuvre
a6dd8aee6a3b6272372532a19fba3d830d40612a
neo/test/io/test_axonio.py
neo/test/io/test_axonio.py
# encoding: utf-8 """ Tests of io.axonio """ try: import unittest2 as unittest except ImportError: import unittest from neo.io import AxonIO from neo.test.io.common_io_test import BaseTestIO class TestAxonIO(BaseTestIO, unittest.TestCase): files_to_test = ['File_axon_1.abf', 'File_a...
# encoding: utf-8 """ Tests of io.axonio """ try: import unittest2 as unittest except ImportError: import unittest from neo.io import AxonIO from neo.test.io.common_io_test import BaseTestIO class TestAxonIO(BaseTestIO, unittest.TestCase): files_to_test = ['File_axon_1.abf', 'File_a...
Test with file from Jackub
Test with file from Jackub git-svn-id: 0eea5547755d67006ec5687992a7464f0ad96b59@379 acbc63fc-6c75-0410-9d68-8fa99cba188a
Python
bsd-3-clause
SummitKwan/python-neo,mschmidt87/python-neo,rgerkin/python-neo,jakobj/python-neo,CINPLA/python-neo,apdavison/python-neo,theunissenlab/python-neo,samuelgarcia/python-neo,guangxingli/python-neo,mgr0dzicki/python-neo,JuliaSprenger/python-neo,NeuralEnsemble/python-neo,npyoung/python-neo,INM-6/python-neo,tclose/python-neo,t...
99a1ce2ecee6dd761113515da5c89b8c7da5537f
Python/Algorithm.py
Python/Algorithm.py
class Algorithm: """ Algorithm Class Base class for the page substitution algorithms. """ def __init__(self, input = []): """ Algorithm Constructor. Parameters ---------- input : list A list containing the the input page swap. """ if not input: #If the list is empty throw an exception. raise...
class Algorithm: """ Algorithm Class Base class for the page substitution algorithms. """ def __init__(self, input = []): """ Algorithm Constructor. Parameters ---------- input : list A list containing the the input page swap. """ if not input: #If the list is empty throw an exception. raise...
Fix logic error under preparePageFrames
Fix logic error under preparePageFrames
Python
mit
caiomcg/OS-PageSubstitution
01b9d47976dd68a3fe9ae2656e423a03edb5187d
examples/source.py
examples/source.py
"""Test client that connects and sends infinite data.""" import sys from tulip import * def dprint(*args): print('source:', *args, file=sys.stderr) class Client(Protocol): data = b'x'*16*1024 def connection_made(self, tr): dprint('connecting to', tr.get_extra_info('addr')) self.tr ...
"""Test client that connects and sends infinite data.""" import sys from tulip import * def dprint(*args): print('source:', *args, file=sys.stderr) class Client(Protocol): data = b'x'*16*1024 def connection_made(self, tr): dprint('connecting to', tr.get_extra_info('addr')) self.tr ...
Fix logic around lost connection.
Fix logic around lost connection.
Python
apache-2.0
leetreveil/tulip,overcastcloud/trollius,leetreveil/tulip,overcastcloud/trollius,leetreveil/tulip,overcastcloud/trollius
9ce7de86b7d9c1e9288fa5c09f97414516cabc63
corehq/apps/reports/filters/urls.py
corehq/apps/reports/filters/urls.py
from django.conf.urls import url from .api import ( EmwfOptionsView, CaseListFilterOptions, DeviceLogUsers, DeviceLogIds, MobileWorkersOptionsView, ReassignCaseOptions, ) from .location import LocationGroupFilterOptions urlpatterns = [ url(r'^emwf_options/$', EmwfOptionsView.as_view(), name...
from django.conf.urls import url from .api import ( EmwfOptionsView, CaseListFilterOptions, DeviceLogUsers, DeviceLogIds, MobileWorkersOptionsView, ReassignCaseOptions, ) from .location import LocationGroupFilterOptions urlpatterns = [ url(r'^emwf_options/$', EmwfOptionsView.as_view(), nam...
Fix bad merge and formatting
Fix bad merge and formatting
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
7186faebdb22f4aacffb2e0603fe6918f6b89ee7
rrd_data_source.py
rrd_data_source.py
class RRDDataSource(object): name = "" data_source_type = "" heartbeat = "" temp_value = 0 def __init__(self, name, data_source_type, heartbeat): self.name = name self.data_source_type = data_source_type self.heartbeat = heartbeat
class RRDDataSource(object): name = "" data_source_type = "" heartbeat = "" temp_value = 0 def __init__(self, name, data_source_type, heartbeat, temp_value=None): self.name = name self.data_source_type = data_source_type self.heartbeat = heartbeat self.temp_value = t...
Add temp_value (optional) parameter to RRDDataSource constructor.
Add temp_value (optional) parameter to RRDDataSource constructor.
Python
mit
netgroup/OSHI-monitoring,StefanoSalsano/OSHI-monitoring,ferrarimarco/OSHI-monitoring,StefanoSalsano/OSHI-monitoring,netgroup/OSHI-monitoring,ferrarimarco/OSHI-monitoring
ff65a3e1b0f061100a20462dea4f654b02707a6f
fig/cli/command.py
fig/cli/command.py
from docker import Client import logging import os import re import yaml from ..project import Project from .docopt_command import DocoptCommand from .formatter import Formatter from .utils import cached_property log = logging.getLogger(__name__) class Command(DocoptCommand): @cached_property def client(self...
from docker import Client import logging import os import re import yaml import socket from ..project import Project from .docopt_command import DocoptCommand from .formatter import Formatter from .utils import cached_property from .errors import UserError log = logging.getLogger(__name__) class Command(DocoptComman...
Check default socket and localhost:4243 for Docker daemon
Check default socket and localhost:4243 for Docker daemon
Python
apache-2.0
MSakamaki/compose,alexisbellido/docker.github.io,prologic/compose,KevinGreene/compose,phiroict/docker,calou/compose,rillig/docker.github.io,docker/docker.github.io,phiroict/docker,vlajos/compose,ekristen/compose,JimGalasyn/docker.github.io,albers/compose,zhangspook/compose,charleswhchan/compose,talolard/compose,nhumric...
036a89ce97d8160fe6b4cb10a95f3cf9e8a855ff
Lib/test/test_openpty.py
Lib/test/test_openpty.py
# Test to see if openpty works. (But don't worry if it isn't available.) import os from test.test_support import verbose, TestFailed, TestSkipped try: if verbose: print "Calling os.openpty()" master, slave = os.openpty() if verbose: print "(master, slave) = (%d, %d)"%(master, slave) except...
# Test to see if openpty works. (But don't worry if it isn't available.) import os from test.test_support import verbose, TestFailed, TestSkipped try: if verbose: print "Calling os.openpty()" master, slave = os.openpty() if verbose: print "(master, slave) = (%d, %d)"%(master, slave) except...
Remove bogus test; the master is not a terminal on Solaris and HP-UX.
Remove bogus test; the master is not a terminal on Solaris and HP-UX.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
301f22b9b2de2a27dd2e3faa27ccb9c70266e938
pybossa/api/project_stats.py
pybossa/api/project_stats.py
# -*- coding: utf8 -*- # This file is part of PYBOSSA. # # Copyright (C) 2015 Scifabric LTD. # # PYBOSSA is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
# -*- coding: utf8 -*- # This file is part of PYBOSSA. # # Copyright (C) 2015 Scifabric LTD. # # PYBOSSA is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
Fix _select_attributes from project api
Fix _select_attributes from project api
Python
agpl-3.0
PyBossa/pybossa,PyBossa/pybossa,Scifabric/pybossa,Scifabric/pybossa
88da3432dc0676cbe74c0d9f170fbd6f18f97f8a
examples/tornado_server.py
examples/tornado_server.py
from tornado import ioloop, web from jsonrpcserver import method, async_dispatch as dispatch @method async def ping(): return "pong" class MainHandler(web.RequestHandler): async def post(self): request = self.request.body.decode() response = await dispatch(request) print(response) ...
from tornado import ioloop, web from jsonrpcserver import method, async_dispatch as dispatch @method async def ping() -> str: return "pong" class MainHandler(web.RequestHandler): async def post(self) -> None: request = self.request.body.decode() response = await dispatch(request) if ...
Remove unwanted print statement from example
Remove unwanted print statement from example
Python
mit
bcb/jsonrpcserver
e44f4ce0db6c56309107bc7280ac4e2b41616ab2
modules/git/git.py
modules/git/git.py
import os import os.path import subprocess from module import Module class git(Module): def __init__(self, scrap): super(git, self).__init__(scrap) scrap.register_event("git", "msg", self.distribute) self.register_cmd("version", self.git_version) self.register_cmd("update", self.up...
import os import os.path import subprocess from module import Module class git(Module): def __init__(self, scrap): super(git, self).__init__(scrap) scrap.register_event("git", "msg", self.distribute) self.register_cmd("version", self.git_version) self.register_cmd("update", self.up...
Use subprocess to update, seems silly to use both subprocess and os.systemm in the same module. update also reports if the version hasn't changed.
Use subprocess to update, seems silly to use both subprocess and os.systemm in the same module. update also reports if the version hasn't changed.
Python
mit
tcoppi/scrappy,johnmiked15/scrappy,johnmiked15/scrappy,tcoppi/scrappy
d5b0234cca1bbab1a0bd20091df44380aca71ee8
tslearn/tests/test_svm.py
tslearn/tests/test_svm.py
import numpy as np from tslearn.metrics import cdist_gak from tslearn.svm import TimeSeriesSVC __author__ = 'Romain Tavenard romain.tavenard[at]univ-rennes2.fr' def test_svm_gak(): n, sz, d = 15, 10, 3 rng = np.random.RandomState(0) time_series = rng.randn(n, sz, d) labels = rng.randint(low=0, high=...
import numpy as np from tslearn.metrics import cdist_gak from tslearn.svm import TimeSeriesSVC, TimeSeriesSVR __author__ = 'Romain Tavenard romain.tavenard[at]univ-rennes2.fr' def test_gamma_value_svm(): n, sz, d = 5, 10, 3 rng = np.random.RandomState(0) time_series = rng.randn(n, sz, d) labels = rn...
Change test name and test SVR too
Change test name and test SVR too
Python
bsd-2-clause
rtavenar/tslearn
e731c3a4a8590f5cddd23fd2f9af265749f08a38
code_snippets/guides-agentchecks-methods.py
code_snippets/guides-agentchecks-methods.py
self.gauge( ... ) # Sample a gauge metric self.increment( ... ) # Increment a counter metric self.decrement( ... ) # Decrement a counter metric self.histogram( ... ) # Sample a histogram metric self.rate( ... ) # Sample a point, with the rate calculated at the end of the check
self.gauge( ... ) # Sample a gauge metric self.increment( ... ) # Increment a counter metric self.decrement( ... ) # Decrement a counter metric self.histogram( ... ) # Sample a histogram metric self.rate( ... ) # Sample a point, with the rate calculated at the end of the check self.count( ... ) # Sample a raw coun...
Document AgentCheck count and monotonic_count methods
Document AgentCheck count and monotonic_count methods
Python
bsd-3-clause
inokappa/documentation,macobo/documentation,macobo/documentation,jhotta/documentation,jhotta/documentation,inokappa/documentation,macobo/documentation,macobo/documentation,inokappa/documentation,jhotta/documentation,jhotta/documentation,jhotta/documentation,jhotta/documentation,inokappa/documentation,inokappa/documenta...
6da466984143d2a9176870583ca5dba8d1b9764c
test/integration/test_graylogapi.py
test/integration/test_graylogapi.py
import pytest from pygraylog.pygraylog import graylogapi def test_get(): api = graylogapi.GraylogAPI('http://echo.jsontest.com/one/two', username = 'Zack', password = 'Zack') res = api._get() expected = { 'one': 'two' } assert res == expected def test_post(): api = gr...
import pytest from pygraylog.pygraylog import graylogapi def test_get(): api = graylogapi.GraylogAPI('http://echo.jsontest.com/one/two', username = 'Zack', password = 'Zack') res = api._get() expected = "{\"one\": \"two\"}\n" assert res == expected def test_post(): api = graylogap...
Modify test to reflect that api returns string response.
Modify test to reflect that api returns string response.
Python
apache-2.0
zmallen/pygraylog
4ba0b5fe7f31d4353e9c091b03df7324d1c20e88
heat/common/pluginutils.py
heat/common/pluginutils.py
# # 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 # ...
# # 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 # ...
Fix no message attribute in exception
Fix no message attribute in exception For py35, message attribute in exception seems removed. We should directly get the string message from exception object if message attribute not presented. And since get message attribute already been deprecated. We should remove sopport on exception.message after we fully jump to...
Python
apache-2.0
noironetworks/heat,noironetworks/heat,openstack/heat,openstack/heat
dd63394499c7c629033e76afa0196dfe48547da2
corehq/messaging/smsbackends/tropo/models.py
corehq/messaging/smsbackends/tropo/models.py
from urllib import urlencode from urllib2 import urlopen from corehq.apps.sms.util import clean_phone_number from corehq.apps.sms.models import SQLSMSBackend from dimagi.ext.couchdbkit import * from corehq.messaging.smsbackends.tropo.forms import TropoBackendForm from django.conf import settings class SQLTropoBackend...
from urllib import urlencode from urllib2 import urlopen from corehq.apps.sms.util import clean_phone_number from corehq.apps.sms.models import SQLSMSBackend from dimagi.ext.couchdbkit import * from corehq.messaging.smsbackends.tropo.forms import TropoBackendForm from django.conf import settings class SQLTropoBackend...
Add opt in/out keywords for tropo
Add opt in/out keywords for tropo
Python
bsd-3-clause
dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq
ed48c19844ee4f78c897c26555bdba9977a9a6ac
bluebottle/test/test_runner.py
bluebottle/test/test_runner.py
from django.test.runner import DiscoverRunner from django.db import connection from tenant_schemas.utils import get_tenant_model from bluebottle.test.utils import InitProjectDataMixin class MultiTenantRunner(DiscoverRunner, InitProjectDataMixin): def setup_databases(self, *args, **kwargs): result = supe...
from django.test.runner import DiscoverRunner from django.db import connection from tenant_schemas.utils import get_tenant_model from bluebottle.test.utils import InitProjectDataMixin class MultiTenantRunner(DiscoverRunner, InitProjectDataMixin): def setup_databases(self, *args, **kwargs): result = supe...
Make it possible to run tests with --keepdb
Make it possible to run tests with --keepdb
Python
bsd-3-clause
onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle
25395cbd3536c1bc2ee1a6bc44a34ea7fc5b2a13
src/priestLogger.py
src/priestLogger.py
import logging from logging.handlers import TimedRotatingFileHandler class PriestLogger: def __init__(self): logHandler = TimedRotatingFileHandler("C:\\lucas\\PriestPy\\Dropbox\\logs\\HowToPriest",when="midnight",backupCount=365) logFormatter = logging.Formatter('%(asctime)s - %(message)s') logHandler.setForma...
import logging from logging.handlers import TimedRotatingFileHandler from time import sleep class PriestLogger: def __init__(self): logHandler = TimedRotatingFileHandler("C:\\lucas\\PriestPy\\Dropbox\\logs\\HowToPriest",when="midnight",backupCount=365) logFormatter = logging.Formatter('%(asctime)s - %(message)s'...
Fix for conflict in opening file
Fix for conflict in opening file
Python
mit
lgkern/PriestPy
7e0ef4ba74bf2d6ea93f49d88c58378e7a1f9106
fabfile.py
fabfile.py
from fusionbox.fabric_helpers import * env.roledefs = { 'dev': ['dev.fusionbox.com'], } env.project_name = 'django-widgy' env.short_name = 'widgy' env.tld = '' def stage_with_docs(pip=False, migrate=False, syncdb=False, branch=None): stage(pip=pip, migrate=migrate, syncdb=syncdb, branch=branch) ...
from fusionbox.fabric_helpers import * env.roledefs = { 'dev': ['dev.fusionbox.com'], } env.project_name = 'django-widgy' env.short_name = 'widgy' env.tld = '' _stage = stage def stage(pip=False, migrate=False, syncdb=False, branch=None): _stage(pip=pip, migrate=migrate, syncdb=syncdb, branch=br...
Make this one role, stage
Make this one role, stage
Python
apache-2.0
j00bar/django-widgy,j00bar/django-widgy,j00bar/django-widgy
78af66131240f79e43fba811cb8769b1911fa013
services/fitbit.py
services/fitbit.py
import foauth.providers class Fitbit(foauth.providers.OAuth1): # General info about the provider provider_url = 'https://www.fitbit.com/' docs_url = 'https://dev.fitbit.com/' category = 'Fitness' # URLs to interact with the API request_token_url = 'https://api.fitbit.com/oauth/request_token' ...
import requests import foauth.providers class Fitbit(foauth.providers.OAuth2): # General info about the provider provider_url = 'https://www.fitbit.com/' docs_url = 'https://dev.fitbit.com/' category = 'Fitness' # URLs to interact with the API authorize_url = 'https://www.fitbit.com/oauth2/a...
Upgrade Fitbit to OAuth 2.0
Upgrade Fitbit to OAuth 2.0
Python
bsd-3-clause
foauth/foauth.org,foauth/foauth.org,foauth/foauth.org
936021e0a7b2f23935f4580c5140c1292a37cf82
runbot_pylint/__openerp__.py
runbot_pylint/__openerp__.py
{ 'name': 'Runbot Pylint', 'category': 'Website', 'summary': 'Runbot', 'version': '1.0', 'description': "Runbot", 'author': 'OpenERP SA', 'depends': ['runbot'], 'external_dependencies': { }, 'data': [ "view/runbot_pylint_view.xml" ], 'installable': True, }
{ 'name': 'Runbot Pylint', 'category': 'Website', 'summary': 'Runbot', 'version': '1.0', 'description': "Runbot", 'author': 'OpenERP SA', 'depends': ['runbot'], 'external_dependencies': { 'bin': ['pylint'], }, 'data': [ "view/runbot_pylint_view.xml" ], 'in...
Add external depedencies to pylint bin
Add external depedencies to pylint bin
Python
agpl-3.0
amoya-dx/runbot-addons
2823efda9d6ec2a14606c9e22ef8085f111d8842
isort/pylama_isort.py
isort/pylama_isort.py
import os import sys from contextlib import contextmanager from typing import Any, Dict, List from pylama.lint import Linter as BaseLinter from . import api @contextmanager def supress_stdout(): stdout = sys.stdout with open(os.devnull, "w") as devnull: sys.stdout = devnull yield sys...
import os import sys from contextlib import contextmanager from typing import Any, Dict, List from pylama.lint import Linter as BaseLinter from . import api @contextmanager def supress_stdout(): stdout = sys.stdout with open(os.devnull, "w") as devnull: sys.stdout = devnull yield sys...
Fix pylama isort integration not to include check=True redundly
Fix pylama isort integration not to include check=True redundly
Python
mit
PyCQA/isort,PyCQA/isort
c52e8e27d7b245722e10887dc97440481d0871f4
scraper/political_parties.py
scraper/political_parties.py
import re import requests import lxml.html from parliament.models import PoliticalParty def create_parties(): url = 'https://www.tweedekamer.nl/kamerleden/fracties' page = requests.get(url) tree = lxml.html.fromstring(page.content) rows = tree.xpath("//ul[@class='reset grouped-list']/li/a") for...
import re import requests import lxml.html from parliament.models import PoliticalParty def create_parties(): url = 'https://www.tweedekamer.nl/kamerleden/fracties' page = requests.get(url) tree = lxml.html.fromstring(page.content) rows = tree.xpath("//ul[@class='reset grouped-list']/li/a") for...
Update party info after creation
Update party info after creation
Python
mit
openkamer/openkamer,openkamer/openkamer,openkamer/openkamer,openkamer/openkamer
01cc82642273af950caedba471ed4cc9e788b615
alapage/urls.py
alapage/urls.py
# -*- coding: utf-8 -*- from django.conf.urls import url from alapage.views import HomepageView, PageView, PagesmapView urlpatterns = [] urlpatterns.append( url(r'^sitemap/$', PagesmapView.as_view(), name="alapage-map")) #urlpatterns.append(url(r'^alapage/wizard/$', PageWizardView.as_view(), name="alapage-wizar...
from django.conf.urls import url from alapage.views import HomepageView, PageView, PagesmapView urlpatterns = [ url(r'^sitemap/?$', PagesmapView.as_view(), name="alapage-map"), url(r'^(?P<url>.*?)?$', PageView.as_view(), name="page-view"), url(r'^', HomepageView.as_view(), name="home-view"), ]
Fix url regex for no trailing slash
Fix url regex for no trailing slash
Python
mit
synw/django-alapage,synw/django-alapage,synw/django-alapage
491d2ad7cea58597e15b095b94930b6ff1dbf4d2
createdb.py
createdb.py
from chalice.extensions import db from chalice import init_app from chalice.blog.models import Tag, Post from chalice.auth.models import User if __name__ == '__main__': app = init_app() with app.test_request_context(): db.create_all() post = Post( 'This is a title', 'The classic hello world her...
from chalice.extensions import db from chalice import init_app from chalice.blog.models import Tag, Post from chalice.auth.models import User if __name__ == '__main__': app = init_app() with app.test_request_context(): db.create_all() user = User(app.config['CHALICE_USER'], app.config['CHALICE_...
Remove dummy post from created.py script. Initial user now taken from config.
Remove dummy post from created.py script. Initial user now taken from config.
Python
bsd-2-clause
andrimarjonsson/chalice,andrimarjonsson/chalice
e8422ac65a4557257d9697b8dfcb538a02e5f6f0
pixelated/common/__init__.py
pixelated/common/__init__.py
import ssl import logging from logging.handlers import SysLogHandler from threading import Timer logger = logging.getLogger('pixelated.startup') def init_logging(name, level=logging.INFO, config_file=None): global logger logger_name = 'pixelated.%s' % name logging.basicConfig(level=level) if config_...
import ssl import logging from logging.handlers import SysLogHandler from threading import Timer logger = logging.getLogger('pixelated.startup') def init_logging(name, level=logging.INFO, config_file=None): global logger logger_name = 'pixelated.%s' % name logging.basicConfig(level=level) if config_...
Revert "Downgraded SSL version to TLS 1 until we have the requests library fixed"
Revert "Downgraded SSL version to TLS 1 until we have the requests library fixed" - TLS1.2 does not work on older pythons (like on MacOSX) but it works as intended on current linux versions so enable it if possible This reverts commit 666630f2a01bdeb7becc3cd3b324c076eaf1567d. Conflicts: pixelated/common/__init_...
Python
agpl-3.0
pixelated-project/pixelated-dispatcher,pixelated-project/pixelated-dispatcher,pixelated/pixelated-dispatcher,pixelated/pixelated-dispatcher,pixelated/pixelated-dispatcher,pixelated-project/pixelated-dispatcher
d7ea84800b89255137300b8e8d83b4b6abfc30b2
src/oscar/apps/voucher/receivers.py
src/oscar/apps/voucher/receivers.py
from oscar.apps.basket import signals def track_voucher_addition(basket, voucher, **kwargs): voucher.num_basket_additions += 1 voucher.save() def track_voucher_removal(basket, voucher, **kwargs): voucher.num_basket_additions -= 1 voucher.save() signals.voucher_addition.connect(track_voucher_additi...
from django.db.models import F from oscar.apps.basket import signals def track_voucher_addition(basket, voucher, **kwargs): voucher.num_basket_additions += 1 voucher.__class__._default_manager.filter(pk=voucher.pk).update( num_basket_additions=F('num_basket_additions') + 1, ) def track_voucher_r...
Fix race condition when tracking num_basket_additions on a voucher
Fix race condition when tracking num_basket_additions on a voucher
Python
bsd-3-clause
jmt4/django-oscar,mexeniz/django-oscar,michaelkuty/django-oscar,pasqualguerrero/django-oscar,binarydud/django-oscar,saadatqadri/django-oscar,jmt4/django-oscar,michaelkuty/django-oscar,nickpack/django-oscar,pasqualguerrero/django-oscar,okfish/django-oscar,sasha0/django-oscar,okfish/django-oscar,sasha0/django-oscar,bnprk...
691dae3963d049664605084438714b2850bd0933
linter.py
linter.py
# # linter.py # Linter for SublimeLinter4, a code checking framework for Sublime Text 3 # # Written by Markus Liljedahl # Copyright (c) 2017 Markus Liljedahl # # License: MIT # """This module exports the AnsibleLint plugin class.""" from SublimeLinter.lint import Linter, util class AnsibleLint(Linter): """Provi...
# # linter.py # Linter for SublimeLinter4, a code checking framework for Sublime Text 3 # # Written by Markus Liljedahl # Copyright (c) 2017 Markus Liljedahl # # License: MIT # """This module exports the AnsibleLint plugin class.""" from SublimeLinter.lint import Linter, util class AnsibleLint(Linter): """Provi...
Update to support SublimeLinter 4
Update to support SublimeLinter 4
Python
mit
mliljedahl/SublimeLinter-contrib-ansible-lint
84597d8b8135af36056f968d10699c206dd06942
adapter/terminal.py
adapter/terminal.py
import os import socket import subprocess import string import logging log = logging.getLogger('terminal') class Terminal: def __init__(self, tty, socket): self.tty = tty self.socket = socket def __del__(self): self.socket.close() TIMEOUT = 1 # Timeout in seconds for child opening a ...
import os import socket import subprocess import string import logging log = logging.getLogger('terminal') class Terminal: def __init__(self, tty, socket): self.tty = tty self.socket = socket def __del__(self): self.socket.close() TIMEOUT = 3 # Timeout in seconds for child opening a ...
Use bash's built-in tcp support, drop dependency on netcat.
Use bash's built-in tcp support, drop dependency on netcat.
Python
mit
vadimcn/vscode-lldb,vadimcn/vscode-lldb,NeroProtagonist/vscode-lldb,NeroProtagonist/vscode-lldb,NeroProtagonist/vscode-lldb,vadimcn/vscode-lldb,NeroProtagonist/vscode-lldb,vadimcn/vscode-lldb,NeroProtagonist/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb
a27a525650571b6f3756edf7f0fdf82d724f22d3
performance/web.py
performance/web.py
import requests from time import time class Client: def __init__(self, host, requests, do_requests_counter): self.host = host self.requests = requests self.counter = do_requests_counter class Request: GET = 'get' POST = 'post' def __init__(self, url, type=GET, data=None): ...
import requests from time import time class Client: def __init__(self, host, requests, do_requests_counter): self.host = host self.requests = requests self.counter = do_requests_counter class Request: GET = 'get' POST = 'post' def __init__(self, url, type=GET, data=None): ...
Update function name and return value
Update function name and return value
Python
mit
BakeCode/performance-testing,BakeCode/performance-testing
a3dd19f7825bcbc65c666dc5e45af1084c061a12
{{cookiecutter.extension_name}}/{{cookiecutter.extension_name}}/__init__.py
{{cookiecutter.extension_name}}/{{cookiecutter.extension_name}}/__init__.py
from IPython.display import display import json # Running `npm run build` will create static resources in the static # directory of this Python package (and create that directory if necessary). def _jupyter_labextension_paths(): return [{ 'name': '{{cookiecutter.extension_name}}', 'src': 'static...
from IPython.display import display, JSON import json # Running `npm run build` will create static resources in the static # directory of this Python package (and create that directory if necessary). def _jupyter_labextension_paths(): return [{ 'name': '{{cookiecutter.extension_name}}', 'src': '...
Use sub-class of IPython.display.JSON vs. display function
Use sub-class of IPython.display.JSON vs. display function
Python
cc0-1.0
gnestor/mimerender-cookiecutter,jupyterlab/mimerender-cookiecutter,jupyterlab/mimerender-cookiecutter,gnestor/mimerender-cookiecutter
ac605b9efdfa0a195a4c9a76800e969098a003ae
test/test_ticket.py
test/test_ticket.py
import unittest from mock import Mock import sys import os import datetime from pytrac import Ticket class TestTicket(unittest.TestCase): def setUp(self): server = Mock() self.ticket = Ticket(server) def testSearchWithAllParams(self): self.ticket.search(summary='test_summary', owner...
import pytest from mock import Mock import sys import os import datetime from pytrac import Ticket class TestTicket(object): def setup_class(self): server = Mock() self.ticket = Ticket(server) def testSearchWithAllParams(self): self.ticket.search(summary='test_summary', owner='someo...
Use pytest for unit test
Use pytest for unit test
Python
apache-2.0
Jimdo/pytrac,Jimdo/pytrac
ea56607fa7ae7257682170e881c67ae5e0f6719c
tests/rest_views.py
tests/rest_views.py
from django.views.generic import View from nap.datamapper.models import ModelDataMapper from nap.rest import views from .models import Poll class PollMapper(ModelDataMapper): class Meta: model = Poll fields = ['question', 'pub_date'] class SinglePollView(views.ObjectGetMixin, views.ObjectPutMi...
from django.views.generic import View from nap.datamapper.models import ModelDataMapper from nap.rest import views from .models import Poll class PollMapper(ModelDataMapper): class Meta: model = Poll fields = ['question', 'pub_date'] class SinglePollView(views.ObjectGetMixin, views.ObjectPutMi...
Update test to use Base view
Update test to use Base view
Python
bsd-3-clause
MarkusH/django-nap,limbera/django-nap
9bb1aebbfc0ca0ff893bafe99de3c32c2ba99952
tests/test_model.py
tests/test_model.py
from context import models from models import model import unittest class test_logic_core(unittest.TestCase): def setUp(self): self.room = model.Room(20, 'new_room') self.room1 = model.Room(6, 'new_room1') self.livingspace = model.LivingSpace('orange') self.office = model.Office(...
from context import models from models import model import unittest class test_model(unittest.TestCase): def setUp(self): self.room = model.Room(20, 'new_room') self.room1 = model.Room(6, 'new_room1') self.livingspace = model.LivingSpace('orange') self.office = model.Office('manj...
Refactor model test to test added properties
Refactor model test to test added properties
Python
mit
georgreen/Geoogreen-Mamboleo-Dojo-Project
3a414d5d4763802bc4bc506a57c1f487655d470a
engineering_project/estimatedtime.py
engineering_project/estimatedtime.py
#!/usr/bin/env python3 import statistics class estimatedtime: def __init__(self, numberofpoints): self.listoftimes = [] self.points = numberofpoints def append(self, timeinseconds, inferprogress=True): # print(timeinseconds) self.listoftimes.append(timeinseconds) ...
#!/usr/bin/env python3 import statistics class ETC: ''' Estimated Time to Completion ''' def __init__(self, numberofpoints): self.listoftimes = [] self.points = numberofpoints + 1 def append(self, timeinseconds, inferprogress=True): # print(timeinseconds) self....
Change estimated time class to ETC
Change estimated time class to ETC
Python
mit
DavidLutton/EngineeringProject
c6d345d01f59965155d9d912615a1eef939c32cb
Xls/Reader/excel_xlrd.py
Xls/Reader/excel_xlrd.py
import xlrd import json import sys import os import argparse def run(argv): parser = argparse.ArgumentParser() parser.add_argument('--size') parser.add_argument('--start') parser.add_argument('--action') parser.add_argument('--file') args = parser.parse_args() if False == os.path.isfile(args.file): ...
import xlrd import json import sys import os import argparse def run(argv): parser = argparse.ArgumentParser() parser.add_argument('--size') parser.add_argument('--start') parser.add_argument('--action') parser.add_argument('--file') parser.add_argument('--max-empty-rows', dest="max_empty_rows") args = p...
Fix empty argument "max-empty-rows" in xls script We send argument "max-empty-rows" to two different script. In xls need to set, that this argument is available
Fix empty argument "max-empty-rows" in xls script We send argument "max-empty-rows" to two different script. In xls need to set, that this argument is available
Python
mit
arodiss/XlsBundle,arodiss/XlsBundle
61693f27510567f4f2f5af2b51f95ae465290d9a
tests/test_directory/test_domain.py
tests/test_directory/test_domain.py
''' Creates all tests to serialize XMLs to xml_curl ''' import logging import pytest from lxml import etree from mock import Mock from wirecurly.directory import Domain, User def test_domain_no_users(): domain = Domain('wirephone.com.ar') response = domain.todict() assert domain.domain == 'wirepho...
''' Creates all tests to serialize XMLs to xml_curl ''' import logging import pytest from lxml import etree from mock import Mock from wirecurly.directory import Domain, User def test_domain_no_users(): domain = Domain('wirephone.com.ar') response = domain.todict() assert domain.domain == 'wirepho...
Add tests for addUsersToGroup function
Add tests for addUsersToGroup function
Python
mpl-2.0
IndiciumSRL/wirecurly
48ea5605807ec9798b77317a73446f4dc335f70a
main.py
main.py
import document import time evalstr = ''' var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText); ''' b = document.createElement('button') b.innerHTML = 'Run' b.setAttribute('id', 'runinjector') b.setAttribute('onclick', eval...
import document import time evalstr = ''' var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText); ''' b = document.createElement('button') b.innerHTML = 'Run' b.setAttribute('id', 'runinjector') b.setAttribute('onclick', eval...
Implement the Python side of Canvas.fillRect
Implement the Python side of Canvas.fillRect
Python
mit
Zirientis/skulpt-canvas,Zirientis/skulpt-canvas
0fb7f7950039d937df35f90a44cabc5603d238de
main.py
main.py
import os import json import sys from pprint import pprint def loadJSON(fInput): with open(fInput) as f: return json.load(f) return None if __name__ == '__main__': filePath = 'data/example.json' data = loadJSON(filePath) # check if the data is loaded correctly if data is None: ...
import os import json import sys from pprint import pprint def loadJSON(fInput): with open(fInput) as f: return json.load(f) return None if __name__ == '__main__': filePath = 'data/example.json' data = loadJSON(filePath) # check if the data is loaded correctly if data is None: ...
Add method definition generator and some sample for test
Add method definition generator and some sample for test
Python
apache-2.0
kilikkuo/kernel-mapper,PyOCL/kernel-mapper
f253feac7a4c53bd17958b0c74adbec528ae2e17
rethinkdb/setup-rethinkdb.py
rethinkdb/setup-rethinkdb.py
#!/usr/bin/env python3 import rethinkdb as r import argparse parser = argparse.ArgumentParser(description='Set up RethinkDB locally') args = parser.parse_args() conn = r.connect() r.db_create('muzhack').run(conn) r.db('muzhack').table_create('users').run(conn) r.db('muzhack').table_create('projects').run(conn) r.db(...
#!/usr/bin/env python3 import rethinkdb as r import argparse parser = argparse.ArgumentParser(description='Set up RethinkDB') parser.add_argument('-H', '--host', default='localhost', help='Specify host') args = parser.parse_args() conn = r.connect(host=args.host) r.db_create('muzhack').run(conn) r.db('muzhack').tabl...
Allow setting up rethinkdb remotely
Allow setting up rethinkdb remotely
Python
mit
muzhack/musitechhub,muzhack/musitechhub,muzhack/musitechhub,muzhack/muzhack,muzhack/muzhack,muzhack/musitechhub,muzhack/muzhack,muzhack/muzhack
5bd9de24e63c557aed1779f6cee611cfeb52ddc0
envs.py
envs.py
import os import gym from gym.spaces.box import Box from baselines import bench from baselines.common.atari_wrappers import wrap_deepmind try: import pybullet_envs except ImportError: pass def make_env(env_id, seed, rank, log_dir): def _thunk(): env = gym.make(env_id) env.seed(seed + ra...
import os import gym from gym.spaces.box import Box from baselines import bench from baselines.common.atari_wrappers import wrap_deepmind try: import pybullet_envs except ImportError: pass def make_env(env_id, seed, rank, log_dir): def _thunk(): env = gym.make(env_id) env.seed(seed + ra...
Change the ugly hack to detect atari
Change the ugly hack to detect atari
Python
mit
YuhangSong/GTN,YuhangSong/GTN,ikostrikov/pytorch-a2c-ppo-acktr
ee130df5b48d1e4196bb9159de64e279656cdfcf
byceps/blueprints/snippet/views.py
byceps/blueprints/snippet/views.py
""" byceps.blueprints.snippet.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from flask import abort, g from ...services.snippet import mountpoint_service from ...util.framework.blueprint import create_blueprint from .templating ...
""" byceps.blueprints.snippet.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from flask import abort, g, url_for from ...services.snippet import mountpoint_service from ...util.framework.blueprint import create_blueprint from .te...
Introduce global template function `url_for_snippet`
Introduce global template function `url_for_snippet` Use it to ease the transition to a multisite-capable snippet URL rule system.
Python
bsd-3-clause
m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
26eec2d069075c662d5b935474e8a2eea0d195b5
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Anton Lavrenov # Copyright (c) 2014 Anton Lavrenov # # License: MIT # """This module exports the Tslint plugin class.""" from SublimeLinter.lint import Linter, util class Tslint(Linter): """Provides an interf...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Anton Lavrenov # Copyright (c) 2014 Anton Lavrenov # # License: MIT # """This module exports the Tslint plugin class.""" from SublimeLinter.lint import Linter, util class Tslint(Linter): """Provides an interf...
Add support for typescriptreact *.tsx files
Add support for typescriptreact *.tsx files
Python
mit
lavrton/SublimeLinter-contrib-tslint
d79edc34bece193b0cf1bc7117c3559ed62e0a7f
main.py
main.py
#!/usr/bin/python3 # -*- coding: utf8 -* import sys # Fix for file paths errors import os PATH = os.path.dirname(os.path.realpath(__file__)) # Import other files from the project from game import Game from idlerpg import IdleRPG from logger import log, story # Import Graphic Lib from PyQt5.QtWidgets import (QApplic...
#!/usr/bin/python3 # -*- coding: utf8 -* import sys # Fix for file paths errors import os PATH = os.path.dirname(os.path.realpath(__file__)) # Import other files from the project from game import Game from idlerpg import IdleRPG from logger import log, story # Import Graphic Lib from PyQt5.QtWidgets import QApplica...
Remove a bunch of unnecessary import
FIX: Remove a bunch of unnecessary import
Python
mit
DanielNautre/idle-rpg
c8177562558d4b59d6d0a8f3fb4518c067394a31
comrade/core/decorators.py
comrade/core/decorators.py
from django.utils.decorators import available_attrs from django.utils.http import urlquote from django.http import HttpResponse from django.template import loader, RequestContext from functools import wraps def singleton(cls): instances = {} def getinstance(): if cls not in instances: inst...
from django.utils.decorators import available_attrs from django.utils.http import urlquote from django.http import HttpResponse from django.template import loader, RequestContext from functools import wraps def singleton(cls): instances = {} def getinstance(): if cls not in instances: inst...
Use authorized + test_func instead of custom decorator.
Use authorized + test_func instead of custom decorator.
Python
mit
bueda/django-comrade
30a4281f2602bd6b9d90d89375785a2645854a0d
enthought/enable2/pyglet_backend/pyglet_app.py
enthought/enable2/pyglet_backend/pyglet_app.py
# proxy from enthought.enable.pyglet_backend.pyglet_app import *
# proxy __all__ = ["get_app", "PygletApp"] from enthought.enable.pyglet_backend.pyglet_app import * # Import the objects which are not declared in __all__, # but are still defined in the real module, such that people # can import them explicitly when needed, just as they could # with the real module. # # It is unli...
Improve the proxy module which maps to a module which uses __all__.
Improve the proxy module which maps to a module which uses __all__. The notes I made in the code apply to all proxy modules which map to a module which uses __all__.
Python
bsd-3-clause
tommy-u/enable,tommy-u/enable,tommy-u/enable,tommy-u/enable
2d0e742c0f8d5f0a9d72b8c2c6fa751ba7842668
tests/test_json.py
tests/test_json.py
from __future__ import absolute_import import fnmatch import os import unittest from . import validate_json_format class TestSettings(unittest.TestCase): def _get_json_files(self, file_pattern, folder='.'): for root, dirnames, filenames in os.walk(folder): for filename in fnmatch.filter(file...
from __future__ import absolute_import import fnmatch import os import unittest from . import validate_json_format class TestSettings(unittest.TestCase): def _get_json_files(self, file_pattern, folder='.'): for root, dirnames, filenames in os.walk(folder): for filename in fnmatch.filter(file...
Include sublime-keymap files in JSON format tests.
Include sublime-keymap files in JSON format tests.
Python
mit
jonlabelle/Trimmer,jonlabelle/Trimmer
ff0ae66ee16bc3ac07cb88ddacb52ffa41779757
tests/test_func.py
tests/test_func.py
from .utils import assert_eval def test_simple_func(): assert_eval('(def @a $a 8) (@a)', 1, 8) def test_simple_func_args(): assert_eval( '(def @a $a $a)' '(@a 1)' '(@a 2)' '(@a 5)', 1, 1, 2, 5) def test_func_args_overwrite_globals(): asse...
from .utils import assert_eval def test_simple_func(): assert_eval('(def @a $a 8) (@a)', 1, 8) def test_simple_func_args(): assert_eval( '(def @a $a $a)' '(@a 1)' '(@a 2)' '(@a 5)', 1, 1, 2, 5) def test_func_args_overwrite_globals(): asse...
Add some more function tests.
Add some more function tests.
Python
bsd-3-clause
sapir/tinywhat,sapir/tinywhat,sapir/tinywhat
c9c618cfcd8caeac9ba23ec1c53d3ebdf32d563d
src/cli/_errors.py
src/cli/_errors.py
""" Error heirarchy for stratis cli. """ class StratisCliError(Exception): """ Top-level stratis cli error. """ pass class StratisCliValueError(StratisCliError): """ Raised when a parameter has an unacceptable value. May also be raised when the parameter has an unacceptable type. """...
""" Error heirarchy for stratis cli. """ class StratisCliError(Exception): """ Top-level stratis cli error. """ pass class StratisCliValueError(StratisCliError): """ Raised when a parameter has an unacceptable value. May also be raised when the parameter has an unacceptable type. """...
Add an exception useful for prototyping.
Add an exception useful for prototyping. Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>
Python
apache-2.0
stratis-storage/stratis-cli,stratis-storage/stratis-cli
8373c005cbf8ebc4069faf5291bb126db2cbb20f
polygraph/types/tests/test_scalars.py
polygraph/types/tests/test_scalars.py
from unittest import TestCase from polygraph.types.scalar import Int class IntTest(TestCase): def test_class_types(self): x = Int(245) self.assertIsInstance(x, int) self.assertIsInstance(x, Int) self.assertEqual(Int(245) + 55, 300) y = Int("506") self.assertIsInsta...
from unittest import TestCase from polygraph.types.scalar import Boolean, Float, Int, String class IntTest(TestCase): def test_class_types(self): x = Int(245) self.assertIsInstance(x, int) self.assertIsInstance(x, Int) self.assertEqual(Int(245) + 55, 300) y = Int("506") ...
Add additional tests around scalars
Add additional tests around scalars
Python
mit
polygraph-python/polygraph
e1ffdcc5f12be623633e2abab2041fcb574173ea
homeassistant/components/zeroconf.py
homeassistant/components/zeroconf.py
""" This module exposes Home Assistant via Zeroconf. Zeroconf is also known as Bonjour, Avahi or Multicast DNS (mDNS). For more details about Zeroconf, please refer to the documentation at https://home-assistant.io/components/zeroconf/ """ import logging import socket from homeassistant.const import (EVENT_HOMEASSIS...
""" This module exposes Home Assistant via Zeroconf. Zeroconf is also known as Bonjour, Avahi or Multicast DNS (mDNS). For more details about Zeroconf, please refer to the documentation at https://home-assistant.io/components/zeroconf/ """ import logging import socket from homeassistant.const import (EVENT_HOMEASSIS...
Use hass.config.api instead of hass.http
Use hass.config.api instead of hass.http
Python
mit
miniconfig/home-assistant,Julian/home-assistant,toddeye/home-assistant,ct-23/home-assistant,deisi/home-assistant,tchellomello/home-assistant,rohitranjan1991/home-assistant,Julian/home-assistant,Duoxilian/home-assistant,betrisey/home-assistant,keerts/home-assistant,ct-23/home-assistant,tboyce021/home-assistant,kyvinh/ho...
c24fa91c900fc4f0d3ac5a10d10bfe5c57c9ef5c
errors.py
errors.py
class ParserError(Exception): """Raised when parsing input fails.""" class OpenParenError(ParserError): """Raised when there are too few opening parenthesis.""" @staticmethod def build(): return OpenParenError("too few opening parenthesis") class CloseParenError(ParserError): """Raised w...
class ParserError(Exception): """Raised when parsing input fails.""" class OpenParenError(ParserError): """Raised when there are too few opening parenthesis.""" @staticmethod def build(): return OpenParenError("too few opening parenthesis") class CloseParenError(ParserError): """Raised w...
Support class tuples as WATE args
Support class tuples as WATE args
Python
mit
jasontbradshaw/plinth
9af440d8d7d2dc7b6ecf254ee1150f03d090cb6a
numpy/linalg/setup.py
numpy/linalg/setup.py
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info config = Configuration('linalg',parent_package,top_path) config.add_data_dir('tests') # Configure lapack_lite lapack_info = get_info('lapack...
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info config = Configuration('linalg',parent_package,top_path) config.add_data_dir('tests') # Configure lapack_lite lapack_info = get_info('lapack...
Disable pythonxerbla.c patch for win32 (the MSVC linker failes on multiple defined symbols) when using optimized lapack.
Disable pythonxerbla.c patch for win32 (the MSVC linker failes on multiple defined symbols) when using optimized lapack.
Python
bsd-3-clause
jschueller/numpy,CMartelLML/numpy,cowlicks/numpy,larsmans/numpy,rudimeier/numpy,bertrand-l/numpy,ViralLeadership/numpy,sonnyhu/numpy,mattip/numpy,moreati/numpy,ViralLeadership/numpy,pyparallel/numpy,dato-code/numpy,mattip/numpy,nbeaver/numpy,dch312/numpy,ajdawson/numpy,WarrenWeckesser/numpy,leifdenby/numpy,larsmans/num...
3b01b6b67e8cf05c31f2c30a3e45a59ffbb31adb
djangae/fields/computed.py
djangae/fields/computed.py
from django.db import models class ComputedFieldMixin(object): def __init__(self, func, *args, **kwargs): self.computer = func kwargs["editable"] = False super(ComputedFieldMixin, self).__init__(*args, **kwargs) def pre_save(self, model_instance, add): value = self.computer(...
from django.db import models class ComputedFieldMixin(object): def __init__(self, func, *args, **kwargs): self.computer = func kwargs["editable"] = False super(ComputedFieldMixin, self).__init__(*args, **kwargs) def pre_save(self, model_instance, add): value = self.computer(...
Add from_db_value instead of removed SubfieldBase fields
Add from_db_value instead of removed SubfieldBase fields
Python
bsd-3-clause
kirberich/djangae,asendecka/djangae,kirberich/djangae,potatolondon/djangae,kirberich/djangae,potatolondon/djangae,grzes/djangae,asendecka/djangae,grzes/djangae,grzes/djangae,asendecka/djangae
fc105f413e6683980c5d2fcc93a471ebbc9fecba
utils/files_provider.py
utils/files_provider.py
from string import Template __author__ = 'maa' templates_folder = 'file_templates_folder\\' def create_and_full_fill_file(template_file_name, destination_file_path, file_name, kwargs): template_file = open(templates_folder + template_file_name, 'r') file_content = template_file.read() template_file.clos...
from string import Template __author__ = 'maa' templates_folder = 'file_templates_folder\\' def create_and_full_fill_file(template_file_name, destination_file_path, kwargs): template_file = open(template_file_name, 'r') file_content = template_file.read() template_file.close() template = Template(f...
Change method params because they are not necessary.
[dev] Change method params because they are not necessary.
Python
apache-2.0
amatkivskiy/baidu,amatkivskiy/baidu
f8d3b5d4c1d3d81dee1c22a4e2563e6b8d116c74
openquake/__init__.py
openquake/__init__.py
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2010-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the Licen...
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2010-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the Licen...
Make the openquake namespace compatible with old setuptools
Make the openquake namespace compatible with old setuptools Former-commit-id: 529c98ec0a7c5a3fefa4da6cdf2f6a58b5487ebc [formerly e5f4dc01e94694bf9bfcae3ecd6eca34a33a24eb] Former-commit-id: e01df405c03f37a89cdf889c45de410cb1ca9b00
Python
agpl-3.0
gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine
8e67071e82e13ae4131da773947f767f1fe91f40
Code/Python/Kamaelia/Examples/UDP_Systems/SimplePeer_Example.py
Code/Python/Kamaelia/Examples/UDP_Systems/SimplePeer_Example.py
#!/usr/bin/python """ Simple Kamaelia Example that shows how to use a simple UDP Peer. A UDP Peer actually sends and recieves however, so we could have more fun example here with the two peers sending each other messages. It's worth noting that these aren't "connected" peers in any shape or form, and they're fixed who...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Vers...
Change license to Apache 2
Change license to Apache 2
Python
apache-2.0
sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia
1c65ef8eeccd433b256ed2cd1d3db7b6264fe8f2
properties/tests/test_mach_angle.py
properties/tests/test_mach_angle.py
#!/usr/bin/env python """Test Mach angle functions. Test data is obtained from http://www.grc.nasa.gov/WWW/k-12/airplane/machang.html. """ import nose import nose.tools as nt from properties.prandtl_meyer_function import mu_in_deg @nt.raises(ValueError) def test_mach_lesser_than_one(): m = 0.1 mu_in_deg(...
#!/usr/bin/env python """Test Mach angle functions. """ from __future__ import absolute_import, division import nose import nose.tools as nt from properties.prandtl_meyer_function import mu_in_deg @nt.raises(ValueError) def test_mach_lesser_than_one(): m = 0.1 mu_in_deg(m) def test_normal_mach(): m1...
Correct test data for mach angle
Correct test data for mach angle
Python
mit
iwarobots/TunnelDesign
d028ada7a1d1c7c66cb6e3e76cd5ed676981bc57
lcp/urls.py
lcp/urls.py
"""lcp URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based v...
"""lcp URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based v...
Move the API to the root.
Move the API to the root.
Python
bsd-2-clause
mblayman/lcp,mblayman/lcp,mblayman/lcp
f5d61059480a2698fc955641819e78cba28173b3
src/adhocracy_core/adhocracy_core/changelog/test_init.py
src/adhocracy_core/adhocracy_core/changelog/test_init.py
from pytest import mark from pytest import fixture from pyramid import testing def test_changelog_create(): from . import Changelog from . import changelog_meta inst = Changelog() assert inst['/path/'] == changelog_meta @fixture() def integration(config): config.include('adhocracy_core.events') ...
from pytest import mark from pytest import fixture from pyramid import testing def test_changelog_create(): from . import Changelog from . import changelog_meta inst = Changelog() assert inst['/path/'] == changelog_meta @fixture() def integration(config): config.include('adhocracy_core.events') ...
Improve test coverage for changelog module
Improve test coverage for changelog module
Python
agpl-3.0
liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocra...
179c13d3fe2589d43e260da86e0465901d149a80
rsk_mind/datasource/datasource_csv.py
rsk_mind/datasource/datasource_csv.py
import csv from datasource import Datasource from ..dataset import Dataset class CSVDatasource(Datasource): def read(self): with open(self.path, 'rb') as infile: reader = csv.reader(infile) header = reader.next() rows = [] for row in reader: ...
import csv from datasource import Datasource from ..dataset import Dataset class CSVDatasource(Datasource): def __init__(self, path, target=None): super(CSVDatasource, self).__init__(path) self.target = target def read(self): with open(self.path, 'rb') as infile: reader = ...
Set targe class on csv document
Set targe class on csv document
Python
mit
rsk-mind/rsk-mind-framework
42c7b4c7b74a3aeccca73f368a16a2f96295ff3b
radar/radar/models/user_sessions.py
radar/radar/models/user_sessions.py
from sqlalchemy import String, Column, Integer, ForeignKey, DateTime, Index from sqlalchemy.dialects import postgresql from sqlalchemy.orm import relationship from radar.database import db from radar.models.users import User, AnonymousUser from radar.models.logs import log_changes @log_changes class UserSession(db.M...
from sqlalchemy import String, Column, Integer, ForeignKey, DateTime, Index from sqlalchemy.dialects import postgresql from sqlalchemy.orm import relationship, backref from radar.database import db from radar.models.users import User, AnonymousUser from radar.models.logs import log_changes @log_changes class UserSes...
Delete user sessions with user
Delete user sessions with user
Python
agpl-3.0
renalreg/radar,renalreg/radar,renalreg/radar,renalreg/radar
38d9a85bc23bfcf3e44081d3077bbd5ca333fdf3
src/damis/api/serializers.py
src/damis/api/serializers.py
from django.contrib.auth.models import User, Group from rest_framework import serializers from damis.models import Dataset, Algorithm, Experiment class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups') class GroupSeria...
from django.contrib.auth.models import User, Group from rest_framework import serializers from damis.models import Dataset, Algorithm, Experiment class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups') class GroupSeria...
Allow modify experiment status via REST API.
Allow modify experiment status via REST API.
Python
agpl-3.0
InScience/DAMIS-old,InScience/DAMIS-old
c265b49a5961f48542d22d8a4174ee885568c08c
luigi/tasks/export/fasta/__init__.py
luigi/tasks/export/fasta/__init__.py
# -*- coding: utf-8 -*- """ Copyright [2009-2017] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by...
# -*- coding: utf-8 -*- """ Copyright [2009-2017] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by...
Simplify the general Fasta export task
Simplify the general Fasta export task It doesn't need to be so complicated, so we simplify it.
Python
apache-2.0
RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline
dcdfe91570e185df19daef49be9a368276e20483
src/core/migrations/0039_fix_reviewer_url.py
src/core/migrations/0039_fix_reviewer_url.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.28 on 2020-05-15 15:52 from __future__ import unicode_literals import re from django.db import migrations REGEX = re.compile("({%\ ?journal_url 'do_review' review_assignment.id\ ?%})") OUTPUT = "{{ review_url }}" def replace_template(apps, schema_editor): Settin...
# -*- coding: utf-8 -*- # Generated by Django 1.11.28 on 2020-05-15 15:52 from __future__ import unicode_literals import re from django.db import migrations REGEX = re.compile("({%\ ?journal_url 'do_review' review_assignment.id\ ?%})") OUTPUT = "{{ review_url }}" def replace_template(apps, schema_editor): Settin...
Handle migrating non-string values (i.e.: NULL)
Handle migrating non-string values (i.e.: NULL)
Python
agpl-3.0
BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway
43c62ea6d5558b0e6e5104eb05d45d89239e70b8
q3/FindAllAbbreviations.py
q3/FindAllAbbreviations.py
import sys def prependAbbrev(front, abbr): if type(front) is type(abbr[0]): return [front + abbr[0]] + abbr[1:] else: return [front] + abbr def prefixAll(p, lst): return [prependAbbrev(p, l) for l in lst] def findAllAbbrev(s): if len(s) == 1: return [[s], [1]] else: ...
import sys def prependAbbrev(front, abbr): if type(front) is type(abbr[0]): return [front + abbr[0]] + abbr[1:] else: return [front] + abbr def prefixAll(p, lst): return [prependAbbrev(p, l) for l in lst] def findAllAbbrev(s): if len(s) == 1: return [[s], [1]] else: ...
Print usage if no word given
Print usage if no word given
Python
mit
UW-UPL/InterviewPrepJan2016,UW-UPL/InterviewPrepJan2016,UW-UPL/InterviewPrepJan2016,UW-UPL/InterviewPrepJan2016
d85d04da0f6ce283f53678bd81bd0987f59ce766
curldrop/cli.py
curldrop/cli.py
import click import os from .app import app from .server import StandaloneServer @click.command() @click.option( '--port', default=8000, help='Port to listen on, default is 8000' ) @click.option( '--upload-dir', default=os.getcwd(), help='Directory where uploads are stored, if not specified th...
import click import os from .app import app from .server import StandaloneServer @click.command() @click.option( '--port', default=8000, help='Port to listen on, default is 8000' ) @click.option( '--upload-dir', default=os.getcwd(), help='Directory where uploads are stored, if not specified th...
Make gunicorn log to stdout/stderr
Make gunicorn log to stdout/stderr
Python
mit
kennell/curldrop,kevvvvv/curldrop
3e03d66c5351ac5e71f82a56aa01ba06865e1c25
conda_verify/cli.py
conda_verify/cli.py
import os import sys from optparse import OptionParser from conda_verify.errors import RecipeError from conda_verify.verify import Verify from conda_verify.utilities import render_metadata, iter_cfgs def cli(): p = OptionParser( usage="usage: %prog [options] <path to recipes or packages>", descr...
import os import sys from optparse import OptionParser from conda_verify.errors import RecipeError from conda_verify.verify import Verify from conda_verify.utilities import render_metadata, iter_cfgs def cli(): p = OptionParser( usage="usage: %prog [options] <path to recipes or packages>", descr...
Change script run message output
Change script run message output
Python
bsd-3-clause
mandeep/conda-verify
67637039b95f4030a462edb35d614bb678426dd3
conversion_check.py
conversion_check.py
def check_iso_mcp(input_file): """ Checks if MCP conversion is allowed for the given file. MCP files are only created if the DIF has an ISO Topic Category of "OCEANS". """ allowed = False # Cannot use the following check: # oceans_tag = '<ISO_Topic_Category>OCEANS</ISO_Topic_Category>' # This is because som...
def check_iso_mcp(input_file): """ Checks if MCP conversion is allowed for the given file. MCP files are only created if the DIF has an ISO Topic Category of "OCEANS". """ allowed = False # Cannot use the following check: # oceans_tag = '<ISO_Topic_Category>OCEANS</ISO_Topic_Category>' # This is because som...
Add ANDS RIF-CS conversion check function
Add ANDS RIF-CS conversion check function
Python
mit
AustralianAntarcticDataCentre/metadata_xml_convert,AustralianAntarcticDataCentre/metadata_xml_convert
a57d4e3e1fa65b11b55d6f46dd778cdaf1ed8504
webstack_django_sorting/middleware.py
webstack_django_sorting/middleware.py
def get_field(self): try: field = self.REQUEST['sort'] except (KeyError, ValueError, TypeError): field = '' return (self.direction == 'desc' and '-' or '') + field def get_direction(self): try: return self.REQUEST['dir'] except (KeyError, ValueError, TypeError): retu...
def get_field(self): try: field = self.GET['sort'] except (KeyError, ValueError, TypeError): field = '' return (self.direction == 'desc' and '-' or '') + field def get_direction(self): try: return self.GET['dir'] except (KeyError, ValueError, TypeError): return 'desc...
Fix deprecated use of REQUEST and only read the GET request
Fix deprecated use of REQUEST and only read the GET request RemovedInDjango19Warning: `request.REQUEST` is deprecated, use `request.GET` or `request.POST` instead.
Python
bsd-3-clause
artscoop/webstack-django-sorting,artscoop/webstack-django-sorting
1b44849f9fac68c6ce0732baded63681cbf58ccb
osmaxx-py/osmaxx/contrib/auth/tests/test_frontend_permissions.py
osmaxx-py/osmaxx/contrib/auth/tests/test_frontend_permissions.py
from django.test import TestCase from django.contrib.auth.models import User, Group from osmaxx.contrib.auth.frontend_permissions import user_in_osmaxx_group, FRONTEND_USER_GROUP class TestFrontendPermissions(TestCase): def test_superuser_can_access_frontend_even_if_not_in_osmaxx_group(self): an_admin = U...
from django.test import TestCase from django.contrib.auth.models import User, Group from osmaxx.contrib.auth.frontend_permissions import user_in_osmaxx_group, FRONTEND_USER_GROUP class TestFrontendPermissions(TestCase): def test_user_can_not_access_frontend_by_default(self): a_user = User.objects.create_u...
Test that users can not access frontend by default
Test that users can not access frontend by default
Python
mit
geometalab/osmaxx,geometalab/osmaxx-frontend,geometalab/osmaxx-frontend,geometalab/drf-utm-zone-info,geometalab/osmaxx-frontend,geometalab/osmaxx,geometalab/drf-utm-zone-info,geometalab/osmaxx,geometalab/osmaxx-frontend,geometalab/osmaxx
43c3a8a94c7783aadb440e529645f7db7c7913ff
successstories/forms.py
successstories/forms.py
from django import forms from .models import Story from cms.forms import ContentManageableModelForm class StoryForm(ContentManageableModelForm): class Meta: model = Story fields = ( 'name', 'company_name', 'company_url', 'category', 'aut...
from django import forms from .models import Story from cms.forms import ContentManageableModelForm class StoryForm(ContentManageableModelForm): pull_quote = forms.CharField(widget=forms.Textarea(attrs={'rows': 5})) class Meta: model = Story fields = ( 'name', 'compan...
Reduce textarea height in Story form
Reduce textarea height in Story form
Python
apache-2.0
proevo/pythondotorg,manhhomienbienthuy/pythondotorg,manhhomienbienthuy/pythondotorg,Mariatta/pythondotorg,python/pythondotorg,python/pythondotorg,Mariatta/pythondotorg,manhhomienbienthuy/pythondotorg,proevo/pythondotorg,Mariatta/pythondotorg,python/pythondotorg,manhhomienbienthuy/pythondotorg,python/pythondotorg,Mariat...
e56e47828d381022cb2742b06f7f47d3fb64a499
hiicart/gateway/braintree/tasks.py
hiicart/gateway/braintree/tasks.py
import logging from celery.decorators import task from hiicart.models import HiiCart from hiicart.gateway.braintree.ipn import BraintreeIPN log = logging.getLogger('hiicart.gateway.braintree.tasks') @task def update_payment_status(hiicart_id, transaction_id, tries=0): """Check the payment status of a Braintree...
import logging from celery.decorators import task from hiicart.models import HiiCart from hiicart.gateway.braintree.ipn import BraintreeIPN log = logging.getLogger('hiicart.gateway.braintree.tasks') @task def update_payment_status(hiicart_id, transaction_id, tries=0, cart_class=HiiCart): """Check the payment s...
Make cart class configurable for braintree task
Make cart class configurable for braintree task
Python
mit
hiidef/hiicart,hiidef/hiicart
cb9b7dcd01495999fac0671acd9e4bf138bd71ea
scripts/spotify-current.py
scripts/spotify-current.py
#!/usr/bin/python # -*- coding: utf-8 -*- import dbus session_bus = dbus.SessionBus() spotify_bus = session_bus.get_object('org.mpris.MediaPlayer2.spotify', '/org/mpris/MediaPlayer2') spotify_properties = dbus.Interface(spotify_bus, 'org.freedesktop.DBus.Properties') metadata = spotify_properties.Get('org.mpris.Media...
#!/usr/bin/python # -*- coding: utf-8 -*- import dbus session_bus = dbus.SessionBus() spotify_bus = session_bus.get_object('org.mpris.MediaPlayer2.spotify', '/org/mpris/MediaPlayer2') spotify_properties = dbus.Interface(spotify_bus, 'org.freedesktop.DBus.Properties') metadata = spotify_properties.Get('org.mpris.Media...
Truncate spotify current song if it is too long
Truncate spotify current song if it is too long
Python
mit
EllisV/dotfiles,EllisV/dotfiles
26de8a5b63d6da42bbafaa3d520fe0fbbb3a7d54
cms/utils/encoder.py
cms/utils/encoder.py
# -*- coding: utf-8 -*- from django.utils.html import conditional_escape from django.core.serializers.json import DjangoJSONEncoder class SafeJSONEncoder(DjangoJSONEncoder): def _recursive_escape(self, o, esc=conditional_escape): if isinstance(o, dict): return type(o)((esc(k), self._recursive_...
# -*- coding: utf-8 -*- from django.utils.html import conditional_escape from django.core.serializers.json import DjangoJSONEncoder class SafeJSONEncoder(DjangoJSONEncoder): def _recursive_escape(self, o, esc=conditional_escape): if isinstance(o, dict): return type(o)((esc(k), self._recursive_...
Fix copy page when permission is disabled
Fix copy page when permission is disabled
Python
bsd-3-clause
frnhr/django-cms,andyzsf/django-cms,jeffreylu9/django-cms,timgraham/django-cms,qnub/django-cms,leture/django-cms,mkoistinen/django-cms,chmberl/django-cms,saintbird/django-cms,datakortet/django-cms,keimlink/django-cms,josjevv/django-cms,youprofit/django-cms,Livefyre/django-cms,takeshineshiro/django-cms,chkir/django-cms,...
ce25be4609f6206343cdcb34b5342843f09f557b
server.py
server.py
from flask import Flask from SPARQLWrapper import SPARQLWrapper, JSON from flask import request, jsonify from flask.ext.cors import CORS app = Flask(__name__) CORS(app) @app.route('/') def hello_world(): auth = request.authorization query = request.args.get('query') if not auth is None and not query is N...
from flask import Flask from SPARQLWrapper import SPARQLWrapper, JSON from flask import request, jsonify from flask.ext.cors import CORS app = Flask(__name__) CORS(app) @app.route('/') def hello_world(): return 'hello world' @app.route('/sparql') def do_sparql(): auth = request.authorization query = requ...
Add test route for heroku
Add test route for heroku
Python
apache-2.0
jvdzwaan/visun-flask
99be36b77741a9b2e3d330eb89e0e381b3a3081f
api.py
api.py
import json from os import environ from eve import Eve from eve.io.mongo import Validator from settings import API_NAME, URL_PREFIX class KeySchemaValidator(Validator): def _validate_keyschema(self, schema, field, dct): "Validate all keys of dictionary `dct` against schema `schema`." for key, va...
import json from os import environ from eve import Eve from eve.io.mongo import Validator from settings import API_NAME, URL_PREFIX class KeySchemaValidator(Validator): def _validate_keyschema(self, schema, field, dct): "Validate all keys of dictionary `dct` against schema `schema`." for key, va...
Add utility method to delete all documents of given resource
Add utility method to delete all documents of given resource
Python
apache-2.0
gwob/Maarifa,gwob/Maarifa,gwob/Maarifa,gwob/Maarifa,gwob/Maarifa