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
53f7acf5fc04ca6f86456fda95504ba41046d860
openedx/features/specializations/templatetags/sso_meta_tag.py
openedx/features/specializations/templatetags/sso_meta_tag.py
from django import template from django.template import Template register = template.Library() @register.simple_tag(takes_context=True) def sso_meta(context): return Template('<meta name="title" content="${ title }">' + ' ' + '<meta name="description" content="${ subtitle }">' + ' ' + ...
from django import template from django.template.loader import get_template register = template.Library() @register.simple_tag(takes_context=True) def sso_meta(context): return get_template('features/specializations/sso_meta_template.html').render(context.flatten())
Add Django Custom Tag SSO
Add Django Custom Tag SSO
Python
agpl-3.0
philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform
--- +++ @@ -1,25 +1,9 @@ from django import template -from django.template import Template +from django.template.loader import get_template register = template.Library() @register.simple_tag(takes_context=True) def sso_meta(context): - return Template('<meta name="title" content="${ title }">' + ' ' + - ...
27bf030df4c2f46eef8cdcd9441bd5d21a22e5cc
parkings/api/public/urls.py
parkings/api/public/urls.py
from django.conf.urls import include, url from rest_framework.routers import DefaultRouter from .parking_area import PublicAPIParkingAreaViewSet from .parking_area_statistics import PublicAPIParkingAreaStatisticsViewSet router = DefaultRouter() router.register(r'parking_area', PublicAPIParkingAreaViewSet) router.regi...
from django.conf.urls import include, url from rest_framework.routers import DefaultRouter from .parking_area import PublicAPIParkingAreaViewSet from .parking_area_statistics import PublicAPIParkingAreaStatisticsViewSet router = DefaultRouter() router.register(r'parking_area', PublicAPIParkingAreaViewSet, base_name='...
Fix public API root view links
Fix public API root view links
Python
mit
tuomas777/parkkihubi
--- +++ @@ -5,8 +5,8 @@ from .parking_area_statistics import PublicAPIParkingAreaStatisticsViewSet router = DefaultRouter() -router.register(r'parking_area', PublicAPIParkingAreaViewSet) -router.register(r'parking_area_statistics', PublicAPIParkingAreaStatisticsViewSet) +router.register(r'parking_area', PublicAPI...
1eb3df5ca3c86effa85ba76a8bdf549f3560f3a5
landscapesim/serializers/regions.py
landscapesim/serializers/regions.py
import json from rest_framework import serializers from landscapesim.models import Region class ReportingUnitSerializer(serializers.Serializer): type = serializers.SerializerMethodField() properties = serializers.SerializerMethodField() geometry = serializers.SerializerMethodField() class Meta: ...
import json from rest_framework import serializers from django.core.urlresolvers import reverse from landscapesim.models import Region class ReportingUnitSerializer(serializers.Serializer): type = serializers.SerializerMethodField() properties = serializers.SerializerMethodField() geometry = serializers...
Add reporting unit URL to region serializer.
Add reporting unit URL to region serializer.
Python
bsd-3-clause
consbio/landscapesim,consbio/landscapesim,consbio/landscapesim
--- +++ @@ -1,6 +1,7 @@ import json from rest_framework import serializers +from django.core.urlresolvers import reverse from landscapesim.models import Region @@ -29,6 +30,11 @@ class RegionSerializer(serializers.ModelSerializer): + url = serializers.SerializerMethodField() + class Meta: ...
521b4fbec142306fad2347a5dd3a56aeec2f9498
events/search_indexes.py
events/search_indexes.py
from haystack import indexes from .models import Event, Place, PublicationStatus from django.utils.html import strip_tags class EventIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) autosuggest = indexes.EdgeNgramField(model_attr='name') start_time ...
from haystack import indexes from .models import Event, Place, PublicationStatus from django.utils.html import strip_tags class EventIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) autosuggest = indexes.EdgeNgramField(model_attr='name') start_time ...
Remove deleted places from place index
Remove deleted places from place index
Python
mit
aapris/linkedevents,aapris/linkedevents,tuomas777/linkedevents,City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents,tuomas777/linkedevents,City-of-Helsinki/linkedevents,tuomas777/linkedevents,aapris/linkedevents
--- +++ @@ -34,3 +34,6 @@ def get_model(self): return Place + + def index_queryset(self, using=None): + return self.get_model().objects.filter(deleted=False)
c65b6adafcdf791030090a72f4490171012ce4fd
config/fuzz_pox_simple.py
config/fuzz_pox_simple.py
from config.experiment_config_lib import ControllerConfig from sts.topology import MeshTopology from sts.control_flow import Fuzzer from sts.input_traces.input_logger import InputLogger from sts.simulation_state import SimulationConfig # Use POX as our controller start_cmd = ('''./pox.py openflow.discovery forwarding...
from config.experiment_config_lib import ControllerConfig from sts.topology import MeshTopology from sts.control_flow import Fuzzer from sts.input_traces.input_logger import InputLogger from sts.simulation_state import SimulationConfig # Use POX as our controller start_cmd = ('''./pox.py samples.buggy ''' ...
Use a buggy pox module
Use a buggy pox module
Python
apache-2.0
ucb-sts/sts,jmiserez/sts,jmiserez/sts,ucb-sts/sts
--- +++ @@ -6,7 +6,7 @@ from sts.simulation_state import SimulationConfig # Use POX as our controller -start_cmd = ('''./pox.py openflow.discovery forwarding.l2_multi ''' +start_cmd = ('''./pox.py samples.buggy ''' '''openflow.of_01 --address=__address__ --port=__port__''') controllers = [Controlle...
84f4626a623283c3c4d98d9be0ccd69fe837f772
download_data.py
download_data.py
#!/usr/bin/env python from lbtoolbox.download import download import os import inspect import tarfile def here(f): me = inspect.getsourcefile(here) return os.path.join(os.path.dirname(os.path.abspath(me)), f) def download_extract(url, into): fname = download(url, into) print("Extracting...") w...
#!/usr/bin/env python from lbtoolbox.download import download import os import inspect import tarfile def here(f): me = inspect.getsourcefile(here) return os.path.join(os.path.dirname(os.path.abspath(me)), f) def download_extract(urlbase, name, into): print("Downloading " + name) fname = download(...
Update download URL and add more output to downloader.
Update download URL and add more output to downloader.
Python
mit
lucasb-eyer/BiternionNet
--- +++ @@ -12,22 +12,25 @@ return os.path.join(os.path.dirname(os.path.abspath(me)), f) -def download_extract(url, into): - fname = download(url, into) +def download_extract(urlbase, name, into): + print("Downloading " + name) + fname = download(os.path.join(urlbase, name), into) print("Extrac...
c94c86df52184af6b07dcf58951688cea178b8e6
dmoj/executors/LUA.py
dmoj/executors/LUA.py
from .base_executor import ScriptExecutor class Executor(ScriptExecutor): ext = '.lua' name = 'LUA' command = 'lua' address_grace = 131072 test_program = "io.write(io.read('*all'))" @classmethod def get_version_flags(cls, command): return ['-v']
from .base_executor import ScriptExecutor class Executor(ScriptExecutor): ext = '.lua' name = 'LUA' command = 'lua' command_paths = ['lua', 'lua5.3', 'lua5.2', 'lua5.1'] address_grace = 131072 test_program = "io.write(io.read('*all'))" @classmethod def get_version_flags(cls, command):...
Make lua autoconfig work better.
Make lua autoconfig work better.
Python
agpl-3.0
DMOJ/judge,DMOJ/judge,DMOJ/judge
--- +++ @@ -5,6 +5,7 @@ ext = '.lua' name = 'LUA' command = 'lua' + command_paths = ['lua', 'lua5.3', 'lua5.2', 'lua5.1'] address_grace = 131072 test_program = "io.write(io.read('*all'))"
7cef87a81278c227db0cb07329d1b659dbd175b3
mail_factory/models.py
mail_factory/models.py
# -*- coding: utf-8 -*- import django from django.conf import settings from django.utils.importlib import import_module from django.utils.module_loading import module_has_submodule def autodiscover(): """Auto-discover INSTALLED_APPS mails.py modules.""" for app in settings.INSTALLED_APPS: module = '...
# -*- coding: utf-8 -*- import django from django.conf import settings from django.utils.module_loading import module_has_submodule try: from importlib import import_module except ImportError: # Compatibility for python-2.6 from django.utils.importlib import import_module def autodiscover(): """Auto...
Use standard library instead of django.utils.importlib
Use standard library instead of django.utils.importlib > django.utils.importlib is a compatibility library for when Python 2.6 was > still supported. It has been obsolete since Django 1.7, which dropped support > for Python 2.6, and is removed in 1.9 per the deprecation cycle. > Use Python's import_module function ins...
Python
bsd-3-clause
novafloss/django-mail-factory,novafloss/django-mail-factory
--- +++ @@ -2,8 +2,13 @@ import django from django.conf import settings -from django.utils.importlib import import_module from django.utils.module_loading import module_has_submodule + +try: + from importlib import import_module +except ImportError: + # Compatibility for python-2.6 + from django.utils.i...
3ca11cd2ba0bcff8bbc4d01df2ba5b72f5b2e4b0
warehouse/packaging/urls.py
warehouse/packaging/urls.py
# Copyright 2013 Donald Stufft # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
# Copyright 2013 Donald Stufft # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
Remove the plural from the url
Remove the plural from the url
Python
apache-2.0
robhudson/warehouse,mattrobenolt/warehouse,techtonik/warehouse,techtonik/warehouse,mattrobenolt/warehouse,mattrobenolt/warehouse,robhudson/warehouse
--- +++ @@ -19,12 +19,12 @@ urls = [ EndpointPrefix("warehouse.packaging.views.", [ Rule( - "/projects/<project_name>/", + "/project/<project_name>/", methods=["GET"], endpoint="project_detail", ), Rule( - "/projects/<project_...
6b2202d0b7a4ef544b63e1692e40c5fec9c5930a
dash_renderer/__init__.py
dash_renderer/__init__.py
# For reasons that I don't fully understand, # unless I include __file__ in here, the packaged version # of this module will just be a .egg file, not a .egg folder. # And if it's just a .egg file, it won't include the necessary # dependencies from MANIFEST.in. # Found the __file__ clue by inspecting the `python setup.p...
# For reasons that I don't fully understand, # unless I include __file__ in here, the packaged version # of this module will just be a .egg file, not a .egg folder. # And if it's just a .egg file, it won't include the necessary # dependencies from MANIFEST.in. # Found the __file__ clue by inspecting the `python setup.p...
Extend import statement to support Python 3
Extend import statement to support Python 3
Python
mit
plotly/dash,plotly/dash,plotly/dash,plotly/dash,plotly/dash
--- +++ @@ -7,7 +7,7 @@ # command in the dash_html_components package which printed out: # `dash_html_components.__init__: module references __file__` # TODO - Understand this better -from version import __version__ +from .version import __version__ __file__ # Dash renderer's dependencies get loaded in a speci...
ad276d549eebe9c6fe99a629a76f02fc04b2bd51
tests/test_pubannotation.py
tests/test_pubannotation.py
import kindred def test_pubannotation(): corpus = kindred.pubannotation.load('bionlp-st-gro-2013-development') assert isinstance(corpus,kindred.Corpus) fileCount = len(corpus.documents) entityCount = sum([ len(d.entities) for d in corpus.documents ]) relationCount = sum([ len(d.relations) for d in corpus.docum...
import kindred def test_pubannotation(): corpus = kindred.pubannotation.load('bionlp-st-gro-2013-development') assert isinstance(corpus,kindred.Corpus) fileCount = len(corpus.documents) entityCount = sum([ len(d.entities) for d in corpus.documents ]) relationCount = sum([ len(d.relations) for d in corpus.docum...
Simplify pubannotation test to not check exact numbers
Simplify pubannotation test to not check exact numbers
Python
mit
jakelever/kindred,jakelever/kindred
--- +++ @@ -10,9 +10,9 @@ entityCount = sum([ len(d.entities) for d in corpus.documents ]) relationCount = sum([ len(d.relations) for d in corpus.documents ]) - assert fileCount == 50 - assert relationCount == 1454 - assert entityCount == 2657 + assert fileCount > 0 + assert relationCount > 0 + assert entityCou...
4b659b7b2552da033753349e059eee172025e00e
adbwp/__init__.py
adbwp/__init__.py
""" adbwp ~~~~~ Android Debug Bridge (ADB) Wire Protocol. """ # pylint: disable=wildcard-import from . import exceptions from .exceptions import * from . import header from .header import Header from . import message from .message import Message __all__ = exceptions.__all__ + ['header', 'message', 'Heade...
""" adbwp ~~~~~ Android Debug Bridge (ADB) Wire Protocol. """ # pylint: disable=wildcard-import from . import exceptions, header, message from .exceptions import * from .header import Header from .message import Message __all__ = exceptions.__all__ + ['header', 'message', 'Header', 'Message'] __version__...
Reorder imports based on isort rules.
Reorder imports based on isort rules.
Python
apache-2.0
adbpy/wire-protocol
--- +++ @@ -6,11 +6,9 @@ """ # pylint: disable=wildcard-import -from . import exceptions +from . import exceptions, header, message from .exceptions import * -from . import header from .header import Header -from . import message from .message import Message __all__ = exceptions.__all__ + ['header', 'messag...
12b1b7a477cc99e1c3ec3405269999c7974677b6
aioinotify/cli.py
aioinotify/cli.py
import logging from argparse import ArgumentParser import asyncio from .protocol import connect_inotify logger = logging.getLogger(__name__) def main(): parser = ArgumentParser() parser.add_argument( '-ll', '--log-level', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'], default='WARNING') parser....
import logging from argparse import ArgumentParser import asyncio from .protocol import connect_inotify logger = logging.getLogger(__name__) def main(): parser = ArgumentParser() parser.add_argument( '-ll', '--log-level', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'], default='WARNING') parser....
Move getting the event loop out of try/except
Move getting the event loop out of try/except
Python
apache-2.0
mwfrojdman/aioinotify
--- +++ @@ -17,9 +17,10 @@ logging.basicConfig(level=getattr(logging, args.log_level)) + loop = asyncio.get_event_loop() try: - loop = asyncio.get_event_loop() _, inotify = loop.run_until_complete(connect_inotify()) + @asyncio.coroutine def run(inotify): ...
9384f76d4ecfe2a822747020ba20771019105aaa
metric_thread.py
metric_thread.py
#!/usr/bin/env python # Copyright 2014 Boundary, Inc. # # 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 o...
#!/usr/bin/env python # Copyright 2014 Boundary, Inc. # # 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 o...
Set threads to daemons so that they exit when the main thread exits
Set threads to daemons so that they exit when the main thread exits
Python
apache-2.0
boundary/boundary-plugin-shell,boundary/boundary-plugin-shell,jdgwartney/boundary-plugin-shell,jdgwartney/boundary-plugin-shell
--- +++ @@ -25,6 +25,7 @@ def __init__(self,item,mutex): Thread.__init__(self,name=item.getName()) + self.setDaemon(True) self.mutex = mutex self.pollingInterval = item.getPollingInterval() self.name = item.getName()
164b07fefdd8db74ccce7ff44c33a6120cd98c86
mfr/ext/tabular/libs/xlrd_tools.py
mfr/ext/tabular/libs/xlrd_tools.py
import xlrd from ..exceptions import TableTooBigException, EmptyTableException from ..configuration import config from ..utilities import header_population from ..compat import range def xlsx_xlrd(fp): """Read and convert a xlsx file to JSON format using the xlrd library :param fp: File pointer object :re...
import xlrd from ..exceptions import TableTooBigException, EmptyTableException from ..configuration import config from ..utilities import header_population from ..compat import range def xlsx_xlrd(fp): """Read and convert a xlsx file to JSON format using the xlrd library :param fp: File pointer object :re...
Fix xlrd issue Column headers must be strings
Fix xlrd issue Column headers must be strings
Python
apache-2.0
mfraezz/modular-file-renderer,rdhyee/modular-file-renderer,AddisonSchiller/modular-file-renderer,mfraezz/modular-file-renderer,TomBaxter/modular-file-renderer,rdhyee/modular-file-renderer,AddisonSchiller/modular-file-renderer,CenterForOpenScience/modular-file-renderer,felliott/modular-file-renderer,AddisonSchiller/modu...
--- +++ @@ -26,7 +26,7 @@ fields = sheet.row_values(0) if sheet.nrows else [] - fields = [value or 'Unnamed: {0}'.format(index+1) for index, value in enumerate(fields)] + fields = [str(value) or 'Unnamed: {0}'.format(index+1) for index, value in enumerate(fields)] data = [dict(zip(fields, sheet....
0f62dc9ba898db96390658107e9ebe9930f8b90a
mmiisort/main.py
mmiisort/main.py
from isort import SortImports import itertools import mothermayi.colors import mothermayi.errors def plugin(): return { 'name' : 'isort', 'pre-commit' : pre_commit, } def do_sort(filename): results = SortImports(filename) return results.in_lines != results.out_lines def ge...
from isort import SortImports import mothermayi.colors import mothermayi.errors def plugin(): return { 'name' : 'isort', 'pre-commit' : pre_commit, } def do_sort(filename): results = SortImports(filename) return results.in_lines != results.out_lines def get_status(had_chan...
Make plugin work in python 3
Make plugin work in python 3 Python 3 doesn't have itertools.izip, just the builtin, zip. This logic allows us to pull out either one depending on python version
Python
mit
EliRibble/mothermayi-isort
--- +++ @@ -1,5 +1,4 @@ from isort import SortImports -import itertools import mothermayi.colors import mothermayi.errors @@ -19,7 +18,7 @@ def pre_commit(config, staged): changes = [do_sort(filename) for filename in staged] messages = [get_status(had_change) for had_change in changes] - lines = ["...
014c8ca68b196c78b9044b194b762cdb3dfe6c78
app/hooks/views.py
app/hooks/views.py
from __future__ import absolute_import from __future__ import unicode_literals from app import app, webhooks @webhooks.hook( app.config.get('GITLAB_HOOK','/hooks/gitlab'), handler='gitlab') class Gitlab: def issue(self, data): pass def push(self, data): pass def tag_push(self, da...
from __future__ import absolute_import from __future__ import unicode_literals from app import app, webhooks @webhooks.hook( app.config.get('GITLAB_HOOK','/hooks/gitlab'), handler='gitlab') class Gitlab: def issue(self, data): # if the repository belongs to a group check if a channel with the same...
Add comment description of methods for gitlab hook
Add comment description of methods for gitlab hook
Python
apache-2.0
pipex/gitbot,pipex/gitbot,pipex/gitbot
--- +++ @@ -8,25 +8,42 @@ handler='gitlab') class Gitlab: def issue(self, data): + # if the repository belongs to a group check if a channel with the same + # name (lowercased and hyphened) exists + # Check if a channel with the same repository name exists + + # If the channel e...
6ecada90e944ee976197e0ee79baf1d711a20803
cla_public/apps/base/forms.py
cla_public/apps/base/forms.py
# -*- coding: utf-8 -*- "Base forms" from flask_wtf import Form from wtforms import StringField, TextAreaField from cla_public.apps.base.fields import MultiRadioField from cla_public.apps.base.constants import FEEL_ABOUT_SERVICE, \ HELP_FILLING_IN_FORM class FeedbackForm(Form): difficulty = TextAreaField(u'D...
# -*- coding: utf-8 -*- "Base forms" from flask_wtf import Form from wtforms import StringField, TextAreaField from cla_public.apps.base.fields import MultiRadioField from cla_public.apps.base.constants import FEEL_ABOUT_SERVICE, \ HELP_FILLING_IN_FORM from cla_public.apps.checker.honeypot import Honeypot class...
Add honeypot field to feedback form
Add honeypot field to feedback form
Python
mit
ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public
--- +++ @@ -7,8 +7,10 @@ from cla_public.apps.base.constants import FEEL_ABOUT_SERVICE, \ HELP_FILLING_IN_FORM +from cla_public.apps.checker.honeypot import Honeypot -class FeedbackForm(Form): + +class FeedbackForm(Honeypot, Form): difficulty = TextAreaField(u'Did you have any difficulty with this serv...
4c76a99e1d72820a367d2195fbd3edc1b0af30fd
organizer/models.py
organizer/models.py
from django.db import models # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Tag(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() class Startup(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() ...
from django.db import models # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Tag(models.Model): name = models.CharField( max_length=31, unique=True) slug = models.SlugField( max_length=31, unique=True, help_text='A label for URL config...
Add options to Tag model fields.
Ch03: Add options to Tag model fields. [skip ci] Field options allow us to easily customize behavior of a field. Global Field Options: https://docs.djangoproject.com/en/1.8/ref/models/fields/#help-text https://docs.djangoproject.com/en/1.8/ref/models/fields/#unique The max_length field option is defined in ...
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
--- +++ @@ -6,8 +6,12 @@ class Tag(models.Model): - name = models.CharField(max_length=31) - slug = models.SlugField() + name = models.CharField( + max_length=31, unique=True) + slug = models.SlugField( + max_length=31, + unique=True, + help_text='A label for URL config.')...
e2fbf646b193284fc5d01684193b9c5aeb415efe
generate_html.py
generate_html.py
from jinja2 import Environment, FileSystemLoader import datetime import json env = Environment(loader=FileSystemLoader('templates'), autoescape=True) names_template = env.get_template('names.html') area_template = env.get_template('areas.html') with open("output/templates.js") as templatesjs: templates = templat...
from jinja2 import Environment, FileSystemLoader import datetime import json env = Environment(loader=FileSystemLoader('templates'), autoescape=True) names_template = env.get_template('names.html') area_template = env.get_template('areas.html') with open("output/templates.js") as templatesjs: templates = templat...
Fix due to merge conflicts
Fix due to merge conflicts
Python
agpl-3.0
TalkAboutLocal/local-news-engine,TalkAboutLocal/local-news-engine,TalkAboutLocal/local-news-engine,TalkAboutLocal/local-news-engine
--- +++ @@ -22,10 +22,13 @@ with open("processed/interesting_names.json") as interesting_names_file: interesting_names = json.load(interesting_names_file) -with open('output/names.html', 'w+') as name_output: +with open('output/names.html', 'w+') as name_output, open("key_field_names.txt") as key_field_names_...
0ed9e159fa606c9dbdb90dfc64fcb357e9f9cedb
plenum/test/test_request.py
plenum/test/test_request.py
from indy_common.types import Request def test_request_all_identifiers_returns_empty_list_for_request_without_signatures(): req = Request() assert req.all_identifiers == []
from plenum.common.request import Request def test_request_all_identifiers_returns_empty_list_for_request_without_signatures(): req = Request() assert req.all_identifiers == []
Fix wrong import in test
Fix wrong import in test Signed-off-by: Sergey Khoroshavin <b770466c7a06c5fe47531d5f0e31684f1131354d@dsr-corporation.com>
Python
apache-2.0
evernym/zeno,evernym/plenum
--- +++ @@ -1,4 +1,4 @@ -from indy_common.types import Request +from plenum.common.request import Request def test_request_all_identifiers_returns_empty_list_for_request_without_signatures():
a16fd23027b5d3f1378f5b9f75958d0f3ef2a124
bandit/__init__.py
bandit/__init__.py
""" django-email-bandit is a Django email backend for hijacking email sending in a test environment. """ __version_info__ = { 'major': 0, 'minor': 2, 'micro': 0, 'releaselevel': 'final', } def get_version(): """ Return the formatted version information """ vers = ["%(major)i.%(minor)...
""" django-email-bandit is a Django email backend for hijacking email sending in a test environment. """ __version_info__ = { 'major': 1, 'minor': 0, 'micro': 0, 'releaselevel': 'dev', } def get_version(): """ Return the formatted version information """ vers = ["%(major)i.%(minor)i"...
Bump version number to reflect dev status.
Bump version number to reflect dev status.
Python
bsd-3-clause
caktus/django-email-bandit,vericant/django-email-bandit,caktus/django-email-bandit
--- +++ @@ -3,10 +3,10 @@ """ __version_info__ = { - 'major': 0, - 'minor': 2, + 'major': 1, + 'minor': 0, 'micro': 0, - 'releaselevel': 'final', + 'releaselevel': 'dev', } def get_version():
4f170397acac08c6fd8a4573ead1f66d631ac8dc
dsub/_dsub_version.py
dsub/_dsub_version.py
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
Update dsub version to 0.3.2.dev0
Update dsub version to 0.3.2.dev0 PiperOrigin-RevId: 243855458
Python
apache-2.0
DataBiosphere/dsub,DataBiosphere/dsub
--- +++ @@ -26,4 +26,4 @@ 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ -DSUB_VERSION = '0.3.1' +DSUB_VERSION = '0.3.2.dev0'
f604979e94fab59eb1b422d4e62ad62d3360c2ac
onserver/urls.py
onserver/urls.py
# -*- coding: utf-8 -*- """onserver URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.ho...
# -*- coding: utf-8 -*- """onserver URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.ho...
Use admin interface by default
Use admin interface by default
Python
mit
on-server/on-server-api,on-server/on-server-api
--- +++ @@ -18,5 +18,5 @@ from django.contrib import admin urlpatterns = [ - url(r'^admin/', admin.site.urls), + url(r'^', admin.site.urls), ]
0241e253c68ca6862a3da26d29a649f65c27ae36
demos/chatroom/experiment.py
demos/chatroom/experiment.py
"""Coordination chatroom game.""" import dallinger as dlgr from dallinger.config import get_config try: unicode = unicode except NameError: # Python 3 unicode = str config = get_config() def extra_settings(): config.register('network', unicode) config.register('n', int) class CoordinationChatroom...
"""Coordination chatroom game.""" import dallinger as dlgr from dallinger.compat import unicode from dallinger.config import get_config config = get_config() def extra_settings(): config.register('network', unicode) config.register('n', int) class CoordinationChatroom(dlgr.experiments.Experiment): """...
Use compat for unicode import
Use compat for unicode import
Python
mit
Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger
--- +++ @@ -1,11 +1,8 @@ """Coordination chatroom game.""" import dallinger as dlgr +from dallinger.compat import unicode from dallinger.config import get_config -try: - unicode = unicode -except NameError: # Python 3 - unicode = str config = get_config()
8033b00ebbcb8e294f47ee558e76ee260ec18d2b
orglog-config.py
orglog-config.py
org = "servo" ignore_repos = ["skia", "skia-snapshots", "cairo", "libpng", "libcss", "libhubbub", "libparserutils", "libwapcaplet", "pixman"] count_forks = ["glutin","rust-openssl"] # Path to where we'll dump the bare checkouts. Must end in / clones_dir = "repos/" # Path to the concatenated log log_...
org = "servo" ignore_repos = ["skia", "skia-snapshots", "cairo", "libpng", "libcss", "libhubbub", "libparserutils", "libwapcaplet", "pixman", "libfreetype2"] count_forks = ["glutin","rust-openssl"] # Path to where we'll dump the bare checkouts. Must end in / clones_dir = "repos/" # P...
Remove libfreetype2, which should have been omitted and was breaking the scripts
Remove libfreetype2, which should have been omitted and was breaking the scripts
Python
mit
servo/servo-org-stats,servo/servo-org-stats,servo/servo-org-stats
--- +++ @@ -1,7 +1,8 @@ org = "servo" ignore_repos = ["skia", "skia-snapshots", "cairo", "libpng", "libcss", - "libhubbub", "libparserutils", "libwapcaplet", "pixman"] + "libhubbub", "libparserutils", "libwapcaplet", "pixman", + "libfreetype2"] count_forks = ["glutin"...
1dfff48a5ddb910b4abbcf8e477b3dda9d606a49
scripts/maf_split_by_src.py
scripts/maf_split_by_src.py
#!/usr/bin/env python2.3 """ Read a MAF from stdin and break into a set of mafs containing no more than a certain number of columns """ usage = "usage: %prog" import sys, string import bx.align.maf from optparse import OptionParser import psyco_full INF="inf" def __main__(): # Parse command line arguments ...
#!/usr/bin/env python2.3 """ Read a MAF from stdin and break into a set of mafs containing no more than a certain number of columns """ usage = "usage: %prog" import sys, string import bx.align.maf from optparse import OptionParser import psyco_full INF="inf" def __main__(): # Parse command line arguments ...
Allow splitting by a particular component (by index)
Allow splitting by a particular component (by index)
Python
mit
bxlab/bx-python,bxlab/bx-python,bxlab/bx-python
--- +++ @@ -21,17 +21,24 @@ parser = OptionParser( usage=usage ) parser.add_option( "-o", "--outprefix", action="store", default="" ) + parser.add_option( "-c", "--component", action="store", default=None ) ( options, args ) = parser.parse_args() out_prefix = options.outprefix + comp = o...
ead9192b4c2acb21df917dfe116785343e9a59a6
scripts/patches/transfer.py
scripts/patches/transfer.py
patches = [ { "op": "move", "from": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/ItemType", "path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType", }, { "op": "replace", "path": "/ResourceTypes/AWS::Transfer::Server/Propert...
patches = [ { "op": "move", "from": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/ItemType", "path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType", }, { "op": "replace", "path": "/ResourceTypes/AWS::Transfer::Server/Propert...
Fix spec issue with Transfer::Server ProtocolDetails
Fix spec issue with Transfer::Server ProtocolDetails
Python
bsd-2-clause
cloudtools/troposphere,cloudtools/troposphere
--- +++ @@ -19,4 +19,14 @@ "path": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/PrimitiveItemType", "value": "String", }, + { + "op": "move", + "from": "/PropertyTypes/AWS::Transfer::Server.ProtocolDetails/Properties/As2Transports/ItemType", + "path": "/P...
4fe19797ba2fb12239ae73da60bb3e726b23ffe9
web/forms.py
web/forms.py
from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import UniqueEmailUser class UniqueEmailUserCreationForm(UserCreationForm): """ A form that creates a UniqueEmailUser. """ def __init__(self, *args, **kargs): super(UniqueEmailUserCreationForm, self).__init__...
from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import UniqueEmailUser class UniqueEmailUserCreationForm(UserCreationForm): """ A form that creates a UniqueEmailUser. """ class Meta: model = UniqueEmailUser fields = ("email",) class UniqueEmailUs...
Fix bug in admin user editing
Fix bug in admin user editing Fixes KeyError when creating or editing a UniqueEmailUser in the admin interface.
Python
mit
uppercounty/uppercounty,uppercounty/uppercounty,uppercounty/uppercounty
--- +++ @@ -7,10 +7,6 @@ """ A form that creates a UniqueEmailUser. """ - - def __init__(self, *args, **kargs): - super(UniqueEmailUserCreationForm, self).__init__(*args, **kargs) - del self.fields['username'] class Meta: model = UniqueEmailUser @@ -22,10 +18,6 @@ ...
89225ed0c7ec627ee32fd973d5f1fb95da173be2
djangae/contrib/locking/memcache.py
djangae/contrib/locking/memcache.py
import random import time from datetime import datetime from django.core.cache import cache class MemcacheLock(object): def __init__(self, identifier, cache, unique_value): self.identifier = identifier self._cache = cache self.unique_value = unique_value @classmethod def acquire(...
import random import time from datetime import datetime from django.core.cache import cache class MemcacheLock(object): def __init__(self, identifier, unique_value): self.identifier = identifier self.unique_value = unique_value @classmethod def acquire(cls, identifier, wait=True, steal_a...
Remove pointless `_cache` attribute on MemcacheLock class.
Remove pointless `_cache` attribute on MemcacheLock class. If this was doing anything useful, I have no idea what it was.
Python
bsd-3-clause
potatolondon/djangae,potatolondon/djangae
--- +++ @@ -6,9 +6,8 @@ class MemcacheLock(object): - def __init__(self, identifier, cache, unique_value): + def __init__(self, identifier, unique_value): self.identifier = identifier - self._cache = cache self.unique_value = unique_value @classmethod @@ -19,7 +18,7 @@ ...
a715821c75521e25172805c98d204fc4e24a4641
CodeFights/circleOfNumbers.py
CodeFights/circleOfNumbers.py
#!/usr/local/bin/python # Code Fights Circle of Numbers Problem def circleOfNumbers(n, firstNumber): pass def main(): tests = [ ["crazy", "dsbaz"], ["z", "a"] ] for t in tests: res = circleOfNumbers(t[0], t[1]) if t[2] == res: print("PASSED: circleOfNumbe...
#!/usr/local/bin/python # Code Fights Circle of Numbers Problem def circleOfNumbers(n, firstNumber): mid = n / 2 return (mid + firstNumber if firstNumber < mid else firstNumber - mid) def main(): tests = [ [10, 2, 7], [10, 7, 2], [4, 1, 3], [6, 3, 0] ] for t in t...
Solve Code Fights circle of numbers problem
Solve Code Fights circle of numbers problem
Python
mit
HKuz/Test_Code
--- +++ @@ -3,13 +3,16 @@ def circleOfNumbers(n, firstNumber): - pass + mid = n / 2 + return (mid + firstNumber if firstNumber < mid else firstNumber - mid) def main(): tests = [ - ["crazy", "dsbaz"], - ["z", "a"] + [10, 2, 7], + [10, 7, 2], + [4, 1, 3], + ...
9ac662557d6313190621c0c84a2c6923e0e9fa72
nodeconductor/logging/middleware.py
nodeconductor/logging/middleware.py
from __future__ import unicode_literals import threading _locals = threading.local() def get_event_context(): return getattr(_locals, 'context', None) def set_event_context(context): _locals.context = context def reset_event_context(): if hasattr(_locals, 'context'): del _locals.context de...
from __future__ import unicode_literals import threading _locals = threading.local() def get_event_context(): return getattr(_locals, 'context', None) def set_event_context(context): _locals.context = context def reset_event_context(): if hasattr(_locals, 'context'): del _locals.context de...
Update event context instead of replace (NC-529)
Update event context instead of replace (NC-529)
Python
mit
opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor
--- +++ @@ -19,7 +19,9 @@ def set_current_user(user): - set_event_context(user._get_log_context('user')) + context = get_event_context() or {} + context.update(user._get_log_context('user')) + set_event_context(context) def get_ip_address(request):
93a95afe231910d9f683909994692fadaf107057
readme_renderer/markdown.py
readme_renderer/markdown.py
# Copyright 2014 Donald Stufft # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
# Copyright 2014 Donald Stufft # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
Make md.render have the same API as rst.render
Make md.render have the same API as rst.render
Python
apache-2.0
pypa/readme,pypa/readme_renderer
--- +++ @@ -26,4 +26,7 @@ 'markdown.extensions.fenced_code', 'markdown.extensions.smart_strong', ]) - return clean(rendered or raw), bool(rendered) + if rendered: + return clean(rendered) + else: + return None
345ccc9d503e6e55fe46d7813958c0081cc1cffe
openstack_dashboard/views.py
openstack_dashboard/views.py
# Copyright 2012 Nebula, Inc. # # 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 agree...
# Copyright 2012 Nebula, Inc. # # 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 agree...
Fix issues with importing the Login form
Fix issues with importing the Login form The Login form lives in openstack_auth.forms and should be directly imported from that file. Change-Id: I42808530024bebb01604adbf4828769812856bf3 Closes-Bug: #1332149
Python
apache-2.0
Mirantis/mos-horizon,endorphinl/horizon,RudoCris/horizon,davidcusatis/horizon,Daniex/horizon,watonyweng/horizon,tqtran7/horizon,sandvine/horizon,openstack/horizon,mdavid/horizon,davidcusatis/horizon,maestro-hybrid-cloud/horizon,VaneCloud/horizon,CiscoSystems/avos,Dark-Hacker/horizon,luhanhan/horizon,RudoCris/horizon,fr...
--- +++ @@ -18,7 +18,7 @@ import horizon from horizon import base -from openstack_auth import views +from openstack_auth import forms def get_user_home(user): @@ -39,7 +39,7 @@ def splash(request): if request.user.is_authenticated(): return shortcuts.redirect(horizon.get_user_home(request.user...
2279aa0c450d53b04f774d9441e4fc0647466581
bottery/message.py
bottery/message.py
import os from datetime import datetime import attr from jinja2 import Environment, FileSystemLoader, select_autoescape @attr.s class Message: id = attr.ib() platform = attr.ib() user = attr.ib() text = attr.ib() timestamp = attr.ib() raw = attr.ib() @property def datetime(self): ...
import os from datetime import datetime import attr from jinja2 import Environment, FileSystemLoader, select_autoescape @attr.s class Message: id = attr.ib() platform = attr.ib() user = attr.ib() text = attr.ib() timestamp = attr.ib() raw = attr.ib() @property def datetime(self): ...
Send platform name to defaul template context
Send platform name to defaul template context
Python
mit
rougeth/bottery
--- +++ @@ -32,7 +32,8 @@ template = env.get_template(template_name) default_context = { - 'user': message.user + 'user': message.user, + 'platform': message.platform, } default_context.update(context) return template.render(**default_context)
22b697729d1ee43d322aa1187b3a5f6101f836a5
odin/__init__.py
odin/__init__.py
__authors__ = "Tim Savage" __author_email__ = "tim@savage.company" __copyright__ = "Copyright (C) 2014 Tim Savage" __version__ = "1.0" # Disable logging if an explicit handler is not added try: import logging logging.getLogger('odin').addHandler(logging.NullHandler()) except AttributeError: pass # Fallbac...
# Disable logging if an explicit handler is not added import logging logging.getLogger('odin.registration').addHandler(logging.NullHandler()) __authors__ = "Tim Savage" __author_email__ = "tim@savage.company" __copyright__ = "Copyright (C) 2014 Tim Savage" __version__ = "1.0" from odin.fields import * # noqa from od...
Remove Python 2.6 backwards compatibility
Remove Python 2.6 backwards compatibility
Python
bsd-3-clause
python-odin/odin
--- +++ @@ -1,14 +1,11 @@ +# Disable logging if an explicit handler is not added +import logging +logging.getLogger('odin.registration').addHandler(logging.NullHandler()) + __authors__ = "Tim Savage" __author_email__ = "tim@savage.company" __copyright__ = "Copyright (C) 2014 Tim Savage" __version__ = "1.0" - -# D...
59daf205869c42b3797aa9dbaaa97930cbca2417
nanshe_workflow/ipy.py
nanshe_workflow/ipy.py
__author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>" __date__ = "$Nov 10, 2015 17:09$" try: from IPython.utils.shimmodule import ShimWarning except ImportError: class ShimWarning(Warning): """Warning issued by IPython 4.x regarding deprecated API.""" pass import warnings with warnings.cat...
__author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>" __date__ = "$Nov 10, 2015 17:09$" import json import re try: from IPython.utils.shimmodule import ShimWarning except ImportError: class ShimWarning(Warning): """Warning issued by IPython 4.x regarding deprecated API.""" pass import warn...
Add function to check if nbserverproxy is running
Add function to check if nbserverproxy is running Provides a simple check to see if the `nbserverproxy` is installed and running. As this is a Jupyter server extension and this code is run from the notebook, we can't simply import `nbserverproxy`. In fact that wouldn't even work when using the Python 2 kernel even tho...
Python
apache-2.0
nanshe-org/nanshe_workflow,DudLab/nanshe_workflow
--- +++ @@ -1,6 +1,9 @@ __author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>" __date__ = "$Nov 10, 2015 17:09$" + +import json +import re try: from IPython.utils.shimmodule import ShimWarning @@ -24,3 +27,39 @@ from ipyparallel import Client from IPython.display import display + +import ipyk...
99d16198b5b61ba13a441a6546ccd1f7ce0b91bc
test/symbols/show_glyphs.py
test/symbols/show_glyphs.py
#!/usr/bin/env python # -*- coding: utf-8 -*- devicons_start = "e700" devicons_end = "e7c5" print "Devicons" for ii in xrange(int(devicons_start, 16), int(devicons_end, 16) + 1): print unichr(ii), custom_start = "e5fa" custom_end = "e62b" print "\nCustom" for ii in xrange(int(custom_start, 16), int(custom_end, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- devicons_start = "e700" devicons_end = "e7c5" print "Devicons" for ii in xrange(int(devicons_start, 16), int(devicons_end, 16) + 1): print unichr(ii), custom_start = "e5fa" custom_end = "e62b" print "\nCustom" for ii in xrange(int(custom_start, 16), int(custom_end, ...
Add octicons in font test script
Add octicons in font test script
Python
mit
mkofinas/prompt-support,mkofinas/prompt-support
--- +++ @@ -28,3 +28,10 @@ print "\nPowerline" for ii in xrange(int(powerline_start, 16), int(powerline_end, 16) + 1): print unichr(ii), + +octicons_start = "f400" +octicons_end = "f4e5" + +print "\nOcticons" +for ii in xrange(int(octicons_start, 16), int(octicons_end, 16) + 1): + print unichr(ii),
2daeee0b9fabb4f1ad709bdbe9c8c12a6281d32d
axis/__main__.py
axis/__main__.py
"""Read events and parameters from your Axis device.""" import asyncio import argparse import logging import sys from axis import AxisDevice async def main(args): loop = asyncio.get_event_loop() device = AxisDevice( loop=loop, host=args.host, username=args.username, password=args.password, p...
"""Read events and parameters from your Axis device.""" import asyncio import argparse import logging import sys from axis import AxisDevice async def main(args): loop = asyncio.get_event_loop() device = AxisDevice( loop=loop, host=args.host, username=args.username, password=args.password, p...
Fix main failing on no event_callback
Fix main failing on no event_callback
Python
mit
Kane610/axis
--- +++ @@ -23,6 +23,10 @@ return if args.events: + def event_handler(action, event): + print(action, event) + + device.enable_events(event_callback=event_handler) device.start() try:
c35e004ae3b2b9b8338673078f8ee523ac79e005
alg_shell_sort.py
alg_shell_sort.py
from __future__ import absolute_import from __future__ import print_function from __future__ import division def _gap_insertion_sort(a_list, start, gap): for i in range(start + gap, len(a_list), gap): current_value = a_list[i] position = i while (position >= gap) and (a_list[position - ga...
from __future__ import absolute_import from __future__ import print_function from __future__ import division def _gap_insertion_sort(a_list, start, gap): for i in range(start + gap, len(a_list), gap): current_value = a_list[i] position = i while (position >= gap) and (a_list[position - ga...
Revise print() in shell_sort() & main()
Revise print() in shell_sort() & main()
Python
bsd-2-clause
bowen0701/algorithms_data_structures
--- +++ @@ -22,7 +22,7 @@ for start_pos in range(sublist_count): _gap_insertion_sort(a_list, start_pos, sublist_count) - print('After increments of size {0}, a_list is \n{1}' + print('After increments of size {0}:\n{1}' .format(sublist_count, a_list)) ...
29061254e99f8e02e8285c3ebc965866c8c9d378
testing/chess_engine_fight.py
testing/chess_engine_fight.py
#!/usr/bin/python import subprocess, os, sys if len(sys.argv) < 2: print('Must specify file names of 2 chess engines') for i in range(len(sys.argv)): print(str(i) + ': ' + sys.argv[i]) sys.exit(1) generator = './' + sys.argv[-2] checker = './' + sys.argv[-1] game_file = 'game.pgn' count = 0 whil...
#!/usr/bin/python import subprocess, os, sys if len(sys.argv) < 2: print('Must specify file names of 2 chess engines') for i in range(len(sys.argv)): print(str(i) + ': ' + sys.argv[i]) sys.exit(1) generator = './' + sys.argv[-2] checker = './' + sys.argv[-1] game_file = 'game.pgn' count = 0 whil...
Check that engine fight files are deleted before test
Check that engine fight files are deleted before test
Python
mit
MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess
--- +++ @@ -19,6 +19,9 @@ except OSError: pass + if os.path.isfile(game_file): + print('Could not delete output file:', game_file) + count += 1 print('Game #' + str(count))
8c637c0f70908a00713014ef2d2ff72e3d5a81dc
prerequisites.py
prerequisites.py
#!/usr/bin/env python import sys # Check that we are in an activated virtual environment try: import os virtual_env = os.environ['VIRTUAL_ENV'] except KeyError: print("It doesn't look like you are in an activated virtual environment.") print("Did you make one?") print("Did you activate it?") ...
#!/usr/bin/env python import sys # Check that we are in an activated virtual environment try: import os virtual_env = os.environ['VIRTUAL_ENV'] except KeyError: print("It doesn't look like you are in an activated virtual environment.") print("Did you make one?") print("Did you activate it?") ...
Use django.get_version in prerequisite checker
Use django.get_version in prerequisite checker
Python
mit
mpirnat/django-tutorial-v2
--- +++ @@ -25,13 +25,14 @@ # Check that we have the expected version of Django -expected_version = (1, 7, 1) +expected_version = '1.7.1' +installed_version = django.get_version() try: - assert django.VERSION[:3] == expected_version + assert installed_version == expected_version except AssertionError: ...
2a724872cba5c48ddbd336f06460aa2ad851c6d0
Pilot3/P3B5/p3b5.py
Pilot3/P3B5/p3b5.py
import os import candle file_path = os.path.dirname(os.path.realpath(__file__)) lib_path2 = os.path.abspath(os.path.join(file_path, '..', '..', 'common')) sys.path.append(lib_path2) REQUIRED = [ 'learning_rate', 'learning_rate_min', 'momentum', 'weight_decay', 'grad_clip', 'seed', 'unro...
import os import sys import candle file_path = os.path.dirname(os.path.realpath(__file__)) lib_path2 = os.path.abspath(os.path.join(file_path, '..', '..', 'common')) sys.path.append(lib_path2) REQUIRED = [ 'learning_rate', 'learning_rate_min', 'momentum', 'weight_decay', 'grad_clip', 'seed'...
Fix missing import for sys
Fix missing import for sys
Python
mit
ECP-CANDLE/Benchmarks,ECP-CANDLE/Benchmarks,ECP-CANDLE/Benchmarks
--- +++ @@ -1,4 +1,5 @@ import os +import sys import candle
7729c90679a74f268d7b0fd88c954fb583830794
parser.py
parser.py
import webquery from lxml import etree import inspect from expression import Expression from collections import defaultdict class Parser(object): registry = defaultdict(dict) @classmethod def __init_subclass__(cls): for name, member in inspect.getmembers(cls): if isinstance(member, Ex...
import webquery from lxml import etree import inspect from expression import Expression from collections import defaultdict class Parser(object): registry = defaultdict(dict) @classmethod def __init_subclass__(cls): for name, member in inspect.getmembers(cls): if isinstance(member, Ex...
Add ability to customize URL
Add ability to customize URL
Python
apache-2.0
shiplu/webxpath
--- +++ @@ -19,9 +19,14 @@ cls = self.__class__ return cls.registry[cls.__name__] + def canonical_url(self, url): + """By overriding this method canonical url can be used""" + return url + def parse(self, url): - content = webquery.urlcontent(url) - root = etree...
b6813731696a03e04367ea3286092320391080e9
puresnmp/__init__.py
puresnmp/__init__.py
""" This module contains the high-level functions to access the library. Care is taken to make this as pythonic as possible and hide as many of the gory implementations as possible. """ from x690.types import ObjectIdentifier # !!! DO NOT REMOVE !!! The following import triggers the processing of SNMP # Types and th...
""" This module contains the high-level functions to access the library. Care is taken to make this as pythonic as possible and hide as many of the gory implementations as possible. """ from x690.types import ObjectIdentifier # !!! DO NOT REMOVE !!! The following import triggers the processing of SNMP # Types and th...
Fix false-positive of a type-check
Fix false-positive of a type-check
Python
mit
exhuma/puresnmp,exhuma/puresnmp
--- +++ @@ -21,7 +21,7 @@ import importlib_metadata # type: ignore -__version__ = importlib_metadata.version("puresnmp") +__version__ = importlib_metadata.version("puresnmp") # type: ignore __all__ = [ "Client",
bf5dd490cec02827d51c887506ce1f55d5012893
astropy/tests/image_tests.py
astropy/tests/image_tests.py
import matplotlib from matplotlib import pyplot as plt from astropy.utils.decorators import wraps MPL_VERSION = matplotlib.__version__ # The developer versions of the form 3.1.x+... contain changes that will only # be included in the 3.2.x release, so we update this here. if MPL_VERSION[:3] == '3.1' and '+' in MPL_V...
import matplotlib from matplotlib import pyplot as plt from astropy.utils.decorators import wraps MPL_VERSION = matplotlib.__version__ # The developer versions of the form 3.1.x+... contain changes that will only # be included in the 3.2.x release, so we update this here. if MPL_VERSION[:3] == '3.1' and '+' in MPL_V...
Update URL for baseline images
Update URL for baseline images
Python
bsd-3-clause
mhvk/astropy,StuartLittlefair/astropy,larrybradley/astropy,StuartLittlefair/astropy,pllim/astropy,astropy/astropy,aleksandr-bakanov/astropy,mhvk/astropy,saimn/astropy,dhomeier/astropy,StuartLittlefair/astropy,stargaser/astropy,dhomeier/astropy,stargaser/astropy,mhvk/astropy,StuartLittlefair/astropy,bsipocz/astropy,dhom...
--- +++ @@ -10,7 +10,7 @@ if MPL_VERSION[:3] == '3.1' and '+' in MPL_VERSION: MPL_VERSION = '3.2' -ROOT = "http://{server}/testing/astropy/2018-10-24T12:38:34.134556/{mpl_version}/" +ROOT = "http://{server}/testing/astropy/2019-08-02T11:38:58.288466/{mpl_version}/" IMAGE_REFERENCE_DIR = (ROOT.format(server='...
030e64d7aee6c3f0b3a0d0508ac1d5ece0bf4a40
astroquery/fermi/__init__.py
astroquery/fermi/__init__.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Access to Fermi Gamma-ray Space Telescope data. http://fermi.gsfc.nasa.gov http://fermi.gsfc.nasa.gov/ssc/data/ """ from astropy.config import ConfigurationItem FERMI_URL = ConfigurationItem('fermi_url', ['http://fermi.g...
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Access to Fermi Gamma-ray Space Telescope data. http://fermi.gsfc.nasa.gov http://fermi.gsfc.nasa.gov/ssc/data/ """ from astropy.config import ConfigurationItem FERMI_URL = ConfigurationItem('fermi_url', ['http://fermi.g...
Clean up namespace to get rid of sphinx warnings
Clean up namespace to get rid of sphinx warnings
Python
bsd-3-clause
imbasimba/astroquery,imbasimba/astroquery,ceb8/astroquery,ceb8/astroquery
--- +++ @@ -17,3 +17,5 @@ import warnings warnings.warn("Experimental: Fermi-LAT has not yet been refactored to have its API match the rest of astroquery.") + +del ConfigurationItem # clean up namespace - prevents doc warnings
3ae40027f42f6228489d2bbc5c2da53c7df8387a
babybuddy/settings/heroku.py
babybuddy/settings/heroku.py
import os import dj_database_url from .base import * # noqa: F401,F403 DEBUG = False # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ['SECRET_KEY'] # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': dj_database_ur...
import os import dj_database_url from .base import * # noqa: F401,F403 DEBUG = os.environ.get('DEBUG', False) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ['SECRET_KEY'] # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { ...
Add a DEBUG environment option to Heroku settings.
Add a DEBUG environment option to Heroku settings.
Python
bsd-2-clause
cdubz/babybuddy,cdubz/babybuddy,cdubz/babybuddy
--- +++ @@ -5,7 +5,7 @@ from .base import * # noqa: F401,F403 -DEBUG = False +DEBUG = os.environ.get('DEBUG', False) # SECURITY WARNING: keep the secret key used in production secret!
ef98ba0f2aa660b85a4116d46679bf30321f2a05
scipy/spatial/transform/__init__.py
scipy/spatial/transform/__init__.py
""" Spatial Transformations (:mod:`scipy.spatial.transform`) ======================================================== .. currentmodule:: scipy.spatial.transform This package implements various spatial transformations. For now, only rotations are supported. Rotations in 3 dimensions ------------------------- .. autos...
""" Spatial Transformations (:mod:`scipy.spatial.transform`) ======================================================== .. currentmodule:: scipy.spatial.transform This package implements various spatial transformations. For now, only rotations are supported. Rotations in 3 dimensions ------------------------- .. autos...
Add RotationSpline into __all__ of spatial.transform
MAINT: Add RotationSpline into __all__ of spatial.transform
Python
bsd-3-clause
grlee77/scipy,pizzathief/scipy,endolith/scipy,Eric89GXL/scipy,gertingold/scipy,aeklant/scipy,anntzer/scipy,tylerjereddy/scipy,ilayn/scipy,scipy/scipy,matthew-brett/scipy,jor-/scipy,endolith/scipy,ilayn/scipy,person142/scipy,Eric89GXL/scipy,nmayorov/scipy,lhilt/scipy,arokem/scipy,endolith/scipy,ilayn/scipy,WarrenWeckess...
--- +++ @@ -21,7 +21,7 @@ from .rotation import Rotation, Slerp from ._rotation_spline import RotationSpline -__all__ = ['Rotation', 'Slerp'] +__all__ = ['Rotation', 'Slerp', 'RotationSpline'] from scipy._lib._testutils import PytestTester test = PytestTester(__name__)
4c85300c5458053ac08a393b00513c80baf28031
reqon/deprecated/__init__.py
reqon/deprecated/__init__.py
import rethinkdb as r from . import coerce, geo, operators, terms from .coerce import COERSIONS from .operators import BOOLEAN, EXPRESSIONS, MODIFIERS from .terms import TERMS from .exceptions import ReqonError, InvalidTypeError, InvalidFilterError def query(query): try: reql = r.db(query['$db']).table(q...
import rethinkdb as r from . import coerce, geo, operators, terms from .coerce import COERSIONS from .operators import BOOLEAN, EXPRESSIONS, MODIFIERS from .terms import TERMS from .exceptions import ReqonError, InvalidTypeError, InvalidFilterError def query(query): try: reql = r.db(query['$db']).table(q...
Fix arguments order of reqon.deprecated.build_terms().
Fix arguments order of reqon.deprecated.build_terms().
Python
mit
dmpayton/reqon
--- +++ @@ -15,7 +15,7 @@ reql = r.table(query['$table']) except KeyError: raise ReqonError('The query descriptor requires a $table key.') - return build_terms(query['$query'], reql) + return build_terms(reql, query['$query']) def build_terms(reql, query):
b659db91c0f4230d1c8ed69dd0cd2697fb573b85
playerAction.py
playerAction.py
import mcpi.minecraft as minecraft import time mc = minecraft.Minecraft.create() while True: pos = mc.player.getPos() x = pos.x y = pos.y z = pos.z # Display position #print x, y, z time.sleep(2) if x >= 343.300 and y <= 344.700 and z <= -301.300 and z >= -302.700 and y == 4:...
import mcpi.minecraft as minecraft import time mc = minecraft.Minecraft.create() while True: pos = mc.player.getPos() x = pos.x y = pos.y z = pos.z # Display position #print x, y, z time.sleep(2) if x >= 343.300 and x <= 344.700 and z <= -301.300 and z >= -302.700 and y == 4:...
Update player position action script
Update player position action script
Python
mit
Nekrofage/MinecraftPython
--- +++ @@ -13,6 +13,6 @@ time.sleep(2) - if x >= 343.300 and y <= 344.700 and z <= -301.300 and z >= -302.700 and y == 4: + if x >= 343.300 and x <= 344.700 and z <= -301.300 and z >= -302.700 and y == 4: print "Active action" mc.postToChat("Active action")
a388280d56bb73e64dbea2244e210878d9371984
NagiosWrapper/NagiosWrapper.py
NagiosWrapper/NagiosWrapper.py
import subprocess nagiosPluginsCommandLines = [ "/usr/lib64/nagios/plugins/check_sensors", "/usr/lib64/nagios/plugins/check_mailq -w 10 -c 20 -M postfix", ] class NagiosWrapper: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = ch...
import subprocess nagiosPluginsCommandLines = [ "/usr/lib64/nagios/plugins/check_sensors", "/usr/lib64/nagios/plugins/check_mailq -w 10 -c 20 -M postfix", ] class NagiosWrapper: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = ch...
Add support for Python 2.6
Add support for Python 2.6
Python
bsd-3-clause
bastiendonjon/sd-agent-plugins,shanethehat/sd-agent-plugins,bencer/sd-agent-plugins,shanethehat/sd-agent-plugins,bencer/sd-agent-plugins,bastiendonjon/sd-agent-plugins
--- +++ @@ -29,11 +29,12 @@ ) out, err = p.communicate() - self.checksLogger.debug('Output of {}: {}'.format(pluginCommand, out)) + self.checksLogger.debug('Output of {0}: {1}'.format(pluginCommand, out)) if err: - self.checksLogger.error...
05715aca84152c78cf0b4d5d7b751ecfa3a9f35a
tinyblog/views/__init__.py
tinyblog/views/__init__.py
from datetime import datetime from django.http import Http404 from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.views.generic import ( ArchiveIndexView, YearArchiveView, MonthArchiveView, ) from tinyblog.models import Post def post(re...
from datetime import datetime from django.http import Http404 from django.shortcuts import get_object_or_404 from django.views.generic import ( ArchiveIndexView, YearArchiveView, MonthArchiveView, DetailView, ) from tinyblog.models import Post class TinyBlogPostView(DetailView): template_name = 't...
Switch the main post detail view to a CBV
Switch the main post detail view to a CBV
Python
bsd-3-clause
dominicrodger/tinyblog,dominicrodger/tinyblog
--- +++ @@ -1,26 +1,31 @@ from datetime import datetime from django.http import Http404 -from django.shortcuts import render_to_response, get_object_or_404 -from django.template import RequestContext +from django.shortcuts import get_object_or_404 from django.views.generic import ( ArchiveIndexView, Year...
fcf626b6cb898bba294f8f4e2ecd2ff57cd144a0
scripts/syscalls.py
scripts/syscalls.py
import sim, syscall_strings, platform if platform.architecture()[0] == '64bit': __syscall_strings = syscall_strings.syscall_strings_64 else: __syscall_strings = syscall_strings.syscall_strings_32 def syscall_name(syscall_number): return '%s[%d]' % (__syscall_strings.get(syscall_number, 'unknown'), syscall_numbe...
import sim, syscall_strings, sys if sys.maxsize == 2**31-1: __syscall_strings = syscall_strings.syscall_strings_32 else: __syscall_strings = syscall_strings.syscall_strings_64 def syscall_name(syscall_number): return '%s[%d]' % (__syscall_strings.get(syscall_number, 'unknown'), syscall_number) class LogSyscall...
Use different way to determine 32/64-bit which returns mode of current binary, not of the system
[scripts] Use different way to determine 32/64-bit which returns mode of current binary, not of the system
Python
mit
abanaiyan/sniper,abanaiyan/sniper,abanaiyan/sniper,abanaiyan/sniper,abanaiyan/sniper
--- +++ @@ -1,9 +1,9 @@ -import sim, syscall_strings, platform +import sim, syscall_strings, sys -if platform.architecture()[0] == '64bit': +if sys.maxsize == 2**31-1: + __syscall_strings = syscall_strings.syscall_strings_32 +else: __syscall_strings = syscall_strings.syscall_strings_64 -else: - __syscall_strin...
4d641110454f114d1f179d306fb63166e66fd6cf
src/foremast/slacknotify/slack_notification.py
src/foremast/slacknotify/slack_notification.py
"""Notify Slack channel.""" import time from ..utils import get_properties, get_template, post_slack_message class SlackNotification: """Post slack notification. Inform users about infrastructure changes to prod* accounts. """ def __init__(self, app=None, env=None, prop_path=None): self.inf...
"""Notify Slack channel.""" import time from ..utils import get_properties, get_template, post_slack_message class SlackNotification: """Post slack notification. Inform users about infrastructure changes to prod* accounts. """ def __init__(self, app=None, env=None, prop_path=None): timestam...
Move timestamp before dict for insertion
fix: Move timestamp before dict for insertion
Python
apache-2.0
gogoair/foremast,gogoair/foremast
--- +++ @@ -11,9 +11,13 @@ """ def __init__(self, app=None, env=None, prop_path=None): - self.info = {'app': app, 'env': env, 'properties': prop_path} timestamp = time.strftime("%B %d, %Y %H:%M:%S %Z", time.gmtime()) - self.info['timestamp'] = timestamp + + self.info = {'app'...
7e11e57ee4f9fc1dc3c967c9b2d26038a7727f72
wqflask/wqflask/database.py
wqflask/wqflask/database.py
# Module to initialize sqlalchemy with flask import os import sys from string import Template from typing import Tuple from urllib.parse import urlparse import importlib import MySQLdb from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import d...
# Module to initialize sqlalchemy with flask import os import sys from string import Template from typing import Tuple from urllib.parse import urlparse import importlib import MySQLdb def sql_uri(): """Read the SQL_URI from the environment or settings file.""" return os.environ.get( "SQL_URI", read_...
Delete unused function and imports.
Delete unused function and imports. * wqflask/wqflask/database.py: Remove unused sqlalchemy imports. (read_from_pyfile): Delete it.
Python
agpl-3.0
genenetwork/genenetwork2,genenetwork/genenetwork2,genenetwork/genenetwork2,genenetwork/genenetwork2
--- +++ @@ -8,16 +8,6 @@ import MySQLdb -from sqlalchemy import create_engine -from sqlalchemy.orm import scoped_session, sessionmaker -from sqlalchemy.ext.declarative import declarative_base - -def read_from_pyfile(pyfile, setting): - orig_sys_path = sys.path[:] - sys.path.insert(0, os.path.dirname(pyfile...
bdcca9f505c185fa0ade4e93a88b8dabc85f9176
pysearch/urls.py
pysearch/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'pysearch.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^search/', inclu...
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'pysearch.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^search/', include('search.urls')), )
Remove access to admin site
Remove access to admin site
Python
mit
nh0815/PySearch,nh0815/PySearch
--- +++ @@ -7,7 +7,5 @@ # Examples: # url(r'^$', 'pysearch.views.home', name='home'), # url(r'^blog/', include('blog.urls')), - - url(r'^admin/', include(admin.site.urls)), url(r'^search/', include('search.urls')), )
5c787be025ca99da339aae221b714bd1d8f2d0bd
route/station.py
route/station.py
from flask import request from flask.ext import restful from route.base import api from model.base import db from model.user import User import logging class StationAPI(restful.Resource): def post(self): data = request.get_json() station = Station(data['name'], data['address'], data['address2'], data['...
from flask import request from flask.ext import restful from route.base import api from model.base import db from model.user import User import logging class StationAPI(restful.Resource): def post(self): data = request.get_json() station = Station(data['name'], data['address'], data['address2'], data['...
Add start of get funtion
Add start of get funtion
Python
mit
hexa4313/velov-companion-server,hexa4313/velov-companion-server
--- +++ @@ -15,4 +15,7 @@ db.session.commit() return Station.query.first() + def get(self, station_id): + data = request.get + api.add_resource(StationAPI, "/station")
d64e85f96483e6b212adca38ca5fa89c64508701
froide_campaign/listeners.py
froide_campaign/listeners.py
from .models import Campaign, InformationObject def connect_info_object(sender, **kwargs): reference = kwargs.get('reference') if reference is None: return if 'campaign' not in reference: return try: campaign, slug = reference['campaign'].split('@', 1) except (ValueError, I...
from .models import Campaign, InformationObject def connect_info_object(sender, **kwargs): reference = kwargs.get('reference') if not reference: return if not reference.startswith('campaign:'): return namespace, campaign_value = reference.split(':', 1) try: campaign, slug =...
Adjust to new reference handling
Adjust to new reference handling
Python
mit
okfde/froide-campaign,okfde/froide-campaign,okfde/froide-campaign
--- +++ @@ -3,12 +3,13 @@ def connect_info_object(sender, **kwargs): reference = kwargs.get('reference') - if reference is None: + if not reference: return - if 'campaign' not in reference: + if not reference.startswith('campaign:'): return + namespace, campaign_value = refere...
b5fa4f9eb11575ddd8838bc53817854de831337f
dumpling/views.py
dumpling/views.py
from django.conf import settings from django.shortcuts import get_object_or_404 from django.views.generic import DetailView from .models import Page class PageView(DetailView): context_object_name = 'page' def get_queryset(self): return Page.objects.published().prefetch_related('pagewidget__widget')...
from django.conf import settings from django.shortcuts import get_object_or_404, render from django.views.generic import DetailView from .models import Page class PageView(DetailView): context_object_name = 'page' def get_queryset(self): return Page.objects.published().prefetch_related('pagewidget_s...
Fix prefetch. Add styles view
Fix prefetch. Add styles view
Python
mit
funkybob/dumpling,funkybob/dumpling
--- +++ @@ -1,5 +1,5 @@ from django.conf import settings -from django.shortcuts import get_object_or_404 +from django.shortcuts import get_object_or_404, render from django.views.generic import DetailView from .models import Page @@ -9,7 +9,7 @@ context_object_name = 'page' def get_queryset(self): - ...
5cf66e26259f5b4c78e61530822fa19dfc117206
settings_test.py
settings_test.py
INSTALLED_APPS = ( 'oauth_tokens', 'taggit', 'vkontakte_groups', ) OAUTH_TOKENS_VKONTAKTE_CLIENT_ID = 3430034 OAUTH_TOKENS_VKONTAKTE_CLIENT_SECRET = 'b0FwzyKtO8QiQmgWQMTz' OAUTH_TOKENS_VKONTAKTE_SCOPE = ['ads,wall,photos,friends,stats'] OAUTH_TOKENS_VKONTAKTE_USERNAME = '+919665223715' OAUTH_TOKENS_VKONTAK...
INSTALLED_APPS = ( 'oauth_tokens', 'taggit', 'vkontakte_groups', ) OAUTH_TOKENS_VKONTAKTE_CLIENT_ID = 3430034 OAUTH_TOKENS_VKONTAKTE_CLIENT_SECRET = 'b0FwzyKtO8QiQmgWQMTz' OAUTH_TOKENS_VKONTAKTE_SCOPE = ['ads,wall,photos,friends,stats'] OAUTH_TOKENS_VKONTAKTE_USERNAME = '+919665223715' OAUTH_TOKENS_VKONTAK...
Fix RuntimeError: maximum recursion depth
Fix RuntimeError: maximum recursion depth
Python
bsd-3-clause
ramusus/django-vkontakte-groups-statistic,ramusus/django-vkontakte-groups-statistic,ramusus/django-vkontakte-groups-statistic
--- +++ @@ -10,3 +10,6 @@ OAUTH_TOKENS_VKONTAKTE_USERNAME = '+919665223715' OAUTH_TOKENS_VKONTAKTE_PASSWORD = 'githubovich' OAUTH_TOKENS_VKONTAKTE_PHONE_END = '96652237' + +# Set VK API Timeout +VKONTAKTE_API_REQUEST_TIMEOUT = 7
a81fbdd334dc475554e77bbb71ae00985f2d23c4
eventlog/stats.py
eventlog/stats.py
from datetime import datetime, timedelta from django.contrib.auth.models import User def stats(): return { "used_site_last_thirty_days": User.objects.filter(log__timestamp__gt=datetime.now() - timedelta(days=30)).distinct().count(), "used_site_last_seven_days": User.objects.filter(log__timestamp_...
from datetime import datetime, timedelta from django.contrib.auth.models import User def used_active(days): used = User.objects.filter( log__timestamp__gt=datetime.now() - timedelta(days=days) ).distinct().count() active = User.objects.filter( log__timestamp__gt=datetime.now() - time...
Add active_seven and active_thirty users
Add active_seven and active_thirty users
Python
bsd-3-clause
ConsumerAffairs/django-eventlog-ca,rosscdh/pinax-eventlog,KleeTaurus/pinax-eventlog,jawed123/pinax-eventlog,pinax/pinax-eventlog
--- +++ @@ -3,8 +3,27 @@ from django.contrib.auth.models import User +def used_active(days): + used = User.objects.filter( + log__timestamp__gt=datetime.now() - timedelta(days=days) + ).distinct().count() + + active = User.objects.filter( + log__timestamp__gt=datetime.now() - timedelta...
850803d02868e20bc637f777ee201ac778c63606
lms/djangoapps/edraak_misc/utils.py
lms/djangoapps/edraak_misc/utils.py
from courseware.access import has_access from django.conf import settings def is_certificate_allowed(user, course): return (course.has_ended() and settings.FEATURES.get('ENABLE_ISSUE_CERTIFICATE') or has_access(user, 'staff', course.id))
from courseware.access import has_access from django.conf import settings def is_certificate_allowed(user, course): if not settings.FEATURES.get('ENABLE_ISSUE_CERTIFICATE'): return False return course.has_ended() or has_access(user, 'staff', course.id)
Disable certificate for all if ENABLE_ISSUE_CERTIFICATE == False
Disable certificate for all if ENABLE_ISSUE_CERTIFICATE == False
Python
agpl-3.0
Edraak/edx-platform,Edraak/edx-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform,Edraak/edx-platform,Edraak/edx-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform,Edraak/edx-platform
--- +++ @@ -3,6 +3,7 @@ def is_certificate_allowed(user, course): - return (course.has_ended() - and settings.FEATURES.get('ENABLE_ISSUE_CERTIFICATE') - or has_access(user, 'staff', course.id)) + if not settings.FEATURES.get('ENABLE_ISSUE_CERTIFICATE'): + return False + + re...
b3a144e9dfba915d186fd1243515172780611689
models/waifu_model.py
models/waifu_model.py
from models.base_model import BaseModel from datetime import datetime from models.user_model import UserModel from peewee import CharField, TextField, DateTimeField, IntegerField, ForeignKeyField WAIFU_SHARING_STATUS_PRIVATE = 1 WAIFU_SHARING_STATUS_PUBLIC_MODERATION = 2 WAIFU_SHARING_STATUS_PUBLIC = 3 class WaifuMo...
from models.base_model import BaseModel from datetime import datetime from models.user_model import UserModel from peewee import CharField, TextField, DateTimeField, IntegerField, ForeignKeyField WAIFU_SHARING_STATUS_PRIVATE = 1 WAIFU_SHARING_STATUS_PUBLIC_MODERATION = 2 WAIFU_SHARING_STATUS_PUBLIC = 3 class WaifuMo...
Add users count to json representation.
Add users count to json representation.
Python
cc0-1.0
sketchturnerr/WaifuSim-backend,sketchturnerr/WaifuSim-backend
--- +++ @@ -20,3 +20,8 @@ rating = IntegerField(null=False, default=0) sharing_status = IntegerField(null=False, default=WAIFU_SHARING_STATUS_PRIVATE) owner = ForeignKeyField(UserModel, related_name='waifus_created_by_me') + + def to_json(self): + json = super(WaifuModel, self).to_json() + ...
0474872ea9db994928fa6848b89b847b4fc80986
smst/__init__.py
smst/__init__.py
__version__ = '0.2.0'
# _ _ # ___ _ __ ___ ___ | |_ ___ ___ | |___ # / __| '_ ` _ \/ __| | __/ _ \ / _ \| / __| # \__ \ | | | | \__ \ | || (_) | (_) | \__ \ # |___/_| |_| |_|___/ \__\___/ \___/|_|___/ # # ~ Spectral Modeling Synthesis Tools ~ # __version__ = '0.2.0'
Add a nice banner made using the figlet tool.
Add a nice banner made using the figlet tool.
Python
agpl-3.0
bzamecnik/sms-tools,bzamecnik/sms-tools,bzamecnik/sms-tools
--- +++ @@ -1 +1,10 @@ +# _ _ +# ___ _ __ ___ ___ | |_ ___ ___ | |___ +# / __| '_ ` _ \/ __| | __/ _ \ / _ \| / __| +# \__ \ | | | | \__ \ | || (_) | (_) | \__ \ +# |___/_| |_| |_|___/ \__\___/ \___/|_|___/ +# +# ~ Spectral Modeling Synthesis Tools ~ +# + __versio...
f6841a527bd8b52aa88c4c3b5980a0001387f33e
scoring/models/regressors.py
scoring/models/regressors.py
from sklearn.ensemble import RandomForestRegressor as randomforest from sklearn.svm import SVR as svm from sklearn.pls import PLSRegression as pls from .neuralnetwork import neuralnetwork __all__ = ['randomforest', 'svm', 'pls', 'neuralnetwork']
from sklearn.ensemble import RandomForestRegressor from sklearn.svm import SVR from sklearn.pls import PLSRegression from .neuralnetwork import neuralnetwork __all__ = ['randomforest', 'svm', 'pls', 'neuralnetwork'] class randomforest(RandomForestRegressor): pass class svm(SVR): pass class svm(PLSRegressio...
Make models inherit from sklearn
Make models inherit from sklearn
Python
bsd-3-clause
mwojcikowski/opendrugdiscovery
--- +++ @@ -1,7 +1,16 @@ -from sklearn.ensemble import RandomForestRegressor as randomforest -from sklearn.svm import SVR as svm -from sklearn.pls import PLSRegression as pls +from sklearn.ensemble import RandomForestRegressor +from sklearn.svm import SVR +from sklearn.pls import PLSRegression from .neuralnetwork ...
5b4c9cebd31e81f775d996ec9168b72d07142caa
follower/pid.py
follower/pid.py
import sys from time import time class PID(object): def __init__(self): """initizes value for the PID""" self.kd = 0 self.ki = 0 self.kp = 1 self.previous_error = 0 self.integral_error = 0 def set_k_values(self, kp, kd, ki): self.kp = kp self...
import sys from time import time class PID(object): def __init__(self): """initizes value for the PID""" self.kd = 0 self.ki = 0 self.kp = 1 self.previous_error = 0 self.integral_error = 0 def set_k_values(self, kp, kd, ki): self.kp = kp self...
Update to follower, reduce speed to motors.
Update to follower, reduce speed to motors.
Python
bsd-2-clause
deepakiam/bot,IEEERobotics/bot,IEEERobotics/bot,IEEERobotics/bot,deepakiam/bot,deepakiam/bot
--- +++ @@ -20,7 +20,7 @@ self.kd = kd def pid(self, target, process_var, timestep): - current_error = (target - process_var) + current_error = (target + process_var) p_error = self.kp * current_error d_error = self.kd * (current_error - self.previous_error) \ ...
740cc8b601eb2cd24bcabef59db9a38d2efde70f
netbox/dcim/fields.py
netbox/dcim/fields.py
from django.core.exceptions import ValidationError from django.core.validators import MinValueValidator, MaxValueValidator from django.db import models from netaddr import AddrFormatError, EUI, mac_unix_expanded class ASNField(models.BigIntegerField): description = "32-bit ASN field" default_validators = [ ...
from django.core.exceptions import ValidationError from django.core.validators import MinValueValidator, MaxValueValidator from django.db import models from netaddr import AddrFormatError, EUI, mac_unix_expanded class ASNField(models.BigIntegerField): description = "32-bit ASN field" default_validators = [ ...
Remove deprecated context parameter from from_db_value
Remove deprecated context parameter from from_db_value
Python
apache-2.0
digitalocean/netbox,digitalocean/netbox,digitalocean/netbox,digitalocean/netbox
--- +++ @@ -22,7 +22,7 @@ def python_type(self): return EUI - def from_db_value(self, value, expression, connection, context): + def from_db_value(self, value, expression, connection): return self.to_python(value) def to_python(self, value):
0855f9b5a9d36817139e61937419553f6ad21f78
symposion/proposals/urls.py
symposion/proposals/urls.py
from django.conf.urls.defaults import * urlpatterns = patterns("symposion.proposals.views", url(r"^submit/$", "proposal_submit", name="proposal_submit"), url(r"^submit/(\w+)/$", "proposal_submit_kind", name="proposal_submit_kind"), url(r"^(\d+)/$", "proposal_detail", name="proposal_detail"), url(r"^(\...
from django.conf.urls import patterns, url urlpatterns = patterns("symposion.proposals.views", url(r"^submit/$", "proposal_submit", name="proposal_submit"), url(r"^submit/([\w-]+)/$", "proposal_submit_kind", name="proposal_submit_kind"), url(r"^(\d+)/$", "proposal_detail", name="proposal_detail"), url...
Allow dashes in proposal kind slugs
Allow dashes in proposal kind slugs We can see from the setting PROPOSAL_FORMS that at least one proposal kind, Sponsor Tutorial, has a slug with a dash in it: sponsor-tutorial. Yet the URL pattern for submitting a proposal doesn't accept dashes in the slug. Fix it.
Python
bsd-3-clause
njl/pycon,pyconjp/pyconjp-website,njl/pycon,Diwahars/pycon,smellman/sotmjp-website,pyconjp/pyconjp-website,pyconjp/pyconjp-website,PyCon/pycon,osmfj/sotmjp-website,njl/pycon,Diwahars/pycon,PyCon/pycon,pyconjp/pyconjp-website,osmfj/sotmjp-website,osmfj/sotmjp-website,PyCon/pycon,osmfj/sotmjp-website,smellman/sotmjp-webs...
--- +++ @@ -1,9 +1,9 @@ -from django.conf.urls.defaults import * +from django.conf.urls import patterns, url urlpatterns = patterns("symposion.proposals.views", url(r"^submit/$", "proposal_submit", name="proposal_submit"), - url(r"^submit/(\w+)/$", "proposal_submit_kind", name="proposal_submit_kind"), + ...
da9c0743657ecc890c2a8503ea4bbb681ae00178
tests/chainer_tests/functions_tests/math_tests/test_arctanh.py
tests/chainer_tests/functions_tests/math_tests/test_arctanh.py
import unittest from chainer import testing import chainer.functions as F import numpy def make_data(shape, dtype): # Input values close to -1 or 1 would make tests unstable x = numpy.random.uniform(-0.9, 0.9, shape).astype(dtype, copy=False) gy = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=Fal...
import unittest from chainer import testing import chainer.functions as F import numpy def make_data(shape, dtype): # Input values close to -1 or 1 would make tests unstable x = numpy.random.uniform(-0.9, 0.9, shape).astype(dtype, copy=False) gy = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=Fal...
Call testing.run_module at the end of the test
Call testing.run_module at the end of the test
Python
mit
okuta/chainer,keisuke-umezawa/chainer,wkentaro/chainer,wkentaro/chainer,okuta/chainer,chainer/chainer,niboshi/chainer,okuta/chainer,pfnet/chainer,chainer/chainer,tkerola/chainer,chainer/chainer,niboshi/chainer,keisuke-umezawa/chainer,okuta/chainer,wkentaro/chainer,hvy/chainer,wkentaro/chainer,niboshi/chainer,niboshi/ch...
--- +++ @@ -16,3 +16,6 @@ @testing.unary_math_function_unittest(F.arctanh, make_data=make_data) class TestArctanh(unittest.TestCase): pass + + +testing.run_module(__name__, __file__)
584891ce58c3e979a5d6871ba7a6ff0a9e01d780
routes/student_vote.py
routes/student_vote.py
from aiohttp import web from db_helper import get_project_id, get_most_recent_group, get_user_id from permissions import view_only, value_set @view_only("join_projects") @value_set("student_choosable") async def on_submit(request): session = request.app["session"] cookies = request.cookies post = await r...
from aiohttp import web from db_helper import get_project_id, get_user_id, can_choose_project from permissions import view_only, value_set @view_only("join_projects") @value_set("student_choosable") async def on_submit(request): session = request.app["session"] cookies = request.cookies post = await requ...
Check if student can choose a project before allowing them to join it
Check if student can choose a project before allowing them to join it
Python
agpl-3.0
wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp
--- +++ @@ -1,6 +1,6 @@ from aiohttp import web -from db_helper import get_project_id, get_most_recent_group, get_user_id +from db_helper import get_project_id, get_user_id, can_choose_project from permissions import view_only, value_set @@ -13,8 +13,8 @@ option = int(post["order"]) - 1 attrs = ["fi...
92ab5c0878ba528fb49a42fde64dd4d6474bc1e8
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.password = p...
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...
Update order of patient attributes in model.
Update order of patient attributes in model.
Python
mit
jawrainey/atc,jawrainey/atc
--- +++ @@ -18,18 +18,16 @@ class Patient(db.Model): __tablename__ = 'patients' - # Used to determine which nurse triaged a patient. - # clientname = db.Column(db.String(64), db.ForeignKey('users.username')) - mobile = db.Column(db.Integer, unique=True, primary_key=True) forename = db.Column(db....
eefff91804317f4fb2c518446ab8e2072af4d87f
app/models.py
app/models.py
from django.db import models import mongoengine from mongoengine import Document, EmbeddedDocument from mongoengine.fields import * # Create your models here. class Greeting(models.Model): when = models.DateTimeField('date created', auto_now_add=True) MONGODB_URI = 'mongodb+srv://fikaadmin:ZJ6TtyTZMXA@fikanoted...
from django.db import models import mongoengine from mongoengine import Document, EmbeddedDocument from mongoengine.fields import * import os # Create your models here. class Greeting(models.Model): when = models.DateTimeField('date created', auto_now_add=True) USER = os.getenv('DATABASE_USER') PASWORD = os.gete...
Remove username and password from repository
Remove username and password from repository
Python
mit
gmkou/FikaNote,gmkou/FikaNote,gmkou/FikaNote
--- +++ @@ -3,13 +3,16 @@ from mongoengine import Document, EmbeddedDocument from mongoengine.fields import * +import os # Create your models here. class Greeting(models.Model): when = models.DateTimeField('date created', auto_now_add=True) +USER = os.getenv('DATABASE_USER') +PASWORD = os.getenv('DATAB...
556cef75198e3a5a8ac3e8f523c54b0b2df6a2c1
mousestyles/data/tests/test_data.py
mousestyles/data/tests/test_data.py
"""Standard test data. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import numpy as np from numpy.testing import assert_equal import mousestyles.data as data def test_all_features_mousedays_11bins(): all_features = data.all_feature_data() ...
"""Standard test data. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import numpy as np from numpy.testing import assert_equal import mousestyles.data as data def test_all_features_loader(): all_features = data.load_all_features() assert_eq...
Test for new data loader
TST: Test for new data loader Just a start, should probably add a more detailed test later.
Python
bsd-2-clause
berkeley-stat222/mousestyles,togawa28/mousestyles,changsiyao/mousestyles
--- +++ @@ -10,8 +10,8 @@ import mousestyles.data as data -def test_all_features_mousedays_11bins(): - all_features = data.all_feature_data() - print(all_features.shape) +def test_all_features_loader(): + all_features = data.load_all_features() + assert_equal(all_features.shape, (21131, 13))
1e10fa30998f63359ddd26d9804bd32a837c2cab
armstrong/esi/tests/_utils.py
armstrong/esi/tests/_utils.py
from django.conf import settings from django.test import TestCase as DjangoTestCase import fudge class TestCase(DjangoTestCase): def setUp(self): self._original_settings = settings def tearDown(self): settings = self._original_settings
from django.conf import settings from django.http import HttpRequest from django.test import TestCase as DjangoTestCase import fudge def with_fake_request(func): def inner(self, *args, **kwargs): request = fudge.Fake(HttpRequest) fudge.clear_calls() result = func(self, request, *args, **kw...
Add in a decorator for generating fake request objects for test cases
Add in a decorator for generating fake request objects for test cases
Python
bsd-3-clause
armstrong/armstrong.esi
--- +++ @@ -1,6 +1,19 @@ from django.conf import settings +from django.http import HttpRequest from django.test import TestCase as DjangoTestCase import fudge + +def with_fake_request(func): + def inner(self, *args, **kwargs): + request = fudge.Fake(HttpRequest) + fudge.clear_calls() + + re...
c8896c3eceb6ef7ffc6eef16af849597a8f7b8e2
Lib/test/test_sunaudiodev.py
Lib/test/test_sunaudiodev.py
from test_support import verbose, TestFailed import sunaudiodev import os def findfile(file): if os.path.isabs(file): return file import sys for dn in sys.path: fn = os.path.join(dn, file) if os.path.exists(fn): return fn return file def play_sound_file(path): fp = open(path, 'r') data = fp.read() ...
from test_support import verbose, TestFailed import sunaudiodev import os def findfile(file): if os.path.isabs(file): return file import sys path = sys.path try: path = [os.path.dirname(__file__)] + path except NameError: pass for dn in path: fn = os.path.join(dn, file) if os.path.exists(fn): return fn ...
Make this test work when imported from the interpreter instead of run from regrtest.py (it still works there too, of course).
Make this test work when imported from the interpreter instead of run from regrtest.py (it still works there too, of course).
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
--- +++ @@ -5,7 +5,12 @@ def findfile(file): if os.path.isabs(file): return file import sys - for dn in sys.path: + path = sys.path + try: + path = [os.path.dirname(__file__)] + path + except NameError: + pass + for dn in path: fn = os.path.join(dn, file) if os.path.exists(fn): return fn return file
675e0a29f780d6053d942dce4f80c6d934f3785a
Python/tigre/utilities/Ax.py
Python/tigre/utilities/Ax.py
from _Ax import _Ax_ext import numpy as np import copy def Ax(img, geo, angles, projection_type="Siddon"): if img.dtype != np.float32: raise TypeError("Input data should be float32, not "+ str(img.dtype)) if not np.isreal(img).all(): raise ValueError("Complex types not compatible for ...
from _Ax import _Ax_ext import numpy as np import copy def Ax(img, geo, angles, projection_type="Siddon"): if img.dtype != np.float32: raise TypeError("Input data should be float32, not "+ str(img.dtype)) if not np.isreal(img).all(): raise ValueError("Complex types not compatible for ...
Check the shape of input data earlier
Check the shape of input data earlier Using geo.nVoxel to check the input img shape earlier, before geo is casted to float32 (geox). We should use any() instead of all(), since "!=" is used?
Python
bsd-3-clause
CERN/TIGRE,CERN/TIGRE,CERN/TIGRE,CERN/TIGRE
--- +++ @@ -8,6 +8,9 @@ raise TypeError("Input data should be float32, not "+ str(img.dtype)) if not np.isreal(img).all(): raise ValueError("Complex types not compatible for projection.") + if any(img.shape != geo.nVoxel): + raise ValueError("Input data should be of shape geo.nVoxel: ...
08d6c4414d72b5431d5a50013058f325f38d7b1c
txdbus/test/test_message.py
txdbus/test/test_message.py
import os import unittest from txdbus import error, message class MessageTester(unittest.TestCase): def test_too_long(self): class E(message.ErrorMessage): _maxMsgLen = 1 def c(): E('foo.bar', 5) self.assertRaises(error.MarshallingError, c) def test_r...
import os import unittest from txdbus import error, message class MessageTester(unittest.TestCase): def test_too_long(self): class E(message.ErrorMessage): _maxMsgLen = 1 def c(): E('foo.bar', 5) self.assertRaises(error.MarshallingError, c) def test_r...
Fix message tests after in message.parseMessage args three commits ago
Fix message tests after in message.parseMessage args three commits ago (three commits ago is 08a6c170daa79e74ba538c928e183f441a0fb441)
Python
mit
cocagne/txdbus
--- +++ @@ -22,7 +22,7 @@ class E(message.ErrorMessage): _messageType=99 try: - message.parseMessage(E('foo.bar', 5).rawMessage) + message.parseMessage(E('foo.bar', 5).rawMessage, oobFDs=[]) self.assertTrue(False) except Exception as e: ...
84c2c987151451180281f1aecb0483321462340c
influxalchemy/__init__.py
influxalchemy/__init__.py
""" InfluxDB Alchemy. """ from .client import InfluxAlchemy from .measurement import Measurement __version__ = "0.1.0"
""" InfluxDB Alchemy. """ import pkg_resources from .client import InfluxAlchemy from .measurement import Measurement try: __version__ = pkg_resources.get_distribution(__package__).version except pkg_resources.DistributionNotFound: # pragma: no cover __version__ = None # pragma: no cove...
Use package version for __version__
Use package version for __version__
Python
mit
amancevice/influxalchemy
--- +++ @@ -1,6 +1,11 @@ """ InfluxDB Alchemy. """ +import pkg_resources from .client import InfluxAlchemy from .measurement import Measurement -__version__ = "0.1.0" + +try: + __version__ = pkg_resources.get_distribution(__package__).version +except pkg_resources.DistributionNotFound: # pragma: no cover +...
fc6e3c276ee638fbb4409fa00d470817205f2028
lib/awsflow/test/workflow_testing_context.py
lib/awsflow/test/workflow_testing_context.py
from awsflow.core import AsyncEventLoop from awsflow.context import ContextBase class WorkflowTestingContext(ContextBase): def __init__(self): self._event_loop = AsyncEventLoop() def __enter__(self): self._context = self.get_context() self.set_context(self) self._event_loop....
from awsflow.core import AsyncEventLoop from awsflow.context import ContextBase class WorkflowTestingContext(ContextBase): def __init__(self): self._event_loop = AsyncEventLoop() def __enter__(self): try: self._context = self.get_context() except AttributeError: ...
Fix context setting on the test context
Fix context setting on the test context
Python
apache-2.0
darjus/botoflow,boto/botoflow
--- +++ @@ -9,7 +9,10 @@ self._event_loop = AsyncEventLoop() def __enter__(self): - self._context = self.get_context() + try: + self._context = self.get_context() + except AttributeError: + self._context = None self.set_context(self) self._e...
b3fb2ba913a836a1e198795019870e318879d5f7
dictionary/forms.py
dictionary/forms.py
from django import forms from django.forms.models import BaseModelFormSet from django.utils.translation import ugettext_lazy as _ class BaseWordFormSet(BaseModelFormSet): def add_fields(self, form, index): super(BaseWordFormSet, self).add_fields(form, index) form.fields["isLocal"] = forms.BooleanF...
from django import forms from django.forms.models import BaseModelFormSet from django.utils.translation import ugettext_lazy as _ class BaseWordFormSet(BaseModelFormSet): def add_fields(self, form, index): super(BaseWordFormSet, self).add_fields(form, index) form.fields["isLocal"] = forms.BooleanF...
Make sure the isLocal BooleanField is not required
Make sure the isLocal BooleanField is not required
Python
agpl-3.0
sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer
--- +++ @@ -6,5 +6,5 @@ class BaseWordFormSet(BaseModelFormSet): def add_fields(self, form, index): super(BaseWordFormSet, self).add_fields(form, index) - form.fields["isLocal"] = forms.BooleanField(label=_("Local")) + form.fields["isLocal"] = forms.BooleanField(label=_("Local"), required...
7db27a3629e442c99abd24503f08d982b6a30e33
packages/Python/lldbsuite/test/lang/objc/modules-cache/TestClangModulesCache.py
packages/Python/lldbsuite/test/lang/objc/modules-cache/TestClangModulesCache.py
"""Test that the clang modules cache directory can be controlled.""" from __future__ import print_function import unittest2 import os import time import platform import shutil import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class ObjCMo...
"""Test that the clang modules cache directory can be controlled.""" from __future__ import print_function import unittest2 import os import time import platform import shutil import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class ObjCMo...
Mark ObjC testcase as skipUnlessDarwin and fix a typo in test function.
Mark ObjC testcase as skipUnlessDarwin and fix a typo in test function. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@326640 91177308-0d34-0410-b5e6-96231b3b80d8 (cherry picked from commit cb9b1a2163f960e34721f74bad30622fda71e43b)
Python
apache-2.0
apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb
--- +++ @@ -22,6 +22,7 @@ def setUp(self): TestBase.setUp(self) + @skipUnlessDarwin def test_expr(self): self.build() self.main_source_file = lldb.SBFileSpec("main.m") @@ -36,5 +37,5 @@ % self.getSourceDir()) (target, process, thread, bkpt) = lld...
d805f9f90558416f69223c72c25357345aae44c7
filer/__init__.py
filer/__init__.py
#-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 __version__ = '0.9pbs.9' # pragma: nocover
#-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 __version__ = '0.9pbs.10' # pragma: nocover
Bump the version since there are commits on top of last tag.
Bump the version since there are commits on top of last tag.
Python
bsd-3-clause
pbs/django-filer,pbs/django-filer,pbs/django-filer,pbs/django-filer,pbs/django-filer
--- +++ @@ -1,3 +1,3 @@ #-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 -__version__ = '0.9pbs.9' # pragma: nocover +__version__ = '0.9pbs.10' # pragma: nocover
e34b7c8d9e869ac1be10e8ae3d71cea794044e13
docs/blender-sphinx-build.py
docs/blender-sphinx-build.py
import os import site # get site-packages into sys.path import sys # add local addons folder to sys.path so blender finds it sys.path = ( [os.path.join(os.path.dirname(__file__), '..', 'scripts', 'addons')] + sys.path ) # run sphinx builder # this assumes that the builder is called as # "blender --backgro...
import os import site # get site-packages into sys.path import sys # add local addons folder to sys.path so blender finds it sys.path = ( [os.path.join(os.path.dirname(__file__), '..')] + sys.path ) # run sphinx builder # this assumes that the builder is called as # "blender --background --factory-startup...
Correct sys.path when generating docs.
Correct sys.path when generating docs.
Python
bsd-3-clause
nightstrike/blender_nif_plugin,amorilia/blender_nif_plugin,amorilia/blender_nif_plugin,nightstrike/blender_nif_plugin
--- +++ @@ -4,7 +4,7 @@ # add local addons folder to sys.path so blender finds it sys.path = ( - [os.path.join(os.path.dirname(__file__), '..', 'scripts', 'addons')] + [os.path.join(os.path.dirname(__file__), '..')] + sys.path )
2f60d4665a960578ab97bdaf313893ec366c24f1
kdb/default_config.py
kdb/default_config.py
# Module: defaults # Date: 14th May 2008 # Author: James Mills, prologic at shortcircuit dot net dot au """defaults - System Defaults This module contains default configuration and sane defaults for various parts of the system. These defaults are used by the environment initially when no environment has been ...
# Module: defaults # Date: 14th May 2008 # Author: James Mills, prologic at shortcircuit dot net dot au """defaults - System Defaults This module contains default configuration and sane defaults for various parts of the system. These defaults are used by the environment initially when no environment has been ...
Enable remote, rmessage and rnotify plugins by default
Enable remote, rmessage and rnotify plugins by default
Python
mit
prologic/kdb,prologic/kdb,prologic/kdb
--- +++ @@ -31,6 +31,9 @@ "greeting.*": "enabled", "help.*": "enabled", "irc.*": "enabled", + "remote.*": "enabled", + "rmessage.*": "enabled", + "rnotify.*": "enabled", "stats.*": "enabled", ...
6eca222d0bc36b2573a09c1345d940239f8e9d4d
documents/models.py
documents/models.py
from django.db import models from django.urls import reverse class Document(models.Model): FILE_TYPES = ('md', 'txt') repo = models.ForeignKey('interface.Repo', related_name='documents') path = models.TextField() filename = models.TextField() body = models.TextField(blank=True) commit_date = ...
from django.db import models from django.urls import reverse class Document(models.Model): FILE_TYPES = ('md', 'txt') repo = models.ForeignKey('interface.Repo', related_name='documents') path = models.TextField() filename = models.TextField() body = models.TextField(blank=True) commit_date = ...
Move Document.__str__ to named method
Move Document.__str__ to named method
Python
mit
ZeroCater/Eyrie,ZeroCater/Eyrie,ZeroCater/Eyrie
--- +++ @@ -12,18 +12,22 @@ commit_date = models.DateTimeField() def __str__(self): + return self.full_path + + @property + def full_path(self): return '{}/{}'.format(self.path, self.filename) @property def github_view_link(self): - return 'https://github.com/{0}/b...
89d9987f742fa74fc3646ccc163610d0c9400d75
dewbrick/utils.py
dewbrick/utils.py
import tldextract import pyphen from random import choice TITLES = ('Mister', 'Little Miss') SUFFIXES = ('Destroyer of Worlds', 'the Monkey Botherer', 'PhD') def generate_name(domain): title = choice(TITLES) _parts = tldextract.extract(domain) _parts = [_parts.subdomain, _parts.domain] parts = [] ...
import tldextract import pyphen from random import choice TITLES = ('Mister', 'Little Miss', 'Señor', 'Queen') SUFFIXES = ('Destroyer of Worlds', 'the Monkey Botherer', 'PhD', 'Ah-gowan-gowan-gowan') def generate_name(domain): title = choice(TITLES) _parts = tldextract.extract(domain) _parts...
Add more titles and suffixes
Add more titles and suffixes
Python
apache-2.0
ohmygourd/dewbrick,ohmygourd/dewbrick,ohmygourd/dewbrick
--- +++ @@ -2,8 +2,9 @@ import pyphen from random import choice -TITLES = ('Mister', 'Little Miss') -SUFFIXES = ('Destroyer of Worlds', 'the Monkey Botherer', 'PhD') +TITLES = ('Mister', 'Little Miss', 'Señor', 'Queen') +SUFFIXES = ('Destroyer of Worlds', 'the Monkey Botherer', 'PhD', + 'Ah-gowan-gowan...
e9814c857bdbf3d163352abddade1d12f0e30810
mbaas/settings_jenkins.py
mbaas/settings_jenkins.py
from mbaas.settings import * INSTALLED_APPS += ('django_nose',) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' NOSE_ARGS = [ '--cover-erase', '--with-xunit', '--with-coverage', '--cover-xml', '--cover-html', '--cover-package=accounts,push', ] DATABASES = { 'default': { 'ENGINE': 'dj...
from mbaas.settings import * INSTALLED_APPS += ('django_nose',) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' NOSE_ARGS = [ '--with-xunit', '--with-coverage', '--cover-xml', '--cover-html', '--cover-package=accounts,push', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqli...
Remove clear before test results
Remove clear before test results
Python
apache-2.0
nnsnodnb/django-mbaas,nnsnodnb/django-mbaas,nnsnodnb/django-mbaas
--- +++ @@ -5,7 +5,6 @@ TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' NOSE_ARGS = [ - '--cover-erase', '--with-xunit', '--with-coverage', '--cover-xml',
4b4ed18f01c13c321285463628bb0a3b70a75ac5
test/conftest.py
test/conftest.py
import functools import os.path import shutil import sys import tempfile import pytest @pytest.fixture(scope="function") def HOME(tmpdir): home = os.path.join(tmpdir, 'john') os.mkdir(home) # NOTE: homely._utils makes use of os.environ['HOME'], so we need to # destroy any homely modules that may have...
import functools import os.path import shutil import sys import tempfile import pytest @pytest.fixture(scope="function") def HOME(tmpdir): old_home = os.environ['HOME'] try: home = os.path.join(tmpdir, 'john') os.mkdir(home) # NOTE: homely._utils makes use of os.environ['HOME'], so w...
Rework HOME fixture so it doesn't leave os.environ corrupted
Rework HOME fixture so it doesn't leave os.environ corrupted
Python
mit
phodge/homely,phodge/homely
--- +++ @@ -9,16 +9,21 @@ @pytest.fixture(scope="function") def HOME(tmpdir): - home = os.path.join(tmpdir, 'john') - os.mkdir(home) - # NOTE: homely._utils makes use of os.environ['HOME'], so we need to - # destroy any homely modules that may have imported things based on this. - # Essentially we ...
4be8c3f8164fe0973d6277ea0d827b777cd4a988
locations/pipelines.py
locations/pipelines.py
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html from scrapy.exceptions import DropItem class DuplicatesPipeline(object): def __init__(self): self.ids_seen = set(...
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html from scrapy.exceptions import DropItem class DuplicatesPipeline(object): def __init__(self): self.ids_seen = set(...
Include spider name in item dedupe pipeline
Include spider name in item dedupe pipeline
Python
mit
iandees/all-the-places,iandees/all-the-places,iandees/all-the-places
--- +++ @@ -13,7 +13,7 @@ self.ids_seen = set() def process_item(self, item, spider): - ref = item['ref'] + ref = (spider.name, item['ref']) if ref in self.ids_seen: raise DropItem("Duplicate item found: %s" % item) else:
edd5adc9be2a700421bd8e98af825322796b8714
dns/models.py
dns/models.py
from google.appengine.ext import db TOP_LEVEL_DOMAINS = 'com net org biz info'.split() class Lookup(db.Model): """ The datastore key name is the domain name, without top level. IP address fields use 0 (zero) for NXDOMAIN because None is returned for missing properties. Updates since 2010-01-01 ...
from google.appengine.ext import db TOP_LEVEL_DOMAINS = """ com net org biz info ag am at be by ch ck de es eu fm in io is it la li ly me mobi ms name ru se sh sy tel th to travel tv us """.split() # Omitting nu, ph, st, ws because they don't seem to have NXDOMAIN. class UpgradeStringProperty(db.IntegerProperty): ...
Upgrade Lookup model to Expando and DNS result properties from integer to string.
Upgrade Lookup model to Expando and DNS result properties from integer to string.
Python
mit
jcrocholl/nxdom,jcrocholl/nxdom
--- +++ @@ -1,22 +1,51 @@ from google.appengine.ext import db -TOP_LEVEL_DOMAINS = 'com net org biz info'.split() +TOP_LEVEL_DOMAINS = """ +com net org biz info +ag am at +be by +ch ck +de +es eu +fm +in io is it +la li ly +me mobi ms +name +ru +se sh sy +tel th to travel tv +us +""".split() + +# Omitting nu, ph, ...
00cbac852e83eb1f3ddc03ed70ad32494f16fdbf
caslogging.py
caslogging.py
""" file: caslogging.py author: Ben Grawi <bjg1568@rit.edu> date: October 2013 description: Sets up the logging information for the CAS Reader """ from config import config import logging as root_logging # Set up the logger logger = root_logging.getLogger() logger.setLevel(root_logging.INFO) logger_for...
""" file: caslogging.py author: Ben Grawi <bjg1568@rit.edu> date: October 2013 description: Sets up the logging information for the CAS Reader """ from config import config import logging as root_logging # Set up the logger logger = root_logging.getLogger() logger.setLevel(root_logging.INFO) logger_for...
Fix of the logging system exception
Fix of the logging system exception Added a format to the date for the logging system. '%Y-%m-%d %H:%M:%S’. Fixed an exception opening the logging file because the variable name was not written correctly.
Python
mit
bumper-app/bumper-bianca,bumper-app/bumper-bianca
--- +++ @@ -12,9 +12,9 @@ logger = root_logging.getLogger() logger.setLevel(root_logging.INFO) -logger_format = root_logging.Formatter('%(asctime)s %(levelname)s: %(message)s') +logger_format = root_logging.Formatter('%(asctime)s %(levelname)s: %(message)s', '%Y-%m-%d %H:%M:%S') -logging_file_handler = root_log...
8bacd0f657a931754d8c03e2de86c5e00ac5f791
modoboa/lib/cryptutils.py
modoboa/lib/cryptutils.py
# coding: utf-8 from Crypto.Cipher import AES import base64 import random import string from modoboa.lib import parameters def random_key(l=16): """Generate a random key :param integer l: the key's length :return: a string """ char_set = string.digits + string.letters + string.punctuation ret...
# coding: utf-8 """Crypto related utilities.""" import base64 import random import string from Crypto.Cipher import AES from modoboa.lib import parameters def random_key(l=16): """Generate a random key. :param integer l: the key's length :return: a string """ population = string.digits + strin...
Make sure key has the required size.
Make sure key has the required size. see #867
Python
isc
tonioo/modoboa,modoboa/modoboa,bearstech/modoboa,carragom/modoboa,tonioo/modoboa,modoboa/modoboa,bearstech/modoboa,carragom/modoboa,bearstech/modoboa,bearstech/modoboa,modoboa/modoboa,carragom/modoboa,modoboa/modoboa,tonioo/modoboa
--- +++ @@ -1,19 +1,26 @@ # coding: utf-8 -from Crypto.Cipher import AES +"""Crypto related utilities.""" + import base64 import random import string + +from Crypto.Cipher import AES + from modoboa.lib import parameters def random_key(l=16): - """Generate a random key + """Generate a random key. ...
e419deba7b1081d1ece70a1840c770d9faad51f0
astral/api/tests/test_nodes.py
astral/api/tests/test_nodes.py
from nose.tools import eq_, ok_ from tornado.httpclient import HTTPRequest import json from astral.api.tests import BaseTest from astral.models.node import Node from astral.models.tests.factories import NodeFactory class NodesHandlerTest(BaseTest): def test_get_nodes(self): [NodeFactory() for _ in range(3...
from nose.tools import eq_, ok_ from tornado.httpclient import HTTPRequest import json from astral.api.tests import BaseTest from astral.models.node import Node from astral.models.tests.factories import NodeFactory class NodesHandlerTest(BaseTest): def test_get_nodes(self): [NodeFactory() for _ in range(3...
Update test for actually checking existence of nodes before creating.
Update test for actually checking existence of nodes before creating.
Python
mit
peplin/astral
--- +++ @@ -17,7 +17,7 @@ ok_(Node.get_by(uuid=node['uuid'])) def test_register_node(self): - data = {'uuid': "a-unique-id", 'port': 8000} + data = {'uuid': "a-unique-id", 'port': 8001} eq_(Node.get_by(uuid=data['uuid']), None) self.http_client.fetch(HTTPRequest( ...
61cef22952451df6345355ad596b38cb92697256
flocker/test/test_flocker.py
flocker/test/test_flocker.py
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Tests for top-level ``flocker`` package. """ from sys import executable from subprocess import check_output, STDOUT from twisted.trial.unittest import SynchronousTestCase class WarningsTests(SynchronousTestCase): """ Tests for warning suppres...
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Tests for top-level ``flocker`` package. """ from sys import executable from subprocess import check_output, STDOUT from twisted.trial.unittest import SynchronousTestCase from twisted.python.filepath import FilePath import flocker class WarningsTest...
Make sure flocker package can be imported even if it's not installed.
Make sure flocker package can be imported even if it's not installed.
Python
apache-2.0
beni55/flocker,hackday-profilers/flocker,achanda/flocker,adamtheturtle/flocker,mbrukman/flocker,Azulinho/flocker,w4ngyi/flocker,agonzalezro/flocker,agonzalezro/flocker,1d4Nf6/flocker,moypray/flocker,AndyHuu/flocker,lukemarsden/flocker,wallnerryan/flocker-profiles,mbrukman/flocker,w4ngyi/flocker,Azulinho/flocker,LaynePe...
--- +++ @@ -8,6 +8,9 @@ from subprocess import check_output, STDOUT from twisted.trial.unittest import SynchronousTestCase +from twisted.python.filepath import FilePath + +import flocker class WarningsTests(SynchronousTestCase): @@ -18,8 +21,11 @@ """ Warnings are suppressed for processes t...
879b093f29135750906f5287e132991de42ea1fe
mqtt/tests/test_client.py
mqtt/tests/test_client.py
import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalP...
import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalP...
Add more time to mqtt.test.client
Add more time to mqtt.test.client
Python
bsd-3-clause
EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient
--- +++ @@ -33,6 +33,18 @@ def test(self): + import sys + from django.core.management.base import OutputWrapper + from django.core.management.color import color_style, no_style + + # seed + from django.core import management + + management.call_command('m...
384822f44d0731f425698cc67115d179d8d13e4c
examples/mastery.py
examples/mastery.py
import cassiopeia as cass from cassiopeia.core import Summoner def test_cass(): name = "Kalturi" masteries = cass.get_masteries() for mastery in masteries: print(mastery.name) if __name__ == "__main__": test_cass()
import cassiopeia as cass def print_masteries(): for mastery in cass.get_masteries(): print(mastery.name) if __name__ == "__main__": print_masteries()
Remove redundant import, change function name.
Remove redundant import, change function name.
Python
mit
10se1ucgo/cassiopeia,meraki-analytics/cassiopeia,robrua/cassiopeia
--- +++ @@ -1,13 +1,10 @@ import cassiopeia as cass -from cassiopeia.core import Summoner -def test_cass(): - name = "Kalturi" - masteries = cass.get_masteries() - for mastery in masteries: +def print_masteries(): + for mastery in cass.get_masteries(): print(mastery.name) if __name__ ==...
e49638c1b2f844e3fa74e00b0d0a96b7c9774c24
test/test_box.py
test/test_box.py
from nex import box def test_glue_flex(): h_box = box.HBox(contents=[box.Glue(dimen=100, stretch=50, shrink=20), box.Glue(dimen=10, stretch=350, shrink=21)], set_glue=False) assert h_box.stretch == [50 + 350] assert h_box.shrink == [20 + 21] def test_g...
from nex.dampf.dvi_document import DVIDocument from nex import box, box_writer def test_glue_flex(): h_box = box.HBox(contents=[box.Glue(dimen=100, stretch=50, shrink=20), box.Glue(dimen=10, stretch=350, shrink=21)], set_glue=False) assert h_box.stretch == [...
Add basic test for box writer
Add basic test for box writer
Python
mit
eddiejessup/nex
--- +++ @@ -1,4 +1,5 @@ -from nex import box +from nex.dampf.dvi_document import DVIDocument +from nex import box, box_writer def test_glue_flex(): @@ -15,3 +16,16 @@ set_glue=True) assert h_box.stretch == [0] assert h_box.shrink == [0] + + +def test_box_writer(): + doc = DVIDo...
76f1ae6bfc6ad22cc06c012a6b96cbf6b12b8d8a
registration/admin.py
registration/admin.py
from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin)
from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') raw_id_fields = ['user'] search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfil...
Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.
Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.
Python
bsd-3-clause
stefankoegl/django-registration-couchdb,ogirardot/django-registration,andresdouglas/django-registration,bruth/django-registration2,stefankoegl/django-couchdb-utils,ogirardot/django-registration,ratio/django-registration,danielsokolowski/django-registration,wuyuntao/django-registration,stefankoegl/django-couchdb-utils,s...
--- +++ @@ -5,6 +5,7 @@ class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') + raw_id_fields = ['user'] search_fields = ('user__username', 'user__first_name')
384b2f1725e01d7f130670598821f03df64d32fe
hello_flask/hello_flask_web.py
hello_flask/hello_flask_web.py
from flask import Flask import logging app = Flask(__name__) app.debug = True stream_handler = logging.StreamHandler() app.logger.addHandler(stream_handler) app.logger.setLevel(logging.INFO) @app.route('/') def root_url(): """ Just return hello world """ return 'Hello world!' if __name__ == '__main__': ...
from flask import Flask, json from time import sleep import logging import os app = Flask(__name__) app.debug = True stream_handler = logging.StreamHandler() app.logger.addHandler(stream_handler) app.logger.setLevel(logging.INFO) @app.route('/') @app.route('/delay=<int:delay>') def root_url(delay=0): """ Just r...
Add a new url endpoint for listing all env vars and a delay to root
Add a new url endpoint for listing all env vars and a delay to root
Python
apache-2.0
CiprianAlt/hello_flask,CiprianAlt/hello_flask,ciprianc/hello_flask,ciprianc/hello_flask
--- +++ @@ -1,5 +1,7 @@ -from flask import Flask +from flask import Flask, json +from time import sleep import logging +import os app = Flask(__name__) app.debug = True @@ -10,9 +12,19 @@ @app.route('/') -def root_url(): +@app.route('/delay=<int:delay>') +def root_url(delay=0): """ Just return hello wo...