commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
0483563fd08063e856915099075b203379e61e7c
bejmy/categories/admin.py
bejmy/categories/admin.py
from django.contrib import admin from bejmy.categories.models import Category @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ( 'name', 'user', 'transaction_type', ) list_filter = ( 'user', 'transaction_type', ) search_fields...
from django.contrib import admin from bejmy.categories.models import Category from mptt.admin import MPTTModelAdmin @admin.register(Category) class CategoryAdmin(MPTTModelAdmin): list_display = ( 'name', 'user', 'transaction_type', ) list_filter = ( 'user', 'trans...
Access to all accounts only for superusers
Access to all accounts only for superusers
Python
mit
bejmy/backend,bejmy/backend
--- +++ @@ -2,9 +2,11 @@ from bejmy.categories.models import Category +from mptt.admin import MPTTModelAdmin + @admin.register(Category) -class CategoryAdmin(admin.ModelAdmin): +class CategoryAdmin(MPTTModelAdmin): list_display = ( 'name', 'user',
c0c7222f4ab1c39dadd78c9bde40d882780ce741
benchexec/tools/legion.py
benchexec/tools/legion.py
""" BenchExec is a framework for reliable benchmarking. This file is part of BenchExec. Copyright (C) 2007-2015 Dirk Beyer All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at ...
""" BenchExec is a framework for reliable benchmarking. This file is part of BenchExec. Copyright (C) 2007-2015 Dirk Beyer All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at ...
Add some files to Legion
Add some files to Legion
Python
apache-2.0
ultimate-pa/benchexec,dbeyer/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,sosy-lab/benchexec,dbeyer/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec
--- +++ @@ -32,7 +32,10 @@ "legion-sv", "Legion.py", "__VERIFIER.c", + "__VERIFIER_assume.c", + "__VERIFIER_assume.instr.s", "__trace_jump.s", + "__trace_buffered.c", "tracejump.py", "lib", ]
4636fc514b0ebf7b16e82cc3eb7de6b69431cd43
site_analytics.py
site_analytics.py
#!/usr/local/bin/python3.6 # read nginx access log # parse and get the ip addresses and times # match ip addresses to geoip # possibly ignore bots import re def get_log_lines(path): """Return a list of regex matched log lines from the passed nginx access log path""" lines = [] with open(path) as f: r = re...
#!/usr/local/bin/python3.6 # read nginx access log # parse and get the ip addresses and times # match ip addresses to geoip # possibly ignore bots import re def get_log_lines(path): """Return a list of regex matched log lines from the passed nginx access log path""" lines = [] with open(path) as f: ...
Fix tab spacing from 2 to 4 spaces
Fix tab spacing from 2 to 4 spaces
Python
mit
mouhtasi/basic_site_analytics
--- +++ @@ -9,29 +9,28 @@ def get_log_lines(path): - """Return a list of regex matched log lines from the passed nginx access log path""" - lines = [] - with open(path) as f: - r = re.compile("""(?P<remote>[^ ]*) (?P<host>[^ ]*) (?P<user>[^ ]*) \[(?P<time>[^\]]*)\] "(?P<method>\S+)(?: +(?P<path>[^\"]*) +\S...
2264e4195e873760b922e6d346eb56d8e1ec6e09
examples/marshmallow/main.py
examples/marshmallow/main.py
import uplink # Local imports import github BASE_URL = "https://api.github.com/" if __name__ == "__main__": # Create a client that uses the marshmallow converter gh = github.GitHub( base_url=BASE_URL, converter=uplink.MarshmallowConverter() ) # Get all public repositories repos = gh.get_...
# Standard library imports from pprint import pformat # Local imports import github BASE_URL = "https://api.github.com/" if __name__ == "__main__": # Create a GitHub API client gh = github.GitHub(base_url=BASE_URL) # Get all public repositories repos = gh.get_repos() # Shorten to first 10 res...
Remove needless creation of MarshmallowConverter
Remove needless creation of MarshmallowConverter
Python
mit
prkumar/uplink
--- +++ @@ -1,15 +1,16 @@ -import uplink +# Standard library imports +from pprint import pformat # Local imports import github + BASE_URL = "https://api.github.com/" + if __name__ == "__main__": - # Create a client that uses the marshmallow converter - gh = github.GitHub( - base_url=BASE_URL, c...
4a7ef27e895ec0f22890062931a2ed68f17a1398
BadTranslator.py
BadTranslator.py
from translate import Translator translator= Translator(to_lang="ru") translation = translator.translate("Hello, world!") print translation
from translate import Translator import random langs = ["af", "ach", "ak", "am", "ar", "az", "be", "bem", "bg", "bh", "bn", "br", "bs", "ca", "chr", "ckb", "co", "crs", "cs", "cy", "da", "de", "ee", "el", "en", "eo", "es", "es-419", "et", "eu", "fa", "fi", "fo", "fr", "fy", "ga", "gaa", "gd", "gl", "gn", "gu", "ha", "h...
Add langs list, add random lang
Add langs list, add random lang Add langs list that includes all supported google translate languages. Add random language selector.
Python
mit
powderblock/PyBad-Translator
--- +++ @@ -1,4 +1,10 @@ from translate import Translator -translator= Translator(to_lang="ru") -translation = translator.translate("Hello, world!") +import random +langs = ["af", "ach", "ak", "am", "ar", "az", "be", "bem", "bg", "bh", "bn", "br", "bs", "ca", "chr", "ckb", "co", "crs", "cs", "cy", "da", "de", "ee", ...
ed36889bbac47015722d50e0253f72a609203c5e
cellardoor/serializers/msgpack_serializer.py
cellardoor/serializers/msgpack_serializer.py
import msgpack from datetime import datetime from . import Serializer def default_handler(obj): try: iterable = iter(obj) except TypeError: pass else: return list(iterable) if isinstance(obj, datetime): return obj.isoformat() raise ValueError, "Can't pack object of type %s" % type(obj).__name__ c...
import msgpack from datetime import datetime import collections from . import Serializer def default_handler(obj): if isinstance(obj, collections.Iterable): return list(obj) if isinstance(obj, datetime): return obj.isoformat() raise ValueError, "Can't pack object of type %s" % type(obj).__name__ class ...
Use more reliable method of detecting iterables in msgpack serializer
Use more reliable method of detecting iterables in msgpack serializer
Python
mit
cooper-software/cellardoor
--- +++ @@ -1,15 +1,12 @@ import msgpack from datetime import datetime +import collections from . import Serializer def default_handler(obj): - try: - iterable = iter(obj) - except TypeError: - pass - else: - return list(iterable) + if isinstance(obj, collections.Iterable): + return list(obj) if isin...
215fba180eee818b123e31a15e4b9d6a6a895c79
scripts/overhead.py
scripts/overhead.py
#!/usr/bin/env python import sys if sys.argv.__len__() < 3: print "Usage : Enter time needed for each portion of the code" print " % overhead <advance> <exchange> <regrid>" sys.exit(); a = float(sys.argv[1]) e = float(sys.argv[2]) r = float(sys.argv[3]) o = r + e print " " # print "%40s %6.1f%%" % (...
#!/usr/bin/env python import sys if sys.argv.__len__() < 3: print "Usage : Enter time needed for each portion of the code" print " % overhead <advance> <exchange> <regrid>" sys.exit(); a = float(sys.argv[1]) e = float(sys.argv[2]) r = float(sys.argv[3]) o = r + e + a print " " # print "%40s %6.1f%%"...
Make everything a percentage of the total
Make everything a percentage of the total
Python
bsd-2-clause
ForestClaw/forestclaw,ForestClaw/forestclaw,ForestClaw/forestclaw,ForestClaw/forestclaw,ForestClaw/forestclaw,ForestClaw/forestclaw
--- +++ @@ -10,7 +10,7 @@ e = float(sys.argv[2]) r = float(sys.argv[3]) -o = r + e +o = r + e + a print " " # print "%40s %6.1f%%" % ("Overhead as percentage of ADVANCE",100.0*o/a)
b4fdec74ac1af2b50ab5c79f6127d87033a9d297
wagtail/wagtailsearch/signal_handlers.py
wagtail/wagtailsearch/signal_handlers.py
from django.db.models.signals import post_save, post_delete from django.db import models from wagtail.wagtailsearch.index import Indexed from wagtail.wagtailsearch.backends import get_search_backends def post_save_signal_handler(instance, **kwargs): for backend in get_search_backends(): backend.add(insta...
from django.db.models.signals import post_save, post_delete from django.db import models from wagtail.wagtailsearch.index import Indexed from wagtail.wagtailsearch.backends import get_search_backends def post_save_signal_handler(instance, **kwargs): if instance not in type(instance).get_indexed_objects(): ...
Make search signal handlers use get_indexed_objects
Make search signal handlers use get_indexed_objects
Python
bsd-3-clause
rv816/wagtail,serzans/wagtail,serzans/wagtail,FlipperPA/wagtail,iansprice/wagtail,nrsimha/wagtail,Toshakins/wagtail,kurtrwall/wagtail,jorge-marques/wagtail,stevenewey/wagtail,darith27/wagtail,kaedroho/wagtail,iho/wagtail,WQuanfeng/wagtail,nealtodd/wagtail,quru/wagtail,mikedingjan/wagtail,timorieber/wagtail,timorieber/w...
--- +++ @@ -6,11 +6,18 @@ def post_save_signal_handler(instance, **kwargs): + if instance not in type(instance).get_indexed_objects(): + return + + for backend in get_search_backends(): backend.add(instance) def post_delete_signal_handler(instance, **kwargs): + if instance not in ...
87707340ac82f852937dae546380b5d5327f5bc7
txlege84/core/views.py
txlege84/core/views.py
from django.views.generic import ListView from bills.mixins import AllSubjectsMixin from core.mixins import ConveneTimeMixin from legislators.mixins import AllLegislatorsMixin, ChambersMixin from explainers.models import Explainer from topics.models import Topic class LandingView(AllSubjectsMixin, AllLegislatorsMix...
from django.views.generic import ListView from core.mixins import ConveneTimeMixin from explainers.models import Explainer from topics.models import Topic class LandingView(ConveneTimeMixin, ListView): model = Topic template_name = 'landing.html' def get_context_data(self, **kwargs): context = ...
Remove unneeded mixins from LandingView
Remove unneeded mixins from LandingView
Python
mit
texastribune/txlege84,texastribune/txlege84,texastribune/txlege84,texastribune/txlege84
--- +++ @@ -1,15 +1,12 @@ from django.views.generic import ListView -from bills.mixins import AllSubjectsMixin from core.mixins import ConveneTimeMixin -from legislators.mixins import AllLegislatorsMixin, ChambersMixin from explainers.models import Explainer from topics.models import Topic -class LandingV...
47d507bdc4dc0ecd54e9956a40741f3b75664ab2
events/models.py
events/models.py
from django.db import models # Create your models here. class Calendar(models.Model): name = models.CharField(max_length=30, unique=True) remote_id = models.CharField(max_length=60) css_class = models.CharField(max_length=10) def __str__(self): return self.name
from django.db import models # Create your models here. class Calendar(models.Model): name = models.CharField(max_length=30, unique=True) remote_id = models.CharField(max_length=60) css_class = models.CharField(max_length=10) def __str__(self): return self.name class Meta: orderin...
Set default ordering of Calendars
Set default ordering of Calendars
Python
mit
Kromey/fbxnano,Kromey/akwriters,Kromey/akwriters,Kromey/fbxnano,Kromey/akwriters,Kromey/fbxnano,Kromey/akwriters,Kromey/fbxnano
--- +++ @@ -9,3 +9,6 @@ def __str__(self): return self.name + class Meta: + ordering = ['name',] +
311c6caae6275cebd820aab9607adefc6b125c92
utils/celery_worker.py
utils/celery_worker.py
import os import sys # Append .. to sys path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import multiscanner from celery import Celery app = Celery('celery_worker', broker='pyamqp://guest@localhost//') @app.task def multiscanner_celery(filelist, config=multiscanner.CONFIG): ''' ...
import os import sys # Append .. to sys path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import multiscanner from celery import Celery RABBIT_USER = 'guest' RABBIT_HOST = 'localhost' app = Celery('celery_worker', broker='pyamqp://%s@%s//' % (RABBIT_USER, RABBIT_HOST)) @app.task def ...
Move rabbit vars to globals
Move rabbit vars to globals
Python
mpl-2.0
mitre/multiscanner,jmlong1027/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner,awest1339/multiscanner,mitre/multiscanner,awest1339/multiscanner,mitre/multiscanner,MITRECND/multiscanner,jmlong1027/multiscanner,MITRECND/multiscanner
--- +++ @@ -6,11 +6,15 @@ from celery import Celery -app = Celery('celery_worker', broker='pyamqp://guest@localhost//') +RABBIT_USER = 'guest' +RABBIT_HOST = 'localhost' + +app = Celery('celery_worker', broker='pyamqp://%s@%s//' % (RABBIT_USER, RABBIT_HOST)) @app.task def multiscanner_celery(filelist, config...
4c69a59f99fd5f425c31e3fdcbf6e3f78d82d9e4
vex_via_wrapper.py
vex_via_wrapper.py
import requests MATCH_LIST_URL = "http://data.vexvia.dwabtech.net/mobile/events/csv" DIVISION_URL = "http://data.vexvia.dwabtech.net/mobile/{}/divisions/csv" MATCH_URL = "http://data.vexvia.dwabtech.net/mobile/{}/{}/matches/csv" def get_events(iq=False): data = requests.get(MATCH_LIST_URL).text.split("\r\n")[1:-1...
import requests MATCH_LIST_URL = "http://data.vexvia.dwabtech.net/mobile/events/csv" DIVISION_URL = "http://data.vexvia.dwabtech.net/mobile/{}/divisions/csv" MATCH_URL = "http://data.vexvia.dwabtech.net/mobile/{}/{}/matches/csv" def get_events(is_iq: bool=False) -> list: """Get a list of iq events or edr events. ...
Add comments to vex via wrapper
Add comments to vex via wrapper
Python
mit
DLProgram/Project_Snake_Sort,DLProgram/Project_Snake_Sort
--- +++ @@ -4,20 +4,48 @@ MATCH_URL = "http://data.vexvia.dwabtech.net/mobile/{}/{}/matches/csv" -def get_events(iq=False): +def get_events(is_iq: bool=False) -> list: + """Get a list of iq events or edr events. + + Args: + is_iq: True for vex iq tournaments, False for vex edr(default). + + Retur...
f9d17e97115d914c9ed231630d01a6d724378f15
zou/app/blueprints/source/csv/persons.py
zou/app/blueprints/source/csv/persons.py
from zou.app.blueprints.source.csv.base import BaseCsvImportResource from zou.app.models.person import Person from zou.app.utils import auth, permissions from sqlalchemy.exc import IntegrityError class PersonsCsvImportResource(BaseCsvImportResource): def check_permissions(self): return permissions.chec...
from zou.app.blueprints.source.csv.base import BaseCsvImportResource from zou.app.models.person import Person from zou.app.utils import auth, permissions from sqlalchemy.exc import IntegrityError class PersonsCsvImportResource(BaseCsvImportResource): def check_permissions(self): return permissions.chec...
Allow to import roles when importing people
Allow to import roles when importing people
Python
agpl-3.0
cgwire/zou
--- +++ @@ -16,6 +16,19 @@ last_name = row["Last Name"] email = row["Email"] phone = row["Phone"] + role = row.get("Role", None) + + if role == "Studio Manager": + role = "admin" + elif role == "Supervisor": + role = "manager" + elif role ==...
f47c5e3d5ef32f1d02b78c1de9737c26754404b2
src/main/webapp/AMI-Scripts/ubuntu-init.py
src/main/webapp/AMI-Scripts/ubuntu-init.py
#!/usr/bin/python import os import httplib import string # To install run: # sudo wget http://$JENKINS_URL/plugin/ec2/AMI-Scripts/ubuntu-init.py -O /usr/bin/userdata # sudo chmod +x /etc/init.d/userdata # add the following line to /etc/rc.local "python /usr/bin/userdata" # If java is installed it will be zero # If ja...
#!/usr/bin/python import os import httplib import string # To install run: # sudo wget http://$JENKINS_URL/plugin/ec2/AMI-Scripts/ubuntu-init.py -O /usr/bin/userdata # sudo chmod +x /etc/init.d/userdata # add the following line to /etc/rc.local "python /usr/bin/userdata" # If java is installed it will be zero # If ja...
Fix trailing spaces/tabs in Python code
Fix trailing spaces/tabs in Python code
Python
mit
mkozell/ec2-plugin,jenkinsci/ec2-plugin,jenkinsci/ec2-plugin,jenkinsci/ec2-plugin,jenkinsci/ec2-plugin,mkozell/ec2-plugin,mkozell/ec2-plugin,mkozell/ec2-plugin
--- +++ @@ -30,7 +30,6 @@ jenkinsUrl = arg.split("=")[1] if arg.split("=")[0] == "SLAVE_NAME": slaveName = arg.split("=")[1] - + os.system("wget " + jenkinsUrl + "jnlpJars/slave.jar -O slave.jar") os.system("java -jar slave.jar -jnlpUrl " + jenkinsUrl + "computer/" + slaveName + "/slave-age...
6a71271ed00ba164cf2755f728f0dbf2ed310f6b
zsi/setup.py
zsi/setup.py
#! /usr/bin/env python # $Header$ import sys from distutils.core import setup _url = "http://www.zolera.com/resources/opensrc/zsi" import ConfigParser cf = ConfigParser.ConfigParser() cf.read('setup.cfg') _version = "%d.%d" % \ ( cf.getint('version', 'major'), cf.getint('version', 'minor') ) try: open('ZSI/v...
#! /usr/bin/env python # $Header$ import sys from distutils.core import setup _url = "http://pywebsvcs.sf.net/" import ConfigParser cf = ConfigParser.ConfigParser() cf.read('setup.cfg') _version = "%d.%d" % \ ( cf.getint('version', 'major'), cf.getint('version', 'minor') ) try: open('ZSI/version.py', 'r').cl...
Change URL from Zolera (sob, snif, sigh :) to SF
Change URL from Zolera (sob, snif, sigh :) to SF git-svn-id: c4afb4e777bcbfe9afa898413b708b5abcd43877@123 7150bf37-e60d-0410-b93f-83e91ef0e581
Python
mit
acigna/pywez,acigna/pywez,acigna/pywez
--- +++ @@ -3,7 +3,7 @@ import sys from distutils.core import setup -_url = "http://www.zolera.com/resources/opensrc/zsi" +_url = "http://pywebsvcs.sf.net/" import ConfigParser cf = ConfigParser.ConfigParser()
960436b17211a225a729805a528653f2aff675d7
src/sentry/utils/social_auth.py
src/sentry/utils/social_auth.py
""" sentry.utils.social_auth ~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from django.conf import settings from social_auth.backends.pipeline.user import create_user from so...
""" sentry.utils.social_auth ~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from django.conf import settings from social_auth.backends.pipeline.user import create_user from so...
Call to create_user fails because django-social-auth module requires 5 parameters now for create_user now.
Call to create_user fails because django-social-auth module requires 5 parameters now for create_user now. The exception is quietly suppressed in social_auth/backends/__init__.py:143 in the pipeline stage for this module since TypeErrors in general are try/except in the authenticate() stage. It can be repro'd by putt...
Python
bsd-3-clause
BuildingLink/sentry,gg7/sentry,kevinlondon/sentry,zenefits/sentry,ewdurbin/sentry,daevaorn/sentry,looker/sentry,zenefits/sentry,BuildingLink/sentry,1tush/sentry,wujuguang/sentry,ewdurbin/sentry,rdio/sentry,pauloschilling/sentry,songyi199111/sentry,argonemyth/sentry,wong2/sentry,jokey2k/sentry,zenefits/sentry,beeftornad...
--- +++ @@ -25,4 +25,11 @@ if not settings.SOCIAL_AUTH_CREATE_USERS and not kwargs.get('user'): raise AuthNotAllowed('You must create an account before associating an identity.') - return create_user(*args, **kwargs) + backend = kwargs.pop('backend') + details = kwargs.pop('details') + res...
b6941b35f5bb20dbc2c7e05bbf6100bf0879be3f
foyer/tests/test_plugin.py
foyer/tests/test_plugin.py
import pytest def test_basic_import(): import foyer assert 'forcefields' in dir(foyer) import foyer.forcefields.forcefields
import pytest import foyer def test_basic_import(): assert 'forcefields' in dir(foyer) @pytest.mark.parametrize('ff_name', ['OPLSAA', 'TRAPPE_UA']) def test_forcefields_exist(ff_name): ff_name in dir(foyer.forcefields) def test_load_forcefield(): OPLSAA = foyer.forcefields.get_forcefield(name='oplsaa'...
Update test to check more internals
Update test to check more internals
Python
mit
mosdef-hub/foyer,iModels/foyer,iModels/foyer,mosdef-hub/foyer
--- +++ @@ -1,7 +1,18 @@ import pytest +import foyer def test_basic_import(): - import foyer assert 'forcefields' in dir(foyer) - import foyer.forcefields.forcefields + + +@pytest.mark.parametrize('ff_name', ['OPLSAA', 'TRAPPE_UA']) +def test_forcefields_exist(ff_name): + ff_name in dir(foyer.forc...
ec613fe1df31dd65d8a52351a29482b54ce007b3
skvideo/__init__.py
skvideo/__init__.py
from skvideo.stuff import * from skvideo.version import __version__ # If you want to use Numpy's testing framerwork, use the following. # Tests go under directory tests/, benchmarks under directory benchmarks/ from numpy.testing import Tester test = Tester().test bench = Tester().bench
from skvideo.version import __version__ # If you want to use Numpy's testing framerwork, use the following. # Tests go under directory tests/, benchmarks under directory benchmarks/ from numpy.testing import Tester test = Tester().test bench = Tester().bench
Remove some unused parts of skeleton
Remove some unused parts of skeleton
Python
bsd-3-clause
aizvorski/scikit-video
--- +++ @@ -1,4 +1,3 @@ -from skvideo.stuff import * from skvideo.version import __version__ # If you want to use Numpy's testing framerwork, use the following.
682010eafe28eed1eeb32ba9d34e213b4f2d7d4b
sourcer/__init__.py
sourcer/__init__.py
from .compiler import ParseResult from .expressions import ( Alt, And, Any, Backtrack, Bind, End, Expect, Fail, ForwardRef, Left, List, Literal, Not, Opt, Or, Require, Return, Right, Some, Start, Struct, Term, Transform, Wh...
from .compiler import ParseResult from .expressions import ( Alt, And, Any, AnyOf, Backtrack, Bind, End, Expect, Fail, ForwardRef, Left, List, Literal, Not, Opt, Or, Require, Return, Right, Some, Start, Struct, Term, Transf...
Add "AnyOf" to public API.
Add "AnyOf" to public API.
Python
mit
jvs/sourcer
--- +++ @@ -4,6 +4,7 @@ Alt, And, Any, + AnyOf, Backtrack, Bind, End,
9e07a21df955b599d27eb8b98b53395fa7170257
spoj/00005/palin.py
spoj/00005/palin.py
#!/usr/bin/env python3 def next_palindrome(k): palin = list(k) n = len(k) mid = n // 2 # case 1: forward right just_copy = False for i in range(mid, n): mirrored = n - 1 - i if k[i] < k[mirrored]: just_copy = True if just_copy: palin[i] = palin[mirrored] # case 2: backward left if not just_copy:...
#!/usr/bin/env python3 def next_palindrome(k): palin = list(k) n = len(k) mid = n // 2 # case 1: forward right just_copy = False for i in range(mid, n): mirrored = n - 1 - i if k[i] < k[mirrored]: just_copy = True if just_copy: palin[i] = palin[mirrored] # case 2: backward left if not just_copy:...
Fix off-by-1 bug for `mid`
Fix off-by-1 bug for `mid` - in SPOJ palin Signed-off-by: Karel Ha <70f8965fdfb04f1fc0e708a55d9e822c449f57d3@gmail.com>
Python
mit
mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming
--- +++ @@ -20,9 +20,9 @@ i -= 1 if i >= 0: palin[i] = str(int(k[i]) + 1) - for j in range(i + 1, mid + 1): + for j in range(i + 1, mid): palin[j] = '0' - for j in range(mid + 1, n): + for j in range(mid, n): mirrored = n - 1 - j palin[j] = palin[mirrored] else:
74d668cb8291822a167d1ddd0fecf7e580375377
serv/rcompserv/serv.py
serv/rcompserv/serv.py
from aiohttp import web from . import __version__ class Server: def __init__(self, host='127.0.0.1', port=8080): self._host = host self._port = port self.app = web.Application() self.app.router.add_get('/', self.index) self.known_commands = ['version'] self.app.rou...
import uuid from datetime import datetime from aiohttp import web import redis from . import __version__ class Server: def __init__(self, host='127.0.0.1', port=8080): self._host = host self._port = port self.app = web.Application() self.app.on_startup.append(self.start_redis) ...
Add route for `trivial` (vacuous) command
Add route for `trivial` (vacuous) command
Python
bsd-3-clause
slivingston/rcomp,slivingston/rcomp,slivingston/rcomp
--- +++ @@ -1,4 +1,8 @@ +import uuid +from datetime import datetime + from aiohttp import web +import redis from . import __version__ @@ -8,9 +12,14 @@ self._host = host self._port = port self.app = web.Application() + self.app.on_startup.append(self.start_redis) self....
c8100c89298091179c9ad7f84452328e28efaa03
crawler/CrawlerExample.py
crawler/CrawlerExample.py
__author__ = 'pascal' from crawler.Crawler import Crawler from utils.path import RessourceUtil # _____ _ # | ____|_ ____ _ _ __ ___ _ __ | | ___ # | _| \ \/ / _` | '_ ` _ \| '_ \| |/ _ \ # | |___ > < (_| | | | | | | |_) | | __/ # |_____/_/\_\__,_|_| |_| |_| .__/|_|\___| # ...
__author__ = 'pascal' from crawler.Crawler import Crawler from indexer.indexer import Indexer from utils.path import RessourceUtil # _____ _ # | ____|_ ____ _ _ __ ___ _ __ | | ___ # | _| \ \/ / _` | '_ ` _ \| '_ \| |/ _ \ # | |___ > < (_| | | | | | | |_) | | __/ # |_____/_/\_\__,_|_| ...
Add an example for building and printing the index.
Add an example for building and printing the index. You can find the example inside the CrawlerExample.py.
Python
cc0-1.0
pascalweiss/SearchEngine,yveskaufmann/SearchEngine,yveskaufmann/SearchEngine
--- +++ @@ -1,6 +1,7 @@ __author__ = 'pascal' from crawler.Crawler import Crawler +from indexer.indexer import Indexer from utils.path import RessourceUtil # _____ _ @@ -36,3 +37,17 @@ # Print the link structure link_structure_txt = crawler.get_link_structure_text() p...
708b519e066b8d443ed4768293db4517021d68fc
thinglang/__init__.py
thinglang/__init__.py
import os from thinglang import utils from thinglang.execution.execution import ExecutionEngine from thinglang.lexer.lexer import lexer from thinglang.parser.analyzer import Analyzer from thinglang.parser.parser import parse from thinglang.parser.simplifier import Simplifier BASE_DIR = os.path.join(os.path.dirname(os...
import os from thinglang import utils from thinglang.execution.execution import ExecutionEngine from thinglang.lexer.lexer import lexer from thinglang.parser.analyzer import Analyzer from thinglang.parser.parser import parse from thinglang.parser.simplifier import Simplifier BASE_DIR = os.path.join(os.path.dirname(os...
Split compiler and execution steps
Split compiler and execution steps
Python
mit
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
--- +++ @@ -15,7 +15,7 @@ return '\n' + '\n'.join(open(f).read() for f in files) -def run(source): +def compiler(source): if not source: raise ValueError('Source cannot be empty') @@ -33,6 +33,12 @@ Analyzer(ast).run() + return ast + + +def run(source): + ast = compiler(source)...
f7a9f65e68b2fe78a0180acb1b2bef552e9633f3
media/collector.py
media/collector.py
import feedparser import pickle import requests hub = "http://feeds.feedburner.com/ampparit-politiikka" ## collect from ampparit all politics related sites feed = feedparser.parse( hub ) stored = [] try: stored = pickle.load( open( '.history' , 'r' ) ) except: pass stored = [] out = open( 'urls.txt' , 'a'...
import feedparser import pickle import requests import sys hub = "http://feeds.feedburner.com/ampparit-politiikka" ## collect from ampparit all politics related sites feed = feedparser.parse( hub ) stored = [] path = sys.argv[0] try: stored = pickle.load( open( path + '/.history' , 'r' ) ) except: pass ...
Make path variable working for server side
Make path variable working for server side
Python
mit
HIIT/digivaalit-2015,HIIT/digivaalit-2015,HIIT/digivaalit-2015
--- +++ @@ -1,6 +1,7 @@ import feedparser import pickle import requests +import sys hub = "http://feeds.feedburner.com/ampparit-politiikka" ## collect from ampparit all politics related sites @@ -8,14 +9,14 @@ stored = [] +path = sys.argv[0] + try: - stored = pickle.load( open( '.history' , 'r' ) ) +...
19a8a0e2f85b7ab01cbd3e2dd283e8e1e9b97373
example/example/tasksapp/run_tasks.py
example/example/tasksapp/run_tasks.py
import time from dj_experiment.tasks.tasks import longtime_add if __name__ == '__main__': result = longtime_add.delay(1, 2) # at this time, our task is not finished, so it will return False print 'Task finished? ', result.ready() print 'Task result: ', result.result # sleep 10 seconds to ensure th...
import time from dj_experiment.tasks.tasks import longtime_add, netcdf_save if __name__ == '__main__': result = longtime_add.delay(1, 2) # at this time, our task is not finished, so it will return False print 'Task finished? ', result.ready() print 'Task result: ', result.result # sleep 10 seconds...
Add the use of task to the example app
Add the use of task to the example app
Python
mit
francbartoli/dj-experiment,francbartoli/dj-experiment
--- +++ @@ -1,6 +1,6 @@ import time -from dj_experiment.tasks.tasks import longtime_add +from dj_experiment.tasks.tasks import longtime_add, netcdf_save if __name__ == '__main__': result = longtime_add.delay(1, 2) @@ -12,3 +12,10 @@ # now the task should be finished and ready method will return True ...
332f275b3ac4b93c523b474c94268bac834c180c
memorize/models.py
memorize/models.py
from datetime import datetime, timedelta import datetime from django.utils.timezone import utc from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from .algorithm import interval class Pra...
from datetime import datetime, timedelta from django.utils.timezone import utc from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from .algorithm import interval class Practice(models.Mo...
Fix datetime usage in memorize model
Fix datetime usage in memorize model
Python
mit
DummyDivision/Tsune,DummyDivision/Tsune,DummyDivision/Tsune
--- +++ @@ -1,5 +1,5 @@ from datetime import datetime, timedelta -import datetime + from django.utils.timezone import utc from django.db import models @@ -27,8 +27,8 @@ def set_next_practice(self, rating): self.times_practiced += 1 minutes, ef = interval(self.times_practiced, rating, self....
8c7daf1c0e140cb68c425b34eb60d9b001fd7063
fiduswriter/base/management/commands/jest.py
fiduswriter/base/management/commands/jest.py
from pathlib import Path import shutil from subprocess import call from django.core.management.base import BaseCommand from django.core.management import call_command from django.conf import settings BABEL_CONF = ''' module.exports = { presets: [ [ '@babel/preset-env', { ...
from pathlib import Path import shutil from subprocess import call from django.core.management.base import BaseCommand from django.core.management import call_command from django.conf import settings BABEL_CONF = ''' module.exports = { presets: [ [ '@babel/preset-env', { ...
Make test suite pass when there are no tests
Make test suite pass when there are no tests
Python
agpl-3.0
fiduswriter/fiduswriter,fiduswriter/fiduswriter,fiduswriter/fiduswriter,fiduswriter/fiduswriter
--- +++ @@ -39,6 +39,7 @@ command_array = [ p / 'node_modules' / '.bin' / 'jest', '--no-cache', + '--passWithNoTests', ] return_value = call(command_array) if return_value > 0:
d6500b3d9af37fb2cd0fa14c82f78b165f9d221b
test_framework/test_settings.py
test_framework/test_settings.py
from .settings import * # NOQA # Django 1.8 still has INSTALLED_APPS as a tuple INSTALLED_APPS = list(INSTALLED_APPS) INSTALLED_APPS.append('djoyapp')
from .settings import * # NOQA INSTALLED_APPS.append('djoyapp')
Remove handling of apps tuple, it is always list now
Remove handling of apps tuple, it is always list now Since Django 1.11, app settings are lists by default
Python
mit
jamescooke/factory_djoy
--- +++ @@ -1,6 +1,4 @@ from .settings import * # NOQA -# Django 1.8 still has INSTALLED_APPS as a tuple -INSTALLED_APPS = list(INSTALLED_APPS) INSTALLED_APPS.append('djoyapp')
46af8faf699d893a95ecec402030ef74e07e77ed
recharges/tasks.py
recharges/tasks.py
import requests from django.conf import settings from celery.task import Task from celery.utils.log import get_task_logger from .models import Account logger = get_task_logger(__name__) class Hotsocket_Login(Task): """ Task to get the username and password varified then produce a token """ name = ...
import requests from django.conf import settings from celery.task import Task from celery.utils.log import get_task_logger from .models import Account logger = get_task_logger(__name__) class Hotsocket_Login(Task): """ Task to get the username and password varified then produce a token """ name = ...
Update login task to get username from settings
Update login task to get username from settings
Python
bsd-3-clause
westerncapelabs/gopherairtime,westerncapelabs/gopherairtime
--- +++ @@ -22,11 +22,15 @@ """ l = self.get_logger(**kwargs) l.info("Logging into hotsocket") - auth = {'username': 'trial_acc_1212', 'password': 'tr14l_l1k3m00n', + + auth = {'username': settings.HOTSOCKET_API_USERNAME, + 'password': settings.HOTSOCKET_API_PAS...
2932698f81a17204b824763e648cd56dbab5f5b2
hawkpost/settings/development.py
hawkpost/settings/development.py
from .common import * # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': "hawkpost_dev", } } # Development App...
from .common import * # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': "hawkpost_dev", } } # If the DB_HOST w...
Allow overriding database and mail_debug settings
Allow overriding database and mail_debug settings Using environment variables to override default database connection and mail_debug settings in development mode. This allows setting the values needed by the Docker environment.
Python
mit
whitesmith/hawkpost,whitesmith/hawkpost,whitesmith/hawkpost
--- +++ @@ -13,6 +13,15 @@ } } +# If the DB_HOST was specified it is overriding the default connection +if 'DB_HOST' in os.environ: + DATABASES['default']['HOST'] = os.environ.get("DB_HOST") + DATABASES['default']['PORT'] = os.environ.get("DB_PORT", 5432) + DATABASES['default']['USER'] = os.environ.g...
aeefef1f80ba92c7900c95c436b61b019d8ffb6a
src/waldur_mastermind/marketplace_openstack/migrations/0011_limit_components.py
src/waldur_mastermind/marketplace_openstack/migrations/0011_limit_components.py
from django.db import migrations TENANT_TYPE = 'Packages.Template' LIMIT = 'limit' def process_components(apps, schema_editor): OfferingComponent = apps.get_model('marketplace', 'OfferingComponent') OfferingComponent.objects.filter(offering__type=TENANT_TYPE).update( billing_type=LIMIT ) class ...
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('marketplace_openstack', '0010_split_invoice_items'), ]
Remove invalid migration script: it has been superceded by 0052_limit_components
Remove invalid migration script: it has been superceded by 0052_limit_components
Python
mit
opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur
--- +++ @@ -1,19 +1,7 @@ from django.db import migrations - -TENANT_TYPE = 'Packages.Template' -LIMIT = 'limit' - - -def process_components(apps, schema_editor): - OfferingComponent = apps.get_model('marketplace', 'OfferingComponent') - OfferingComponent.objects.filter(offering__type=TENANT_TYPE).update( - ...
353ad2e4d03d5ad5a8c5a1e949e8cd3251c7d85b
holviapi/tests/test_api_idempotent.py
holviapi/tests/test_api_idempotent.py
# -*- coding: utf-8 -*- import os import pytest import holviapi @pytest.fixture def connection(): pool = os.environ.get('HOLVI_POOL', None) key = os.environ.get('HOLVI_KEY', None) if not pool or not key: raise RuntimeError("HOLVI_POOL and HOLVI_KEY must be in ENV for these tests") cnc = holviap...
# -*- coding: utf-8 -*- import os import pytest import holviapi @pytest.fixture def connection(): pool = os.environ.get('HOLVI_POOL', None) key = os.environ.get('HOLVI_KEY', None) if not pool or not key: raise RuntimeError("HOLVI_POOL and HOLVI_KEY must be in ENV for these tests") cnc = holviap...
Test getting invoice by code
Test getting invoice by code
Python
mit
rambo/python-holviapi,rambo/python-holviapi
--- +++ @@ -22,3 +22,10 @@ l = invoiceapi.list_invoices() i = next(l) assert type(i) == holviapi.Invoice + +def test_get_invoice(invoiceapi): + l = invoiceapi.list_invoices() + i = next(l) + assert type(i) == holviapi.Invoice + i2 = invoiceapi.get_invoice(i.code) + assert i.code == i2.co...
745c03d3cc5ae31fb852ba7bfc9d0ad6a9ac4716
unittests.py
unittests.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import const import uniformdh import obfsproxy.network.buffer as obfs_buf class UniformDHTest( unittest.TestCase ): def setUp( self ): weAreServer = True self.udh = uniformdh.new("A" * const.SHARED_SECRET_LENGTH, weAreServer) de...
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import const import uniformdh import obfsproxy.network.buffer as obfs_buf class UniformDHTest( unittest.TestCase ): def setUp( self ): weAreServer = True self.udh = uniformdh.new("A" * const.SHARED_SECRET_LENGTH, weAreServer) de...
Add UniformDH unit test to test for invalid HMACs.
Add UniformDH unit test to test for invalid HMACs.
Python
bsd-3-clause
isislovecruft/scramblesuit,isislovecruft/scramblesuit
--- +++ @@ -31,5 +31,18 @@ publicKey = self.udh.getRemotePublicKey() self.failUnless(len(publicKey) == const.PUBLIC_KEY_LENGTH) + def test3_invalidHMAC( self ): + # Make the HMAC invalid. + handshake = self.udh.createHandshake() + if handshake[-1] != 'a': + hands...
da47bca1bbdffff536d240cafe780533ee79809e
mesh.py
mesh.py
#!/usr/bin/env python3 import os import shutil import sys import readline import traceback readline.parse_and_bind('tab: complete') readline.parse_and_bind('set editing-mode vi') builtin_cmds = {'cd', 'pwd', 'exit',} def prompt(): return '%s$ ' % os.getcwd() def read_command(): line = input(prompt()) re...
#!/usr/bin/env python3 import os import shutil import sys import readline import traceback readline.parse_and_bind('tab: complete') readline.parse_and_bind('set editing-mode vi') builtin_cmds = {'cd', 'pwd', 'exit',} def prompt(): return '%s$ ' % os.getcwd() def read_command(): line = input(prompt()) re...
Handle ctrl-c and ctrl-d properly
Handle ctrl-c and ctrl-d properly
Python
mit
mmichie/mesh
--- +++ @@ -45,7 +45,13 @@ else: #pid = subprocess.Popen(cmd_text, stdin=None, stdout=None, shell=True) os.system(cmd_text) + except KeyboardInterrupt: + print('') + pass except SystemExit: + break + except EOFError...
6c932dc133ca2e6608297a93489e5c57ad73d5c2
models/fallahi_eval/evidence_sources.py
models/fallahi_eval/evidence_sources.py
from util import pklload from collections import defaultdict import indra.tools.assemble_corpus as ac if __name__ == '__main__': # Load cached Statements just before going into the model stmts = pklload('pysb_stmts') # Start a dictionary for source counts sources_count = defaultdict(int) # Count ...
from util import pklload from collections import defaultdict import indra.tools.assemble_corpus as ac if __name__ == '__main__': # Load cached Statements just before going into the model stmts = pklload('pysb_stmts') # Start a dictionary for source counts sources_count = defaultdict(int) # Count ...
Fix some things in evidence sources
Fix some things in evidence sources
Python
bsd-2-clause
johnbachman/belpy,sorgerlab/indra,johnbachman/indra,johnbachman/belpy,sorgerlab/belpy,pvtodorov/indra,bgyori/indra,pvtodorov/indra,pvtodorov/indra,sorgerlab/indra,sorgerlab/belpy,johnbachman/belpy,sorgerlab/belpy,pvtodorov/indra,johnbachman/indra,sorgerlab/indra,bgyori/indra,johnbachman/indra,bgyori/indra
--- +++ @@ -34,6 +34,7 @@ if r and not d: reading_only += v - for k, v in sorted(sources_count.items(), key=lambda x: (len(x[1]), x[1])): + for k, v in sorted(sources_count.items(), key=lambda x: (len(x[0]), ','.join(sorted(x[0])))): sources_str = ','.join(k) - line_str =...
ee485b086e66f6c423e6c9b728d43a6ace071d55
Lib/test/test_frozen.py
Lib/test/test_frozen.py
# Test the frozen module defined in frozen.c. from __future__ import with_statement from test.test_support import captured_stdout, run_unittest import unittest import sys, os class FrozenTests(unittest.TestCase): def test_frozen(self): with captured_stdout() as stdout: try: im...
# Test the frozen module defined in frozen.c. from __future__ import with_statement from test.test_support import captured_stdout, run_unittest import unittest import sys, os class FrozenTests(unittest.TestCase): def test_frozen(self): with captured_stdout() as stdout: try: im...
Make it possible to run this test stand-alone.
Make it possible to run this test stand-alone.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
--- +++ @@ -38,3 +38,6 @@ def test_main(): run_unittest(FrozenTests) + +if __name__ == "__main__": + test_main()
61f710b64f32da26bd36c7c95a3f46e4d21c991a
modules/output_statistics.py
modules/output_statistics.py
from pysqlite2 import dbapi2 as sqlite import sys, os.path class Statistics: def __init__(self): self.total = 0 self.passed = 0 self.failed = 0 def register(self, manager, parser): manager.register(instance=self, event='input', keyword='stats', callback=self.input, order=65535)...
import sys, os.path has_sqlite = True try: from pysqlite2 import dbapi2 as sqlite except: has_sqlite = False class Statistics: def __init__(self): self.total = 0 self.passed = 0 self.failed = 0 def register(self, manager, parser): manager.register(instance=self, event=...
Check that python-sqlite2 is installed
Check that python-sqlite2 is installed git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@147 3942dd89-8c5d-46d7-aeed-044bccf3e60c
Python
mit
asm0dey/Flexget,gazpachoking/Flexget,vfrc2/Flexget,X-dark/Flexget,ianstalk/Flexget,patsissons/Flexget,tvcsantos/Flexget,ibrahimkarahan/Flexget,Flexget/Flexget,ibrahimkarahan/Flexget,lildadou/Flexget,LynxyssCZ/Flexget,antivirtel/Flexget,drwyrm/Flexget,jawilson/Flexget,offbyone/Flexget,ZefQ/Flexget,thalamus/Flexget,malka...
--- +++ @@ -1,5 +1,10 @@ -from pysqlite2 import dbapi2 as sqlite import sys, os.path + +has_sqlite = True +try: + from pysqlite2 import dbapi2 as sqlite +except: + has_sqlite = False class Statistics: def __init__(self): @@ -25,6 +30,8 @@ con.commit() def input(self, feed): + ...
62c5e911689555c62931692e0d6ff87ed7340559
src/models/split.py
src/models/split.py
# Third-party modules import numpy as np import pandas as pd from sklearn.model_selection import KFold # Hand-made modules from .base import BloscpackMixin KWARGS_READ_CSV = { "sep": "\t", "header": 0, "parse_dates": [0], "index_col": 0 } class ValidationSplitHandler(BloscpackMixin): def __init__...
# Third-party modules import numpy as np import pandas as pd from sklearn.model_selection import KFold # Hand-made modules from .base import PathHandlerBase, BloscpackMixin KWARGS_READ_CSV = { "sep": "\t", "header": 0, "parse_dates": [0], "index_col": 0 } KWARGS_TO_CSV = { "sep": "\t" } OBJECTIVE_L...
Adjust to current serialization conditions
Adjust to current serialization conditions + blp -> tsv
Python
mit
gciteam6/xgboost,gciteam6/xgboost
--- +++ @@ -3,7 +3,7 @@ import pandas as pd from sklearn.model_selection import KFold # Hand-made modules -from .base import BloscpackMixin +from .base import PathHandlerBase, BloscpackMixin KWARGS_READ_CSV = { "sep": "\t", @@ -11,6 +11,12 @@ "parse_dates": [0], "index_col": 0 } +KWARGS_TO_CSV =...
47b751c5578d2419eaf1a7bb90c53b46eea80c9f
objectcube/settings.py
objectcube/settings.py
import os # Database configurations. DB_HOST = os.environ.get('OBJECTCUBE_DB_HOST', 'localhost') DB_USER = os.environ.get('OBJECTCUBE_DB_USER', os.environ.get('LOGNAME')) DB_PORT = int(os.environ.get('OBJECTCUBE_DB_PORT', 5432)) DB_DBNAME = os.environ.get('OBJECTCUBE_DB_NAME', os.environ.get('LOGNAME')) DB_PASSWORD = ...
import os # Database configurations. DB_HOST = os.environ.get('OBJECTCUBE_DB_HOST', 'localhost') DB_USER = os.environ.get('OBJECTCUBE_DB_USER', os.environ.get('LOGNAME')) DB_PORT = int(os.environ.get('OBJECTCUBE_DB_PORT', 5432)) DB_DBNAME = os.environ.get('OBJECTCUBE_DB_NAME', os.environ.get('LOGNAME')) DB_PASSWORD = ...
Correct the Object service after rename of object_service.py file to object.py
Correct the Object service after rename of object_service.py file to object.py
Python
bsd-2-clause
rudatalab/python-objectcube,rudatalab/python-objectcube,rudatalab/python-objectcube
--- +++ @@ -16,7 +16,7 @@ 'DimensionService': 'objectcube.services.impl.postgresql.dimension.' 'DimensionService', - 'ObjectService': 'objectcube.services.impl.postgresql.object_service.' + 'ObjectService': 'objectcube.services.impl.postgresql.object.' 'ObjectServ...
f081906482bf080363dd494a6ab0ca6ed63b49f5
loremipsum/tests/plugs_testpackage/plugin.py
loremipsum/tests/plugs_testpackage/plugin.py
"""Test plugin.""" def load(*args, **kwargs): pass def dump(*args, **kwargs): pass def plugin(): import sys return (__name__.split('.')[-1], sys.modules.get(__name__))
"""Test plugin. def load(*args, **kwargs): pass def dump(*args, **kwargs): pass def plugin(): return (__name__.split('.')[-1], sys.modules.get(__name__)) """
Put useless module function into docstring
Put useless module function into docstring
Python
bsd-3-clause
monkeython/loremipsum
--- +++ @@ -1,14 +1,13 @@ -"""Test plugin.""" +"""Test plugin. -def load(*args, **kwargs): - pass +def load(*args, **kwargs): pass -def dump(*args, **kwargs): - pass +def dump(*args, **kwargs): pass def plugin(): - import sys return (__name__.split('.')[-1], sys.modules.get(__name__)) + +""...
28252bbc3c5f784e5f6267788a7f4196473d7292
tests/conftest.py
tests/conftest.py
# -*- coding: utf-8 -*- import pytest from cheetah_lint import five @pytest.yield_fixture(autouse=True) def no_warnings(recwarn): yield ret = len(tuple( warning for warning in recwarn # cheetah raises this warning when compiling a trivial file if not ( isinstance(warning.m...
# -*- coding: utf-8 -*- import pytest from cheetah_lint import five @pytest.fixture(autouse=True) def no_warnings(recwarn): yield ret = len(tuple( warning for warning in recwarn # cheetah raises this warning when compiling a trivial file if not ( isinstance(warning.message...
Replace deprecated yield_fixture with fixture
Replace deprecated yield_fixture with fixture Committed via https://github.com/asottile/all-repos
Python
mit
asottile/cheetah_lint
--- +++ @@ -4,7 +4,7 @@ from cheetah_lint import five -@pytest.yield_fixture(autouse=True) +@pytest.fixture(autouse=True) def no_warnings(recwarn): yield ret = len(tuple(
2551eb35f2d5c5b95952b40c2583468a8deb5565
pylib/djangoproj/binalerts/tests.py
pylib/djangoproj/binalerts/tests.py
""" Integration-style tests for binalerts. These tests think of things from the web frontend point of view. They are designed to make sure the application behaves as required to the user. """ # Various tips on testing forms: # http://stackoverflow.com/questions/2257958/django-unit-testing-for-form-edit from django.te...
""" Integration-style tests for binalerts. These tests think of things from the web frontend point of view. They are designed to make sure the application behaves as required to the user. """ # Various tips on testing forms: # http://stackoverflow.com/questions/2257958/django-unit-testing-for-form-edit from django.te...
Test for error if not a postcode.
Test for error if not a postcode.
Python
agpl-3.0
mysociety/binalerts,mysociety/binalerts,mysociety/binalerts
--- +++ @@ -14,14 +14,21 @@ def setUp(self): self.c = Client() - def test_frontpage_asks_for_postcode(self): + def test_asks_for_postcode(self): response = self.c.get('/') self.assertEqual(response.status_code, 200) + + self.assertEqual(response.template.name, 'binaler...
f87008f6a8c3d4039ab69b558bae17f6ea006fca
skcode/__init__.py
skcode/__init__.py
""" SkCode (Python implementation of BBcode syntax) parser library. """ # Package information __author__ = "Fabien Batteix (@skywodd)" __copyright__ = "Copyright 2015, TamiaLab" __credits__ = ["Fabien Batteix", "TamiaLab"] __license__ = "GPLv3" __version__ = "1.0.6" __maintainer__ = "Fabien Batteix" __email__ = "fabie...
""" SkCode (Python implementation of BBcode syntax) parser library. """ # Package information __author__ = "Fabien Batteix (@skywodd)" __copyright__ = "Copyright 2015, TamiaLab" __credits__ = ["Fabien Batteix", "TamiaLab"] __license__ = "GPLv3" __version__ = "1.0.7" __maintainer__ = "Fabien Batteix" __email__ = "fabie...
Upgrade version from 1.0.6 to 1.0.7
Upgrade version from 1.0.6 to 1.0.7
Python
agpl-3.0
TamiaLab/PySkCode
--- +++ @@ -7,7 +7,7 @@ __copyright__ = "Copyright 2015, TamiaLab" __credits__ = ["Fabien Batteix", "TamiaLab"] __license__ = "GPLv3" -__version__ = "1.0.6" +__version__ = "1.0.7" __maintainer__ = "Fabien Batteix" __email__ = "fabien.batteix@tamialab.fr" __status__ = "Development" # "Production"
b740490e49b775809cb99b4cf30e3b7cf259d8f6
superdesk/io/__init__.py
superdesk/io/__init__.py
"""Superdesk IO""" from abc import ABCMeta, abstractmethod import superdesk import logging from superdesk.celery_app import celery providers = {} allowed_providers = [] logger = logging.getLogger(__name__) from .commands.update_ingest import UpdateIngest from .commands.add_provider import AddProvider # NOQA def ...
"""Superdesk IO""" from abc import ABCMeta, abstractmethod import superdesk import logging from superdesk.celery_app import celery providers = {} allowed_providers = [] logger = logging.getLogger(__name__) from .commands.remove_expired_content import RemoveExpiredContent from .commands.update_ingest import UpdateIn...
Revert "fix(ingest) - disable expired content removal"
Revert "fix(ingest) - disable expired content removal" This reverts commit 281e051344c9fe8e835941117e2d2068ecdabd87.
Python
agpl-3.0
mdhaman/superdesk,akintolga/superdesk-aap,ioanpocol/superdesk-ntb,marwoodandrew/superdesk,marwoodandrew/superdesk-aap,marwoodandrew/superdesk-aap,plamut/superdesk,darconny/superdesk,darconny/superdesk,superdesk/superdesk,amagdas/superdesk,hlmnrmr/superdesk,mdhaman/superdesk-aap,sivakuna-aap/superdesk,liveblog/superdesk...
--- +++ @@ -10,6 +10,7 @@ allowed_providers = [] logger = logging.getLogger(__name__) +from .commands.remove_expired_content import RemoveExpiredContent from .commands.update_ingest import UpdateIngest from .commands.add_provider import AddProvider # NOQA @@ -33,6 +34,7 @@ @celery.task() def fetch_ingest...
23075e994d081a90a1b3ed48b7e30b82c4614854
tests/test_acf.py
tests/test_acf.py
import pytest from steamfiles import acf @pytest.yield_fixture def acf_data(): with open('tests/test_data/appmanifest_202970.acf', 'rt') as f: yield f.read() @pytest.mark.usefixtures('acf_data') def test_loads_dumps(acf_data): assert acf.dumps(acf.loads(acf_data)) == acf_data
import io import pytest from steamfiles import acf test_file_name = 'tests/test_data/appmanifest_202970.acf' @pytest.yield_fixture def acf_data(): with open(test_file_name, 'rt') as f: yield f.read() @pytest.mark.usefixtures('acf_data') def test_loads_dumps(acf_data): assert acf.dumps(acf.loads(acf...
Add more tests for ACF format
Add more tests for ACF format
Python
mit
leovp/steamfiles
--- +++ @@ -1,13 +1,28 @@ +import io import pytest from steamfiles import acf + +test_file_name = 'tests/test_data/appmanifest_202970.acf' @pytest.yield_fixture def acf_data(): - with open('tests/test_data/appmanifest_202970.acf', 'rt') as f: + with open(test_file_name, 'rt') as f: yield f.read...
3f57221af38a25dceb9d1024c225481ec2f49328
parchment/views.py
parchment/views.py
from django.conf import settings from django.views.generic import FormView from .crypto import Parchment from .forms import ParchmentForm class ParchmentView(FormView): form_class = ParchmentForm template_name = 'parchment/login.html' def get_initial(self): sso_key = getattr(settings, 'PARCHMENT...
from urllib import urlencode from django.conf import settings from django.views.generic import FormView from .crypto import Parchment from .forms import ParchmentForm class ParchmentView(FormView): form_class = ParchmentForm template_name = 'parchment/login.html' connect_variables = {} def get(self...
Encrypt all provided GET parameters
Encrypt all provided GET parameters
Python
bsd-3-clause
jbittel/django-parchment,jbittel/django-parchment
--- +++ @@ -1,3 +1,5 @@ +from urllib import urlencode + from django.conf import settings from django.views.generic import FormView @@ -8,9 +10,15 @@ class ParchmentView(FormView): form_class = ParchmentForm template_name = 'parchment/login.html' + connect_variables = {} + + def get(self, request,...
93ebb6982851a710ff17c856059b1368bed24168
server.py
server.py
import flask app = flask.Flask(__name__) @app.route('/') def index(): return flask.jsonify(hello='world') if __name__ == '__main__': app.run(debug=True)
import flask app = flask.Flask(__name__) def make_tour(): tour = { 'id': 1, 'name': 'Test Tour', 'route': [ { 'description': 'This is a description of this place.', 'photos': ['photo1.jpg', 'photo2.jpg'], 'coordinate': (3, 4), }, { 'coordinate': (2, 3), }, { 'coordinate': (4, 1) ...
Add /tours endpoint with dummy data
Add /tours endpoint with dummy data
Python
mit
wtg/RPI_Tours_Server
--- +++ @@ -1,10 +1,33 @@ import flask app = flask.Flask(__name__) + +def make_tour(): + tour = { + 'id': 1, + 'name': 'Test Tour', + 'route': [ + { + 'description': 'This is a description of this place.', + 'photos': ['photo1.jpg', 'photo2.jpg'], + 'coordinate': (3, 4), + }, { + 'coordinate': ...
0f2ccc881e8d2b8b0f4064e3e1fae39b14875821
tortilla/utils.py
tortilla/utils.py
# -*- coding: utf-8 -*- import six from formats import FormatBank, discover_json, discover_yaml formats = FormatBank() discover_json(formats, content_type='application/json') discover_yaml(formats, content_type='application/x-yaml') def run_from_ipython(): try: __IPYTHON__ return True exc...
# -*- coding: utf-8 -*- import six from formats import FormatBank, discover_json, discover_yaml formats = FormatBank() discover_json(formats, content_type='application/json') discover_yaml(formats, content_type='application/x-yaml') def run_from_ipython(): return getattr(__builtins__, "__IPYTHON__", False) ...
Refactor run_from_ipython() implementation to make it pass static code analysis test
Refactor run_from_ipython() implementation to make it pass static code analysis test
Python
mit
redodo/tortilla
--- +++ @@ -12,11 +12,7 @@ def run_from_ipython(): - try: - __IPYTHON__ - return True - except NameError: - return False + return getattr(__builtins__, "__IPYTHON__", False) class Bunch(dict):
45d442cfe9c737332ca75e68e1488667937015ed
src/repository/models.py
src/repository/models.py
from django.db import models import git, os class Github (models.Model): username = models.CharField(max_length=39) repository = models.CharField(max_length=100) def __str__(self): return self.repository def clone_repository(self): DIR_NAME = self.repository REMOTE_URL = "http...
from django.db import models from django.conf import settings import git, os class Github (models.Model): username = models.CharField(max_length=39) repository = models.CharField(max_length=100) def __str__(self): return self.repository def clone_repository(self): DIR_NAME = os.path.j...
Clone repository to playbooks directory
Clone repository to playbooks directory
Python
bsd-3-clause
lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin
--- +++ @@ -1,4 +1,5 @@ from django.db import models +from django.conf import settings import git, os class Github (models.Model): @@ -9,10 +10,10 @@ return self.repository def clone_repository(self): - DIR_NAME = self.repository + DIR_NAME = os.path.join(settings.PLAYBOOK_DIR, self...
ca43660869bbd390979a928dc219e016c1a0607a
api/route_settings.py
api/route_settings.py
import json import falcon import models import schemas import api_util settings_schema = schemas.SettingSchema(many=True) setting_schema = schemas.SettingSchema() class SettingsResource: def on_get(self, req, resp): settings = models.Setting.select() settings_dict = {} for setting in...
import json import falcon import models import schemas import api_util class SettingsResource: def on_get(self, req, resp): settings = models.Setting.select() settings_dict = {} for setting in settings: settings_dict[setting.key] = setting.value resp.body = api_uti...
Remove reference to now-deleted SettingSchema
Remove reference to now-deleted SettingSchema
Python
mit
thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline
--- +++ @@ -5,10 +5,6 @@ import models import schemas import api_util - - -settings_schema = schemas.SettingSchema(many=True) -setting_schema = schemas.SettingSchema() class SettingsResource:
b86bcfd1f1762cbb956b3eb42b515107249cb66e
production_settings.py
production_settings.py
from default_settings import * import dj_database_url DATABASES = { 'default': dj_database_url.config(), } SECRET_KEY = os.environ['SECRET_KEY'] STATICFILES_STORAGE = 's3storage.S3HashedFilesStorage' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY', '') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_KEY...
from default_settings import * import dj_database_url DATABASES = { 'default': dj_database_url.config(), } SECRET_KEY = os.environ['SECRET_KEY'] STATICFILES_STORAGE = 's3storage.S3HashedFilesStorage' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY', '') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_KEY...
Disable querystring auth for s3
Disable querystring auth for s3
Python
mit
brutasse/djangopeople,brutasse/djangopeople,django/djangopeople,django/djangopeople,django/djangopeople,brutasse/djangopeople,polinom/djangopeople,polinom/djangopeople,brutasse/djangopeople,polinom/djangopeople,polinom/djangopeople
--- +++ @@ -13,6 +13,7 @@ AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY', '') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_KEY', '') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_BUCKET_NAME', '') +AWS_QUERYSTRING_AUTH = False STATIC_URL = 'https://s3.amazonaws.com/%s/' % AWS_STORAGE_BUCKET_NAME
51a2ac2d66d4245626f3d8830bb47f596b3d9879
app/minify.py
app/minify.py
# Python 3 import glob import os uglifyjs = os.path.abspath("../lib/uglifyjs") input_dir = os.path.abspath("./Resources/Tracker/scripts") output_dir = os.path.abspath("./Resources/Tracker/scripts.min") for file in glob.glob(input_dir + "/*.js"): name = os.path.basename(file) print("Minifying {0}...".format(n...
#!/usr/bin/env python3 import glob import os import shutil import sys if os.name == "nt": uglifyjs = os.path.abspath("../lib/uglifyjs.cmd") else: uglifyjs = "uglifyjs" if shutil.which(uglifyjs) is None: print("Cannot find executable: {0}".format(uglifyjs)) sys.exit(1) input_dir = os.path.abspath("./...
Fix app minification script on non-Windows systems
Fix app minification script on non-Windows systems
Python
mit
chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker
--- +++ @@ -1,9 +1,19 @@ -# Python 3 +#!/usr/bin/env python3 import glob import os +import shutil +import sys -uglifyjs = os.path.abspath("../lib/uglifyjs") +if os.name == "nt": + uglifyjs = os.path.abspath("../lib/uglifyjs.cmd") +else: + uglifyjs = "uglifyjs" + +if shutil.which(uglifyjs) is None: + pr...
c3c8c566c8294715b07614c1d18a2c6de3a7c212
app/models.py
app/models.py
from app import db class User(db.Model): __tablename__ = 'users' username = db.Column(db.String(64), nullable=False, unique=True, primary_key=True) password = db.Column(db.String(192), nullable=False) def __init__(self, username, password): self.username = username self.email = pass...
from app import db class User(db.Model): __tablename__ = 'users' username = db.Column(db.String(64), nullable=False, unique=True, primary_key=True) password = db.Column(db.String(192), nullable=False) def __init__(self, username, password): self.username = username self.password = p...
Fix variable names in model.
Fix variable names in model.
Python
mit
jawrainey/atc,jawrainey/atc
--- +++ @@ -9,10 +9,10 @@ def __init__(self, username, password): self.username = username - self.email = password + self.password = password def __repr__(self): - return 'The users name is: %r' % self.name + return 'The users name is: %r' % self.username class ...
105d46937babb7a43901d8238fb9cc0a7b00c8c9
lyman/tools/commandline.py
lyman/tools/commandline.py
import argparse parser = argparse.ArgumentParser() parser.add_argument("-subjects", nargs="*", dest="subjects", help=("list of subject ids, name of file in lyman " "directory, or full path to text file with " "subject ids")) parser.add_argument("...
import argparse parser = argparse.ArgumentParser() parser.add_argument("-subjects", nargs="*", dest="subjects", help=("list of subject ids, name of file in lyman " "directory, or full path to text file with " "subject ids")) parser.add_argument("...
Add slurm to command line plugin choices
Add slurm to command line plugin choices
Python
bsd-3-clause
mwaskom/lyman,tuqc/lyman,kastman/lyman
--- +++ @@ -7,8 +7,8 @@ "directory, or full path to text file with " "subject ids")) parser.add_argument("-plugin", default="multiproc", - choices=["linear", "multiproc", - "ipython", "torque", "sge"], + ...
f3c95f9875c59564faff909b0cf5a8869515b1f3
readthedocs/rtd_tests/tests/__init__.py
readthedocs/rtd_tests/tests/__init__.py
from test_api import * from view_tests import * from test_doc_building import * from test_backend import *
from test_api import * #from view_tests import * from test_doc_building import * from test_backend import *
Kill the view tests for now, to get them greeeeeen
Kill the view tests for now, to get them greeeeeen
Python
mit
agjohnson/readthedocs.org,kdkeyser/readthedocs.org,laplaceliu/readthedocs.org,LukasBoersma/readthedocs.org,fujita-shintaro/readthedocs.org,davidfischer/readthedocs.org,cgourlay/readthedocs.org,stevepiercy/readthedocs.org,soulshake/readthedocs.org,hach-que/readthedocs.org,SteveViss/readthedocs.org,raven47git/readthedocs...
--- +++ @@ -1,4 +1,4 @@ from test_api import * -from view_tests import * +#from view_tests import * from test_doc_building import * from test_backend import *
ac95449e6774538756d7813d73c8b113f9dcb6e6
axis/configuration.py
axis/configuration.py
"""Python library to enable Axis devices to integrate with Home Assistant.""" import requests from requests.auth import HTTPDigestAuth class Configuration(object): """Device configuration.""" def __init__(self, *, loop, host, username, password, port=80, web_proto='http', ve...
"""Python library to enable Axis devices to integrate with Home Assistant.""" import requests from requests.auth import HTTPDigestAuth class Configuration(object): """Device configuration.""" def __init__(self, *, loop, host, username, password, port=80, web_proto='http', v...
Allow to properly disable verification of SSL
Allow to properly disable verification of SSL
Python
mit
Kane610/axis
--- +++ @@ -2,6 +2,7 @@ import requests from requests.auth import HTTPDigestAuth + class Configuration(object): """Device configuration.""" @@ -19,10 +20,8 @@ self.password = password self.session = requests.Session() - self.session.auth = HTTPDigestAuth( - self.usern...
0e30e73ffa928b11fd6ee6c0ea12709100623e5f
pltpreview/view.py
pltpreview/view.py
"""Convenience functions for matplotlib plotting and image viewing.""" import numpy as np from matplotlib import pyplot as plt def show(image, blocking=False, title='', **kwargs): """Show *image*. If *blocking* is False the call is nonblocking. *title* is the image title. *kwargs* are passed to matplotlib's ...
"""Convenience functions for matplotlib plotting and image viewing.""" import numpy as np from matplotlib import pyplot as plt def show(image, blocking=False, title='', **kwargs): """Show *image*. If *blocking* is False the call is nonblocking. *title* is the image title. *kwargs* are passed to matplotlib's ...
Use pop for getting blocking parameter
Use pop for getting blocking parameter
Python
mit
tfarago/pltpreview
--- +++ @@ -25,7 +25,7 @@ sets the figure title. This command always creates a new figure. Returns a list of ``Line2D`` instances. """ - blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking') + blocking = kwargs.pop('blocking', False) title = kwargs.pop('title', '') ...
f8b83fc7976768c2b9d92ab35297aa17637eeb92
firefed/feature/addons.py
firefed/feature/addons.py
import json from feature import Feature from output import good, bad, info from tabulate import tabulate class Addons(Feature): def run(self, args): with open(self.profile_path('extensions.json')) as f: addons = json.load(f)['addons'] info(('%d addons found. (%d active)\n' % ...
import json from feature import Feature from output import good, bad, info from tabulate import tabulate def signed_state(num): # See constants defined in [1] states = { -2: 'broken', -1: 'unknown', 0: 'missing', 1: 'preliminary', 2: 'signed', 3: 'system', ...
Add signature and visibility status to addon feature
Add signature and visibility status to addon feature
Python
mit
numirias/firefed
--- +++ @@ -4,12 +4,27 @@ from tabulate import tabulate +def signed_state(num): + # See constants defined in [1] + states = { + -2: 'broken', + -1: 'unknown', + 0: 'missing', + 1: 'preliminary', + 2: 'signed', + 3: 'system', + 4: 'privileged' + } + tex...
314b8cf14eb3bed9b116b78ce0199e73399a4dab
businesstime/test/holidays/aus_test.py
businesstime/test/holidays/aus_test.py
from datetime import datetime, date, timedelta import unittest from businesstime.holidays.aus import QueenslandPublicHolidays, BrisbanePublicHolidays class QueenslandPublicHolidaysTest(unittest.TestCase): def test_2016_08(self): holidays_gen = QueenslandPublicHolidays() self.assertEqual( ...
from datetime import datetime, date, timedelta import unittest from businesstime.holidays.aus import QueenslandPublicHolidays, BrisbanePublicHolidays class QueenslandPublicHolidaysTest(unittest.TestCase): def test_2016_08(self): holidays_gen = QueenslandPublicHolidays() self.assertEqual( ...
Fix tests in python 2.6
Fix tests in python 2.6
Python
bsd-2-clause
seatgeek/businesstime
--- +++ @@ -27,5 +27,6 @@ def test_out_of_range(self): holidays_gen = BrisbanePublicHolidays() - with self.assertRaises(NotImplementedError): - list(holidays_gen(date(2017, 1, 1), end=date(2017, 12, 31))) + def test(): + return list(holidays_gen(date(2017, 1, 1), en...
f3cdd316f9e0859f77389c68b073134a6076374b
ppp_datamodel_notation_parser/requesthandler.py
ppp_datamodel_notation_parser/requesthandler.py
"""Request handler of the module.""" from functools import partial from ppp_datamodel import Sentence, TraceItem, Response from ppp_datamodel.parsers import parse_triples, ParseError def tree_to_response(measures, trace, tree): trace = trace + [TraceItem('DatamodelNotationParser', ...
"""Request handler of the module.""" from functools import partial from ppp_datamodel import Sentence, TraceItem, Response from ppp_datamodel.parsers import parse_triples, ParseError def tree_to_response(tree, measures, trace): trace = trace + [TraceItem('DatamodelNotationParser', ...
Fix compatibility with new parser.
Fix compatibility with new parser.
Python
mit
ProjetPP/PPP-DatamodelNotationParser,ProjetPP/PPP-DatamodelNotationParser
--- +++ @@ -5,7 +5,7 @@ from ppp_datamodel import Sentence, TraceItem, Response from ppp_datamodel.parsers import parse_triples, ParseError -def tree_to_response(measures, trace, tree): +def tree_to_response(tree, measures, trace): trace = trace + [TraceItem('DatamodelNotationParser', ...
9ec8949d62188efe8c40e859c20fc55339f4e7e2
taca/utils/filesystem.py
taca/utils/filesystem.py
"""Filesystem utilities.""" import contextlib import os import shutil RUN_RE = '^\d{6}_[a-zA-Z\d\-]+_\d{4}_[AB0][A-Z\d\-]+$' @contextlib.contextmanager def chdir(new_dir): """Context manager to temporarily change to a new directory.""" cur_dir = os.getcwd() os.chdir(new_dir) try: yield fin...
"""Filesystem utilities.""" import contextlib import os import shutil RUN_RE = '^\d{6}_[a-zA-Z\d\-]+_\d{2,}_[AB0][A-Z\d\-]+$' @contextlib.contextmanager def chdir(new_dir): """Context manager to temporarily change to a new directory.""" cur_dir = os.getcwd() os.chdir(new_dir) try: yield fi...
Fix FC name pattern for NextSeq2000
Fix FC name pattern for NextSeq2000
Python
mit
SciLifeLab/TACA,SciLifeLab/TACA,SciLifeLab/TACA
--- +++ @@ -3,7 +3,7 @@ import os import shutil -RUN_RE = '^\d{6}_[a-zA-Z\d\-]+_\d{4}_[AB0][A-Z\d\-]+$' +RUN_RE = '^\d{6}_[a-zA-Z\d\-]+_\d{2,}_[AB0][A-Z\d\-]+$' @contextlib.contextmanager def chdir(new_dir):
bd31b43fc6f282f2f6cc4bf11a6ae5c51e0e3501
bot/config.py
bot/config.py
import os import logging import pytz BOT_URL = os.getenv("BOT_URL", "") ENVIRONMENT = os.getenv("ENVIRONMENT", "local") WEBHOOK = os.getenv("WEBHOOK", "") BOTTLE_PORT = os.getenv("BOTTLE_PORT", "8080") BOTTLE_HOST = os.getenv("BOTTLE_HOST", "127.0.0.1") LAST_UPDATE_ID_FILE = "last_update" GROUPS_DB_NAME = "tags" POLL_...
import os import logging import pytz BOT_URL = os.getenv("BOT_URL", "") ENVIRONMENT = os.getenv("ENVIRONMENT", "local") WEBHOOK = os.getenv("WEBHOOK", "") BOTTLE_PORT = os.getenv("BOTTLE_PORT", "8080") BOTTLE_HOST = os.getenv("BOTTLE_HOST", "127.0.0.1") LAST_UPDATE_ID_FILE = "last_update" GROUPS_DB_NAME = "tags" POLL_...
Add Pending migration env var
Add Pending migration env var
Python
mit
cesar0094/telegram-tldrbot
--- +++ @@ -13,3 +13,4 @@ MAX_TAGS = 5 LOGGING_LEVEL = logging.DEBUG LOCAL_TIMEZONE = pytz.timezone('America/Mexico_City') +PENDING_MIGRATION = os.getenv("PENDING_MIGRATION", False)
e64b0544b146cb810424e0e243835a34aa977f40
boxoffice/__init__.py
boxoffice/__init__.py
# -*- coding: utf-8 -*- # imports in this file are order-sensitive from pytz import timezone from flask import Flask from flask.ext.mail import Mail from flask.ext.lastuser import Lastuser from flask.ext.lastuser.sqlalchemy import UserManager from baseframe import baseframe, assets, Version from ._version import __vers...
# -*- coding: utf-8 -*- # imports in this file are order-sensitive from pytz import timezone from flask import Flask from flask.ext.mail import Mail from flask.ext.lastuser import Lastuser from flask.ext.lastuser.sqlalchemy import UserManager from baseframe import baseframe, assets, Version from ._version import __vers...
Add assests ractive-transitions-fly and validate
Add assests ractive-transitions-fly and validate
Python
agpl-3.0
hasgeek/boxoffice,hasgeek/boxoffice,hasgeek/boxoffice,hasgeek/boxoffice
--- +++ @@ -37,7 +37,7 @@ lastuser.init_usermanager(UserManager(db, User)) app.config['tz'] = timezone(app.config['TIMEZONE']) - baseframe.init_app(app, requires=['boxoffice'], ext_requires=['baseframe-bs3', 'fontawesome>=4.0.0', 'ractive']) + baseframe.init_app(app, requires=['boxoffice'], ext_requ...
5736e8314d5af3346a15224b27448f1c795f665c
bin/coverage_check.py
bin/coverage_check.py
#!/usr/bin/env python import os import subprocess from lib import functional from util import find_all def coverage_module(package, module): command = ( 'coverage run --branch' ' --source=%s.%s tests/%s/%s_test.py') print subprocess.check_output( command % (package, module, package,...
#!/usr/bin/env python import os import subprocess from lib import functional from util import find_all def coverage_module(package, module): command = ( 'coverage run --branch' ' --source=%s.%s tests/%s/%s_test.py') print subprocess.check_output( command % (package, module, package,...
Remove hard coded 'engine' and 'lib' in coverage testing
Remove hard coded 'engine' and 'lib' in coverage testing
Python
mit
Tactique/game_engine,Tactique/game_engine
--- +++ @@ -38,7 +38,7 @@ def coverage_test_all(): os.chdir(os.environ['PORTER']) - for package in ['lib', 'engine']: + for package in os.listdir('src/'): coverage_test_package(package) if __name__ == '__main__':
4dd5dbf6c1f693c54b31a84756350cb9588921d1
pybinding/model.py
pybinding/model.py
from scipy.sparse import csr_matrix from . import _cpp from .system import System from .lattice import Lattice from .support.sparse import SparseMatrix class Model(_cpp.Model): def __init__(self, *params): super().__init__() self.add(*params) def add(self, *params): for param in para...
import numpy as np from scipy.sparse import csr_matrix from . import _cpp from . import results from .system import System from .lattice import Lattice from .support.sparse import SparseMatrix class Model(_cpp.Model): def __init__(self, *params): super().__init__() self.add(*params) def add(...
Add onsite energy map to Model
Add onsite energy map to Model
Python
bsd-2-clause
dean0x7d/pybinding,MAndelkovic/pybinding,MAndelkovic/pybinding,dean0x7d/pybinding,dean0x7d/pybinding,MAndelkovic/pybinding
--- +++ @@ -1,6 +1,8 @@ +import numpy as np from scipy.sparse import csr_matrix from . import _cpp +from . import results from .system import System from .lattice import Lattice from .support.sparse import SparseMatrix @@ -38,3 +40,9 @@ def modifiers(self) -> list: return (self.state_modifiers + ...
517c0f2b1f8e6616cc63ec0c3990dcff2922f0e6
pinax/invitations/admin.py
pinax/invitations/admin.py
from django.contrib import admin from django.contrib.auth import get_user_model from .models import InvitationStat, JoinInvitation User = get_user_model() class InvitationStatAdmin(admin.ModelAdmin): raw_id_fields = ["user"] readonly_fields = ["invites_sent", "invites_accepted"] list_display = [ ...
from django.contrib import admin from django.contrib.auth import get_user_model from .models import InvitationStat, JoinInvitation User = get_user_model() class InvitationStatAdmin(admin.ModelAdmin): raw_id_fields = ["user"] readonly_fields = ["invites_sent", "invites_accepted"] list_display = [ ...
Use f-strings in place of `str.format()`
Use f-strings in place of `str.format()`
Python
unknown
pinax/pinax-invitations,eldarion/kaleo
--- +++ @@ -24,6 +24,6 @@ JoinInvitation, list_display=["from_user", "to_user", "sent", "status", "to_user_email"], list_filter=["sent", "status"], - search_fields=["from_user__{}".format(User.USERNAME_FIELD)] + search_fields=[f"from_user__{User.USERNAME_FIELD}"] ) admin.site.register(Invitatio...
1918ed65e441057724b82a3cb710898f8742214b
canaryd/subprocess.py
canaryd/subprocess.py
import os import shlex import sys from canaryd_packages import six from canaryd.log import logger if os.name == 'posix' and sys.version_info[0] < 3: from canaryd_packages.subprocess32 import * # noqa else: from subprocess import * # noqa def get_command_output(command, *args, **kwargs): logger.debug...
import os import shlex import sys from canaryd_packages import six from canaryd.log import logger if os.name == 'posix' and sys.version_info[0] < 3: from canaryd_packages.subprocess32 import * # noqa else: from subprocess import * # noqa def get_command_output(command, *args, **kwargs): logger.debug...
Fix indent and don't decode input command.
Fix indent and don't decode input command.
Python
mit
Oxygem/canaryd,Oxygem/canaryd
--- +++ @@ -16,14 +16,11 @@ def get_command_output(command, *args, **kwargs): logger.debug('Executing command: {0}'.format(command)) - if isinstance(command, six.binary_type): - command = command.decode() - if ( not kwargs.get('shell', False) and not isinstance(command, (list,...
e6d216077a683aa07b811b5f131dd07809f741bc
readthedocs/settings/postgres.py
readthedocs/settings/postgres.py
from .base import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'docs', 'USER': 'postgres', # Not used with sqlite3. 'PASSWORD': '', 'HOST': 'golem', 'PORT': '', } } DEBUG = False TEMPLATE_DEBUG = F...
from .base import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'docs', 'USER': 'postgres', # Not used with sqlite3. 'PASSWORD': '', 'HOST': '10.177.73.97', 'PORT': '', } } DEBUG = False TEMPLATE_DE...
Update database server in the configs.
Update database server in the configs.
Python
mit
michaelmcandrew/readthedocs.org,ojii/readthedocs.org,safwanrahman/readthedocs.org,Tazer/readthedocs.org,CedarLogic/readthedocs.org,kdkeyser/readthedocs.org,GovReady/readthedocs.org,Tazer/readthedocs.org,nikolas/readthedocs.org,dirn/readthedocs.org,espdev/readthedocs.org,johncosta/private-readthedocs.org,gjtorikian/read...
--- +++ @@ -6,7 +6,7 @@ 'NAME': 'docs', 'USER': 'postgres', # Not used with sqlite3. 'PASSWORD': '', - 'HOST': 'golem', + 'HOST': '10.177.73.97', 'PORT': '', } }
6749c5a4541836fcf25abbc571082b4c909b0bbb
corehq/apps/app_manager/migrations/0019_exchangeapplication_required_privileges.py
corehq/apps/app_manager/migrations/0019_exchangeapplication_required_privileges.py
# Generated by Django 2.2.24 on 2021-09-14 17:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app_manager', '0018_migrate_case_search_labels'), ] operations = [ migrations.AddField( model_name='exchangeapplication', ...
# Generated by Django 2.2.24 on 2021-09-14 17:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app_manager', '0018_migrate_case_search_labels'), ] operations = [ migrations.AddField( model_name='exchangeapplication', ...
Fix migration with help text
Fix migration with help text
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
--- +++ @@ -13,6 +13,7 @@ migrations.AddField( model_name='exchangeapplication', name='required_privileges', - field=models.TextField(help_text='Space-separated list of privilege strings from corehq.privileges', null=True), + field=models.TextField(null=True, h...
3291b015a5f3d311c72980913756a08d87b1ac1a
scripts/blacklisted.py
scripts/blacklisted.py
import os import platform # If you are adding a new entry, please include a short comment # explaining why the specific test is blacklisted. _unix_black_list = set([name.lower() for name in [ 'blackparrot', 'blackucode', 'blackunicore', 'earlgrey_nexysvideo', # ram size in ci machines 'lpddr', 'simplepa...
import os import platform # If you are adding a new entry, please include a short comment # explaining why the specific test is blacklisted. _unix_black_list = set([name.lower() for name in [ 'blackparrot', 'blackucode', 'blackunicore', 'earlgrey_nexysvideo', # ram size in ci machines 'lpddr', 'rsd', ...
Exclude a few failing tests
Exclude a few failing tests Rsd - failing on linux due to running out of memory Verilator - failing on Windows clang due to stack overflow caused by expression evaluation
Python
apache-2.0
chipsalliance/Surelog,alainmarcel/Surelog,alainmarcel/Surelog,chipsalliance/Surelog,alainmarcel/Surelog,chipsalliance/Surelog,alainmarcel/Surelog,chipsalliance/Surelog
--- +++ @@ -8,15 +8,17 @@ 'blackparrot', 'blackucode', 'blackunicore', - 'earlgrey_nexysvideo', # ram size in ci machines + 'earlgrey_nexysvideo', # ram size in ci machines 'lpddr', - 'simpleparsertestcache', # race condition + 'rsd', # Out of memory on CI machines + 'simplepa...
77fc06c0ee8ca2c8669ca1cd7f45babb21d75ba5
opps/__init__.py
opps/__init__.py
import pkg_resources pkg_resources.declare_namespace(__name__)
# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: from pkgutil import extend_path __path__ = extend_path(__path__, __name__)
Remove opps package on opps-polls
Remove opps package on opps-polls
Python
mit
opps/opps-polls,opps/opps-polls
--- +++ @@ -1,3 +1,6 @@ -import pkg_resources - -pkg_resources.declare_namespace(__name__) +# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages +try: + __import__('pkg_resources').declare_namespace(__name__) +except ImportError: + from pkgutil import extend_path + __path__ = extend_pa...
fb427a72bf3d8fb3802689bf89a9d71dee47108c
semillas_backend/users/serializers.py
semillas_backend/users/serializers.py
#from phonenumber_field.serializerfields import PhoneNumberField from rest_framework import serializers from drf_extra_fields.geo_fields import PointField from .models import User class UserSerializer(serializers.ModelSerializer): """ Usage: from rest_framework.renderers import JSONRenderer from ...
#from phonenumber_field.serializerfields import PhoneNumberField from rest_framework import serializers from drf_extra_fields.geo_fields import PointField from .models import User class UserSerializer(serializers.ModelSerializer): """ Usage: from rest_framework.renderers import JSONRenderer from ...
Add location to user profile post
Add location to user profile post
Python
mit
Semillas/semillas_backend,Semillas/semillas_backend,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_platform,Semillas/semillas_platform
--- +++ @@ -25,10 +25,11 @@ email = serializers.CharField(required=False) picture = serializers.ImageField(required=False) uuid = serializers.CharField(read_only=True) + location = PointField(required=False) class Meta: model = User - fields = ('name', 'picture', 'phone', 'ema...
54f27f507820b5c9a7e832c46eb2a5ba3d918a2f
scripts/task/solver.py
scripts/task/solver.py
import numpy as np from eigen3 import toEigen import rbdyn as rbd class WLSSolver(object): def __init__(self): self.tasks = [] def addTask(self, task, weight): t = [task, weight] self.tasks.append(t) return t def rmTask(self, taskDef): self.tasks.remove(taskDef) def solve(self, mb, ...
import numpy as np from eigen3 import toEigenX import rbdyn as rbd class WLSSolver(object): def __init__(self): self.tasks = [] def addTask(self, task, weight): t = [task, weight] self.tasks.append(t) return t def rmTask(self, taskDef): self.tasks.remove(taskDef) def solve(self, mb,...
Fix a bad eigen vector cast.
Fix a bad eigen vector cast.
Python
bsd-2-clause
jrl-umi3218/RBDyn,gergondet/RBDyn,gergondet/RBDyn,gergondet/RBDyn,jrl-umi3218/RBDyn,jrl-umi3218/RBDyn,jrl-umi3218/RBDyn,gergondet/RBDyn,gergondet/RBDyn
--- +++ @@ -1,6 +1,6 @@ import numpy as np -from eigen3 import toEigen +from eigen3 import toEigenX import rbdyn as rbd class WLSSolver(object): @@ -31,5 +31,5 @@ #alpha1 = np.linalg.lstsq(jac, err)[0] alpha2 = np.linalg.pinv(jac)*err - mbc.alpha = rbd.vectorToDof(mb, toEigen(alpha2)) + mbc.a...
e913ed7d5643c4acc85ed7ec82a70c235053360f
tests/test_token.py
tests/test_token.py
""" NOTE: There are no tests that check for data validation at this point since the interpreter doesn't have any data validation as a feature. """ import pytest from calc import INTEGER, Token def test_no_defaults(): # There's no valid defaults at the moment. with pytest.raises(TypeError): Token() ...
import pytest from calc import INTEGER, Token def test_token_cannot_be_instantiated_with_no_defaults(): """ Test that there are currently no valid defaults for a :class:`Token`. More simply, ensure that a :class:`Token` cannot be instantiated without any arguments. """ with pytest.raises(Type...
Improve documentation in token tests. Rename functions to be more clear
Improve documentation in token tests. Rename functions to be more clear
Python
isc
bike-barn/red-green-refactor
--- +++ @@ -1,27 +1,33 @@ -""" - -NOTE: There are no tests that check for data validation at this point since -the interpreter doesn't have any data validation as a feature. -""" import pytest from calc import INTEGER, Token -def test_no_defaults(): - # There's no valid defaults at the moment. +def test_to...
9b043b0bd31f35e140831f61a4484513922f8712
stop_words/__init__.py
stop_words/__init__.py
import os __VERSION__ = (2014, 5, 26) CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) STOP_WORDS_DIR = os.path.join(CURRENT_DIR, 'stop-words/') def get_version(): """ :rtype: basestring """ return ".".join(str(v) for v in __VERSION__) def get_stop_words(language): """ :type langua...
import os __VERSION__ = (2014, 5, 26) CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) STOP_WORDS_DIR = os.path.join(CURRENT_DIR, 'stop-words/') LANGUAGE_MAPPING = { 'ar': 'arabic', 'da': 'danish', 'nl': 'dutch', 'en': 'english', 'fi': 'finnish', 'fr': 'french', 'de': 'german', ...
Implement language code mapping and check availability of the language
Implement language code mapping and check availability of the language
Python
bsd-3-clause
Alir3z4/python-stop-words
--- +++ @@ -4,6 +4,26 @@ CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) STOP_WORDS_DIR = os.path.join(CURRENT_DIR, 'stop-words/') +LANGUAGE_MAPPING = { + 'ar': 'arabic', + 'da': 'danish', + 'nl': 'dutch', + 'en': 'english', + 'fi': 'finnish', + 'fr': 'french', + 'de': 'german', + ...
c30bd67d4fc1773ce8b0752d8e4a7cc00e2a7ae4
app/forms.py
app/forms.py
from flask.ext.wtf import Form from wtforms import StringField, BooleanField from wtforms.validators import DataRequired class LoginForm(Form): openid = StringField('openid', validators=[DataRequired()]) remember_me = BooleanField('remember_me', default=False)
from flask.ext.wtf import Form from wtforms import StringField, BooleanField, TextAreaField from wtforms.validators import DataRequired, Length class LoginForm(Form): openid = StringField('openid', validators=[DataRequired()]) remember_me = BooleanField('remember_me', default=False) class EditForm(Form): ...
Define the edit profile form
Define the edit profile form
Python
mit
ddayguerrero/blogme,ddayguerrero/blogme,ddayguerrero/blogme,ddayguerrero/blogme,ddayguerrero/blogme
--- +++ @@ -1,8 +1,13 @@ from flask.ext.wtf import Form -from wtforms import StringField, BooleanField -from wtforms.validators import DataRequired +from wtforms import StringField, BooleanField, TextAreaField +from wtforms.validators import DataRequired, Length class LoginForm(Form): openid = StringField(...
1d0dd7856d1c1e80f24a94af4fc323530383b009
readthedocs/gold/models.py
readthedocs/gold/models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ LEVEL_CHOICES = ( ('v1-org-patron', '$5'), ('v1-org-supporter', '$10'), ) class GoldUser(models.Model): pub_date = models.DateTimeField(_('Publication date'), auto_now_add=True) modified_date = models.DateTimeField(_...
from django.db import models from django.utils.translation import ugettext_lazy as _ LEVEL_CHOICES = ( ('v1-org-5', '$5/mo'), ('v1-org-10', '$10/mo'), ('v1-org-15', '$15/mo'), ('v1-org-20', '$20/mo'), ('v1-org-50', '$50/mo'), ('v1-org-100', '$100/mo'), ) class GoldUser(models.Model): pub_...
Update plan names and levels
Update plan names and levels
Python
mit
hach-que/readthedocs.org,istresearch/readthedocs.org,VishvajitP/readthedocs.org,laplaceliu/readthedocs.org,stevepiercy/readthedocs.org,VishvajitP/readthedocs.org,davidfischer/readthedocs.org,jerel/readthedocs.org,clarkperkins/readthedocs.org,soulshake/readthedocs.org,sunnyzwh/readthedocs.org,michaelmcandrew/readthedocs...
--- +++ @@ -2,8 +2,12 @@ from django.utils.translation import ugettext_lazy as _ LEVEL_CHOICES = ( - ('v1-org-patron', '$5'), - ('v1-org-supporter', '$10'), + ('v1-org-5', '$5/mo'), + ('v1-org-10', '$10/mo'), + ('v1-org-15', '$15/mo'), + ('v1-org-20', '$20/mo'), + ('v1-org-50', '$50/mo'), + ...
e8aca80abcf8c309c13360c386b9505a595e1998
app/oauth.py
app/oauth.py
# -*- coding: utf-8 -*- import logging import httplib2 import json import time import random from apiclient import errors from apiclient.discovery import build from oauth2client.client import SignedJwtAssertionCredentials class OAuth(): __services = dict() @staticmethod def getCredentials(email, scopes, ...
# -*- coding: utf-8 -*- import logging import httplib2 import json import time import random from apiclient import errors from apiclient.discovery import build from oauth2client.client import SignedJwtAssertionCredentials class OAuth(): __services = dict() @staticmethod def getCredentials(email, scopes, ...
Revert "Do not cache discovery"
Revert "Do not cache discovery" This reverts commit fcd37e8228d66230008963008a24e9a8afc669e7.
Python
mit
lumapps/lumRest
--- +++ @@ -38,11 +38,9 @@ credentials, http = OAuth.getCredentials(email, scopes, client_secret, client_id) if discoveryUrl: - OAuth.__services[key] = build(api, version, http=http, discoveryServiceUrl=discoveryUrl, - cache_disco...
eb2f19a95175d68c5ac5345d38c8ce8db3b3ba9c
packs/linux/actions/get_open_ports.py
packs/linux/actions/get_open_ports.py
import nmap from st2actions.runners.pythonrunner import Action """ Note: This action requires nmap binary to be available and needs to run as root. """ class PortScanner(Action): def run(self, host): result = [] port_details = {} ps = nmap.PortScanner() scan_res = ps.scan(host, arguments='--min-pa...
import nmap from st2actions.runners.pythonrunner import Action """ Note: This action requires nmap binary to be available and needs to run as root. """ class PortScanner(Action): def run(self, host): result = [] port_details = {} ps = nmap.PortScanner() scan_res = ps.scan(host, arguments='--min-pa...
Remove unused main entry point.
Remove unused main entry point.
Python
apache-2.0
pinterb/st2contrib,psychopenguin/st2contrib,tonybaloney/st2contrib,jtopjian/st2contrib,StackStorm/st2contrib,pearsontechnology/st2contrib,psychopenguin/st2contrib,lmEshoo/st2contrib,lmEshoo/st2contrib,meirwah/st2contrib,pidah/st2contrib,armab/st2contrib,tonybaloney/st2contrib,pearsontechnology/st2contrib,digideskio/st2...
--- +++ @@ -22,9 +22,5 @@ for port in ports: port_details = {port:{'state':ps[host][comm][port]['state'], 'service':ps[host][comm][port]['name'], 'protocol':comm}} result.append(port_details) + return result - -if __name__ == "__main__": - ps = PortScanner() - ps.r...
0024b8b921d788a0539bc242bd1600c0da666bd6
panoptes/state_machine/states/core.py
panoptes/state_machine/states/core.py
import time import transitions from panoptes.utils.logger import has_logger @has_logger class PanState(transitions.State): """ Base class for PANOPTES transitions """ def __init__(self, *args, **kwargs): name = kwargs.get('name', self.__class__) self.panoptes = kwargs.get('panoptes', None)...
import time import transitions from panoptes.utils.logger import has_logger @has_logger class PanState(transitions.State): """ Base class for PANOPTES transitions """ def __init__(self, *args, **kwargs): name = kwargs.get('name', self.__class__) self.panoptes = kwargs.get('panoptes', None)...
Remove return state from main `main`
Remove return state from main `main`
Python
mit
panoptes/POCS,panoptes/POCS,joshwalawender/POCS,AstroHuntsman/POCS,joshwalawender/POCS,joshwalawender/POCS,panoptes/POCS,panoptes/POCS,AstroHuntsman/POCS,AstroHuntsman/POCS,AstroHuntsman/POCS
--- +++ @@ -22,7 +22,6 @@ assert self.panoptes is not None msg = "Must implement `main` method inside class {}. Exiting".format(self.name) self.panoptes.logger.warning(msg) - return 'exit' def sleep(self, seconds=None): """ sleep for `seconds` or `_sleep_delay` second...
b529ef8eb6985103e8b0a0cf81399a50a26c05f5
app/views.py
app/views.py
from app import mulungwishi_app as url from flask import render_template @url.route('/') def index(): return render_template('index.html') @url.route('/<query>') def print_user_input(query): if '=' in query: query_container, query_value = query.split('=') return 'Your query is {} which is eq...
from app import mulungwishi_app as url from flask import render_template @url.route('/') def index(): return render_template('index.html') @url.route('/<query>') def print_user_input(query): if '=' in query: query_container, query_value = query.split('=') return 'Your query is {} which is eq...
Replace 404 redirection for incorrect query
Replace 404 redirection for incorrect query
Python
mit
admiral96/mulungwishi-webhook,engagespark/mulungwishi-webhook,engagespark/public-webhooks,engagespark/public-webhooks,admiral96/public-webhooks,admiral96/mulungwishi-webhook,engagespark/mulungwishi-webhook,admiral96/public-webhooks
--- +++ @@ -12,7 +12,7 @@ if '=' in query: query_container, query_value = query.split('=') return 'Your query is {} which is equal to {}'.format(query_container, query_value) - return page_not_found(404) + return "You've entered an incorrect query. Please check and try again. Input : "+qu...
e45b3d3a2428d3703260c25b4275359bf6786a37
launcher.py
launcher.py
from pract2d.game import gamemanager if __name__ == '__main__': game = gamemanager.GameManager() game.run()
from pract2d.game import gamemanager from pract2d.core import files from platform import system import os if __name__ == '__main__': try: if system() == 'Windows' or not os.environ["PYSDL2_DLL_PATH"]: os.environ["PYSDL2_DLL_PATH"] = files.get_path() except KeyError: pass game = ...
Set the default sdl2 library locations.
Set the default sdl2 library locations.
Python
bsd-2-clause
mdsitton/pract2d
--- +++ @@ -1,5 +1,13 @@ from pract2d.game import gamemanager +from pract2d.core import files +from platform import system +import os if __name__ == '__main__': + try: + if system() == 'Windows' or not os.environ["PYSDL2_DLL_PATH"]: + os.environ["PYSDL2_DLL_PATH"] = files.get_path() + exce...
5c90e74139f2735d0b4d62f524eb624780c48847
scripts/migration/projectorganizer/migrate_projectorganizer.py
scripts/migration/projectorganizer/migrate_projectorganizer.py
"""Fixes nodes without is_folder set. This script must be run from the OSF root directory for the imports to work. """ from framework.mongo import database def main(): database['node'].update({"is_folder": {'$exists': False}}, {'$set': {'is_folder': False}}, multi=True) print('-----\nDone.') if __name__ ...
"""Fixes nodes without is_folder set. This script must be run from the OSF root directory for the imports to work. """ from framework.mongo import database def main(): database['node'].update({"is_folder": {'$exists': False}}, {'$set': {'is_folder': False}}, multi=True) database['node'].update({"is_dashboa...
Update migration to ensure node's have is_dashboard and expanded fields
Update migration to ensure node's have is_dashboard and expanded fields
Python
apache-2.0
kushG/osf.io,cwisecarver/osf.io,cldershem/osf.io,caseyrygt/osf.io,ticklemepierce/osf.io,brandonPurvis/osf.io,danielneis/osf.io,rdhyee/osf.io,pattisdr/osf.io,barbour-em/osf.io,Johnetordoff/osf.io,felliott/osf.io,samchrisinger/osf.io,Johnetordoff/osf.io,mfraezz/osf.io,DanielSBrown/osf.io,crcresearch/osf.io,mluke93/osf.io...
--- +++ @@ -9,6 +9,8 @@ def main(): database['node'].update({"is_folder": {'$exists': False}}, {'$set': {'is_folder': False}}, multi=True) + database['node'].update({"is_dashboard": {'$exists': False}}, {'$set': {'is_dashboard': False}}, multi=True) + database['node'].update({"expanded": {'$exists': Fal...
42465957542fe232739d58c2a46098d13fb9c995
tests/parser_db.py
tests/parser_db.py
from compiler import error, parse class ParserDB(): """A class for parsing with memoized parsers.""" parsers = {} @classmethod def _parse(cls, data, start='program'): mock = error.LoggerMock() try: parser = cls.parsers[start] except KeyError: parser =...
from compiler import error, parse class ParserDB(): """A class for parsing with memoized parsers.""" parsers = {} @classmethod def _parse(cls, data, start='program'): mock = error.LoggerMock() try: parser = cls.parsers[start] except KeyError: parser =...
Clear previous logger state on each call.
ParserDB: Clear previous logger state on each call.
Python
mit
Renelvon/llama,dionyziz/llama,dionyziz/llama,Renelvon/llama
--- +++ @@ -18,6 +18,9 @@ start=start ) + # Clear previous logger state prior to parsing. + parser.logger.clear() + tree = parser.parse(data=data) return tree
c01cef9340a3d55884fe38b60b209dbad5f97ea6
nova/db/sqlalchemy/migrate_repo/versions/080_add_hypervisor_hostname_to_compute_nodes.py
nova/db/sqlalchemy/migrate_repo/versions/080_add_hypervisor_hostname_to_compute_nodes.py
# Copyright 2012 OpenStack, LLC # # 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 ...
# Copyright 2012 OpenStack, LLC # # 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 ...
Use sqlalchemy reflection in migration 080
Use sqlalchemy reflection in migration 080 Change-Id: If2a0e59461d108d59c6e9907d3db053ba2b44f57
Python
apache-2.0
petrutlucian94/nova,adelina-t/nova,DirectXMan12/nova-hacking,sridevikoushik31/nova,gooddata/openstack-nova,alvarolopez/nova,whitepages/nova,thomasem/nova,affo/nova,berrange/nova,eayunstack/nova,mahak/nova,cernops/nova,felixma/nova,apporc/nova,cyx1231st/nova,openstack/nova,klmitch/nova,JianyuWang/nova,CiscoSystems/nova,...
--- +++ @@ -12,22 +12,19 @@ # See the License for the specific language governing permissions and # limitations under the License. -from sqlalchemy import * - - -meta = MetaData() - -compute_nodes = Table("compute_nodes", meta, Column("id", Integer(), - primary_key=True, nullable=False)) - -hypervisor_...
452955ca8b7ba2ef01fc97800e5f350fee3e3a6e
tvnamer/renamer.py
tvnamer/renamer.py
import re import os import pytvdbapi.api as tvdb class Renamer: def __init__(self, api_key): self.tvdb = tvdb.TVDB(api_key) @staticmethod def flat_file_list(directory): directory = os.path.normpath(directory) for dirpath, dirnames, filenames in os.walk(directory): fo...
import re import os import pytvdbapi.api as tvdb class Renamer: def __init__(self, api_key): self.tvdb = tvdb.TVDB(api_key) @staticmethod def flat_file_list(directory): directory = os.path.normpath(directory) for dirpath, dirnames, filenames in os.walk(directory): fo...
Add normalising params from the regex input
Add normalising params from the regex input
Python
mit
tomleese/tvnamer,thomasleese/tvnamer
--- +++ @@ -19,6 +19,18 @@ full_path = full_path[len(directory)+1:] yield full_path + @staticmethod + def normalise_params(params): + def normalise(key, value): + if key == "show": + return str(value) + elif key in ["episode", "seas...
38496eddbb214ee856b588e5b1cda62d5e353ab7
system_maintenance/tests/functional/tests.py
system_maintenance/tests/functional/tests.py
from selenium import webdriver import unittest class FunctionalTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): self.browser.quit() def test_app_home_title(self): self.browser.get('http://loc...
Add simple functional test to test the title of the app's home page
Add simple functional test to test the title of the app's home page
Python
bsd-3-clause
mfcovington/django-system-maintenance,mfcovington/django-system-maintenance,mfcovington/django-system-maintenance
--- +++ @@ -0,0 +1,20 @@ +from selenium import webdriver +import unittest + + +class FunctionalTest(unittest.TestCase): + + def setUp(self): + self.browser = webdriver.Firefox() + self.browser.implicitly_wait(3) + + def tearDown(self): + self.browser.quit() + + def test_app_home_title(se...
c0b09cc5d1f51672e696364616552008c13b89c4
packages/Python/lldbsuite/test/commands/expression/import-std-module/sysroot/TestStdModuleSysroot.py
packages/Python/lldbsuite/test/commands/expression/import-std-module/sysroot/TestStdModuleSysroot.py
""" Test that we respect the sysroot when building the std module. """ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil import os class ImportStdModule(TestBase): mydir = TestBase.compute_mydir(__file__) @skipIf(compiler=no_match("clang")) ...
""" Test that we respect the sysroot when building the std module. """ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil import os class ImportStdModule(TestBase): mydir = TestBase.compute_mydir(__file__) # We only emulate a fake libc++ in this...
Add import-std-module/sysroot to the libc++ test category.
[lldb] Add import-std-module/sysroot to the libc++ test category. We essentially test libc++ in a sysroot here so let's make sure that we actually only run this test on platforms where libc++ testing is enabled. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@374572 91177308-0d34-0410-b5e6-96231b3b80d8
Python
apache-2.0
llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb
--- +++ @@ -11,6 +11,10 @@ mydir = TestBase.compute_mydir(__file__) + # We only emulate a fake libc++ in this test and don't use the real libc++, + # but we still add the libc++ category so that this test is only run in + # test configurations where libc++ is actually supposed to be tested. + @ad...
39086b074dbac8d6d743ede09ce3556e4861e5a4
wdim/client/blob.py
wdim/client/blob.py
import json import hashlib from wdim.client.storable import Storable class Blob(Storable): HASH_METHOD = 'sha1' @classmethod def _create(cls, data): sha = hashlib(cls.HASH_METHOD, json.dumps(data)) return cls(sha, data) @classmethod def _from_document(cls, document): re...
import json import hashlib from wdim import exceptions from wdim.client import fields from wdim.client.storable import Storable class Blob(Storable): HASH_METHOD = 'sha256' _id = fields.StringField(unique=True) data = fields.DictField() @classmethod async def create(cls, data): sha = h...
Reimplement Blob, switch to sha256
Reimplement Blob, switch to sha256
Python
mit
chrisseto/Still
--- +++ @@ -1,31 +1,27 @@ import json import hashlib +from wdim import exceptions +from wdim.client import fields from wdim.client.storable import Storable class Blob(Storable): - HASH_METHOD = 'sha1' + HASH_METHOD = 'sha256' + + _id = fields.StringField(unique=True) + data = fields.DictField(...
ca7580c12ffefafce1705d60ab74fcb22af18eb4
examples/python_interop/python_interop.py
examples/python_interop/python_interop.py
#!/usr/bin/env python # Copyright 2017 Stanford University # # 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 applicabl...
#!/usr/bin/env python # Copyright 2017 Stanford University # # 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 applicabl...
Update Python example with a task call.
examples: Update Python example with a task call.
Python
apache-2.0
StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion
--- +++ @@ -20,9 +20,10 @@ import legion @legion.task -def f(task, regions, context, runtime): +def f(ctx): print("inside task f") @legion.task -def main_task(task, regions, context, runtime): - print("%x" % legion.c.legion_runtime_get_executing_processor(runtime, context).id) +def main_task(ctx): + ...
a839dcaa51cde0bf191cc87ff2cf54bbc483d61e
main.py
main.py
#!/usr/bin/env python import sys import json from pprint import pprint try: import requests except ImportError: print( 'Script requires requests package. \n' 'You can install it by running "pip install requests"' ) exit() API_URL = 'http://jsonplaceholder.typicode.com/posts/' def get_...
#!/usr/bin/env python import sys import json from pprint import pprint try: import requests except ImportError: print( 'Script requires requests package. \n' 'You can install it by running "pip install requests"' ) exit() API_URL = 'http://jsonplaceholder.typicode.com/posts/' def get_...
Print all data from posts
Print all data from posts
Python
mit
sevazhidkov/rest-wrapper
--- +++ @@ -33,14 +33,23 @@ return False return True + +def print_post(post): + for (key, value) in post.items(): + print key + ':', value + print('Loading data') # If user didn't provided id, print all posts. # Else - validate id and get post by id. if len(sys.argv) == 1: - pprint(ge...
032bd078b7650905148ceb3adf653d1f78f7e73f
srtm.py
srtm.py
import os import json import numpy as np SAMPLES = 1201 # For SRTM3, use 3601 for SRTM1 def get_elevation(lat, lon): file = get_file_name(lat, lon) if file: return read_elevation_from_file(file, lat, lon) # Treat it as data void as in SRTM documentation return -32768 def read_elevation_from...
import os import json import numpy as np SAMPLES = 1201 # For SRTM3, use 3601 for SRTM1 HGTDIR = 'hgt' # All 'hgt' files will be kept here uncompressed def get_elevation(lat, lon): file = get_file_name(lat, lon) if file: return read_elevation_from_file(file, lat, lon) # Treat it as data void as in...
Add HGTDIR to store hgt files inside a directory
Add HGTDIR to store hgt files inside a directory
Python
mit
aatishnn/srtm-python
--- +++ @@ -3,7 +3,7 @@ import numpy as np SAMPLES = 1201 # For SRTM3, use 3601 for SRTM1 - +HGTDIR = 'hgt' # All 'hgt' files will be kept here uncompressed def get_elevation(lat, lon): file = get_file_name(lat, lon) @@ -26,6 +26,7 @@ def get_file_name(lat, lon): file = "N%(lat)dE0%(lon)d.hgt" % {...
1bf15bca7a492bf874dccab08e24df053b7a859f
mesh.py
mesh.py
import os import sys import traceback builtin_cmds = {'cd', 'pwd',} def prompt(): print '%s $ ' % os.getcwd(), def read_command(): return sys.stdin.readline() def parse_command(cmd_text): return (cmd_text, cmd_text.strip().split()) def record_command(command): return True def run_builtin(cmd): ...
#!/usr/bin/env python3 import os import shutil import sys import traceback builtin_cmds = {'cd', 'pwd', 'exit',} def prompt(): print('%s $ ' % os.getcwd(), end='', flush=True) def read_command(): return sys.stdin.readline() def parse_command(cmd_text): return (cmd_text, cmd_text.strip().split()) def r...
Switch to Python 3, add exit built_in
Switch to Python 3, add exit built_in
Python
mit
mmichie/mesh
--- +++ @@ -1,11 +1,14 @@ +#!/usr/bin/env python3 + import os +import shutil import sys import traceback -builtin_cmds = {'cd', 'pwd',} +builtin_cmds = {'cd', 'pwd', 'exit',} def prompt(): - print '%s $ ' % os.getcwd(), + print('%s $ ' % os.getcwd(), end='', flush=True) def read_command(): retur...
35d5ca76a0c7f63545d2e8bc6b877c78ba9eab1d
tests/adapter/_path.py
tests/adapter/_path.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys def fix(): p = os.path.join(os.path.dirname(__file__), '../../src/') if p not in sys.path: sys.path.insert(0, p) if "__main__" == __name__: fix()
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from unittest import mock except ImportError: import mock def fix(): p = os.path.join(os.path.dirname(__file__), '../../src/') if p not in sys.path: sys.path.insert(0, p) if "__main__" == __name__: fix()
Make 'mock' mocking library available for test cases stored under 'tests/adapter'
Make 'mock' mocking library available for test cases stored under 'tests/adapter'
Python
bsd-3-clause
michalbachowski/pygrapes,michalbachowski/pygrapes,michalbachowski/pygrapes
--- +++ @@ -2,11 +2,18 @@ # -*- coding: utf-8 -*- import os import sys + +try: + from unittest import mock +except ImportError: + import mock + def fix(): p = os.path.join(os.path.dirname(__file__), '../../src/') if p not in sys.path: sys.path.insert(0, p) + if "__main__" == __name__...
3e843b9d0474657eeefc896b06e50968defb2514
wsgi.py
wsgi.py
# Yith Library Server is a password storage server. # Copyright (C) 2015 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as publ...
# Yith Library Web Client is a client for Yith Library Server. # Copyright (C) 2015 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Web Client. # # Yith Library Web Client is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Pub...
Fix project name in license section
Fix project name in license section
Python
agpl-3.0
lorenzogil/yith-library-web-client,ablanco/yith-library-web-client,ablanco/yith-library-web-client,lorenzogil/yith-library-web-client,ablanco/yith-library-web-client,ablanco/yith-library-web-client,lorenzogil/yith-library-web-client,lorenzogil/yith-library-web-client
--- +++ @@ -1,20 +1,20 @@ -# Yith Library Server is a password storage server. +# Yith Library Web Client is a client for Yith Library Server. # Copyright (C) 2015 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # -# This file is part of Yith Library Server. +# This file is part of Yith Library Web Client. # -...
cadab3fef1e95c0b186dc28860ac4797243fdf22
tests/test_visualization.py
tests/test_visualization.py
from tornado.httpclient import HTTPRequest import json import os.path import json import shutil from xml.etree import ElementTree as ET from util import generate_filename from util import make_trace_folder from tests.base import BaseRecorderTestCase class VisualizationTestCase(BaseRecorderTestCase): def test_no...
from tornado.httpclient import HTTPRequest import json import os.path import json import shutil from xml.etree import ElementTree as ET from util import generate_filename from util import make_trace_folder from tests.base import BaseRecorderTestCase class VisualizationTestCase(BaseRecorderTestCase): def test_no...
Update test case for visualization page.
Update test case for visualization page.
Python
bsd-3-clause
openxc/web-logging-example,openxc/web-logging-example
--- +++ @@ -15,4 +15,4 @@ def test_no_data(self): self.http_client.fetch(self.get_url('/visualization'), self.stop) response = self.wait() - assert 'class="vehicle"' in response.body + assert "measurement" in response.body
eaaf941646ff8b22a6d3ef3689f22ad1b9f7a8e2
tensorflow/contrib/py2tf/impl/config.py
tensorflow/contrib/py2tf/impl/config.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
Add the utils module to the uncompiled whitelist.
Add the utils module to the uncompiled whitelist. PiperOrigin-RevId: 185733139
Python
apache-2.0
jbedorf/tensorflow,arborh/tensorflow,zasdfgbnm/tensorflow,jhseu/tensorflow,kobejean/tensorflow,Intel-tensorflow/tensorflow,ZhangXinNan/tensorflow,jbedorf/tensorflow,jart/tensorflow,nburn42/tensorflow,annarev/tensorflow,ghchinoy/tensorflow,annarev/tensorflow,kobejean/tensorflow,ageron/tensorflow,dendisuhubdy/tensorflow,...
--- +++ @@ -18,6 +18,9 @@ from __future__ import division from __future__ import print_function +from tensorflow.contrib.py2tf import utils + + PYTHON_LITERALS = { 'None': None, 'False': False, @@ -27,6 +30,7 @@ DEFAULT_UNCOMPILED_MODULES = set(( ('tensorflow',), + (utils.__name__,), )) ...
cba3b00a92194cb34d27a63e71a17f2239079c7b
setup.py
setup.py
from setuptools import setup import os setup( name = "cmsplugin-bootstrap-carousel", packages = ['cmsplugin_bootstrap_carousel',], package_data = { '': [ 'templates/cmsplugin_bootstrap_carousel/*.html', ] }, version = "0.1.2", description = "Bootstrap carousel plug...
from setuptools import setup import os setup( name = "cmsplugin-bootstrap-carousel", packages = ['cmsplugin_bootstrap_carousel',], package_data = { '': [ 'templates/cmsplugin_bootstrap_carousel/*.html', ] }, version = "0.1.3", description = "Bootstrap carousel plug...
Upgrade the version to force reinstall by wheels
Upgrade the version to force reinstall by wheels
Python
bsd-3-clause
360youlun/cmsplugin-bootstrap-carousel,360youlun/cmsplugin-bootstrap-carousel
--- +++ @@ -11,7 +11,7 @@ ] }, - version = "0.1.2", + version = "0.1.3", description = "Bootstrap carousel plugin for django-cms 2.2", long_description=open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(), author = "Antoine Nguyen",
255d1f753ee8b48cbb2d7131e72ebc5dfbaf443c
setup.py
setup.py
from setuptools import setup import editorconfig setup( name='EditorConfig', version=editorconfig.__version__, author='EditorConfig Team', packages=['editorconfig'], url='http://editorconfig.org/', license='LICENSE.txt', description='EditorConfig File Locator and Interpreter for Python', ...
from setuptools import setup import editorconfig setup( name='EditorConfig', version=editorconfig.__version__, author='EditorConfig Team', packages=['editorconfig'], url='http://editorconfig.org/', license='LICENSE.txt', description='EditorConfig File Locator and Interpreter for Python', ...
Rename `editorconfig.py` command to `editorconfig`
Rename `editorconfig.py` command to `editorconfig`
Python
bsd-2-clause
pocke/editorconfig-vim,VictorBjelkholm/editorconfig-vim,benjifisher/editorconfig-vim,VictorBjelkholm/editorconfig-vim,johnfraney/editorconfig-vim,pocke/editorconfig-vim,benjifisher/editorconfig-vim,johnfraney/editorconfig-vim,benjifisher/editorconfig-vim,pocke/editorconfig-vim,johnfraney/editorconfig-vim,VictorBjelkhol...
--- +++ @@ -12,7 +12,7 @@ long_description=open('README.rst').read(), entry_points = { 'console_scripts': [ - 'editorconfig.py = editorconfig.main:main', + 'editorconfig = editorconfig.main:main', ] }, )
28cdad6e8ab6bd400ef50331a2f93af93620cc7f
app/models.py
app/models.py
from django.db import models class Event(models.Model): when = models.DateTimeField(auto_now=True) what = models.TextField()
from django.db import models class Event(models.Model): when = models.DateTimeField(auto_now=True) what = models.TextField() def time(self): return '{:%H:%M}'.format(self.when)
Return human-sensible time in Event
Return human-sensible time in Event
Python
mit
schatten/logan
--- +++ @@ -3,3 +3,6 @@ class Event(models.Model): when = models.DateTimeField(auto_now=True) what = models.TextField() + + def time(self): + return '{:%H:%M}'.format(self.when)