commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
65ecd11b4d4689108eabd464377afdb20ff95240
rest_framework_simplejwt/utils.py
rest_framework_simplejwt/utils.py
from __future__ import unicode_literals from calendar import timegm from datetime import datetime from django.conf import settings from django.utils import six from django.utils.functional import lazy from django.utils.timezone import is_aware, make_aware, utc def make_utc(dt): if settings.USE_TZ and not is_awa...
from __future__ import unicode_literals from calendar import timegm from datetime import datetime from django.conf import settings from django.utils import six from django.utils.functional import lazy from django.utils.timezone import is_naive, make_aware, utc def make_utc(dt): if settings.USE_TZ and is_naive(d...
Use is_naive here for clarity
Use is_naive here for clarity
Python
mit
davesque/django-rest-framework-simplejwt,davesque/django-rest-framework-simplejwt
eb33d70bfda4857fbd76616cf3bf7fb7d7feec71
spoj/00005/palin.py
spoj/00005/palin.py
#!/usr/bin/env python3 def next_palindrome(k): palin = list(k) n = len(k) mid = n // 2 # case 1: forward right just_copy = False for i in range(mid, n): mirrored = n - 1 - i if k[i] < k[mirrored]: just_copy = True if just_copy: palin[i] = palin[mirrored] # case 2: backward left if not just_copy:...
#!/usr/bin/env python3 def next_palindrome(k): palin = list(k) n = len(k) mid = n // 2 # case 1: forward right just_copy = False for i in range(mid, n): mirrored = n - 1 - i if k[i] < k[mirrored]: just_copy = True if just_copy: palin[i] = palin[mirrored] # case 2: backward left if not just_copy:...
Fix bug in ranges (to middle)
Fix bug in ranges (to middle) - in SPOJ palin Signed-off-by: Karel Ha <70f8965fdfb04f1fc0e708a55d9e822c449f57d3@gmail.com>
Python
mit
mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming
e43596395507c4606909087c0e77e84c1a232811
damn/__init__.py
damn/__init__.py
""" **damn** (aka *digital audio for music nerds*) is an easy-to-use python package for digital audio signal processing, analysis and synthesis. """ __version__ = '0.0.0'
""" **damn** (aka *digital audio for music nerds*) is an easy-to-use python package for digital audio signal processing, analysis and synthesis. """ __author__ = 'Romain Clement' __copyright__ = 'Copyright 2014, Romain Clement' __credits__ = [] __license__ = 'MIT' __version__ = "0.0.0" __maintainer__ = 'Romain Clement...
Add meta information for damn package
[DEV] Add meta information for damn package
Python
mit
rclement/yodel,rclement/yodel
7c4a8d1249becb11727002c4eb2cd2f58c712244
zou/app/utils/emails.py
zou/app/utils/emails.py
from flask_mail import Message from zou.app import mail, app def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body with app.app_context(): message = Message( sender=...
from flask_mail import Message from zou.app import mail, app def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body with app.app_context(): mail_default_sender = app.config["MAIL...
Fix configuration of email default sender
Fix configuration of email default sender
Python
agpl-3.0
cgwire/zou
a5cc18bab108f83ab45073272fa467fc62a2649b
run_python_tests.py
run_python_tests.py
#!/usr/bin/python import os import optparse import sys import unittest USAGE = """%prog SDK_PATH TEST_PATH Run unit tests for App Engine apps. SDK_PATH Path to the SDK installation. TEST_PATH Path to package containing test modules. WEBTEST_PATH Path to the webtest library.""" def main(sdk_path, test_path, ...
#!/usr/bin/python import os import optparse import sys import unittest USAGE = """%prog SDK_PATH TEST_PATH Run unit tests for App Engine apps. SDK_PATH Path to the SDK installation. TEST_PATH Path to package containing test modules. WEBTEST_PATH Path to the webtest library.""" def main(sdk_path, test_path, ...
Revert "Python tests now return an error code on fail."
Revert "Python tests now return an error code on fail."
Python
bsd-3-clause
pquochoang/samples,jiayliu/apprtc,todotobe1/apprtc,jan-ivar/adapter,82488059/apprtc,shelsonjava/apprtc,procandi/apprtc,4lejandrito/adapter,overtakermtg/samples,mvenkatesh431/samples,JiYou/apprtc,martin7890/samples,Zauberstuhl/adapter,TribeMedia/samples,jiayliu/apprtc,bpyoung92/apprtc,aadebuger/docker-apprtc,xdumaine/ad...
49e95022577eb40bcf9e1d1c9f95be7269fd0e3b
scripts/update_acq_stats.py
scripts/update_acq_stats.py
#!/usr/bin/env python # Licensed under a 3-clause BSD style license - see LICENSE.rst from mica.stats import update_acq_stats update_acq_stats.main() import os table_file = mica.stats.acq_stats.table_file file_stat = os.stat(table_file) if file_stat.st_size > 50e6: print(""" Warning: {tfile} is larger than 50MB a...
#!/usr/bin/env python # Licensed under a 3-clause BSD style license - see LICENSE.rst import os from mica.stats import update_acq_stats import mica.stats.acq_stats update_acq_stats.main() table_file = mica.stats.acq_stats.TABLE_FILE file_stat = os.stat(table_file) if file_stat.st_size > 50e6: print(""" Warning: {...
Fix reference to acq table file in script
Fix reference to acq table file in script
Python
bsd-3-clause
sot/mica,sot/mica
8a6144fc3918856cb2259f65f9ee5cc9cfaf1fdc
locustfile.py
locustfile.py
from locust import HttpLocust, TaskSet, task class UserBehavior(TaskSet): tasks = [] def on_start(self): pass @task def index(self): self.client.get("/") @task def move_map(self): self.client.get("") @task def select_scene(self): # Get url ...
from locust import HttpLocust, TaskSet, task from bs4 import BeautifulSoup from requests import Session import random class UserBehavior(TaskSet): def on_start(self): pass @task def index(self): self.client.get("/") @task def move_map(self): lat = random.uniform(-1, 1) ...
Add random functionality to map move.
Add random functionality to map move.
Python
mit
recombinators/snapsat,recombinators/snapsat,recombinators/snapsat
3b41e2166adde50f36f8f7ea389c80b76b83acaf
test/test_wavedrom.py
test/test_wavedrom.py
import subprocess from utils import * @all_files_in_dir('wavedrom_0') def test_wavedrom_0(datafiles): with datafiles.as_cwd(): subprocess.check_call(['python3', 'wavedrom-test.py']) @all_files_in_dir('wavedrom_1') def test_wavedrom_1(datafiles): with datafiles.as_cwd(): for s in get_simulato...
import subprocess from utils import * @all_files_in_dir('wavedrom_0') def test_wavedrom_0(datafiles): with datafiles.as_cwd(): subprocess.check_call(['python3', 'wavedrom-test.py']) @all_files_in_dir('wavedrom_1') @all_available_simulators() def test_wavedrom_1(datafiles, simulator): with datafiles....
Update wavedrom tests to get simulators via fixture
Update wavedrom tests to get simulators via fixture
Python
apache-2.0
nosnhojn/svunit-code,svunit/svunit,nosnhojn/svunit-code,svunit/svunit,svunit/svunit,nosnhojn/svunit-code
9d041287e5e0d1950d5dcda23f6f68522d287282
tests/test_machine.py
tests/test_machine.py
import rml.machines def test_machine_load_elements(): lattice = rml.machines.get_elements(machine='SRI21', elemType='BPM') assert len(lattice) == 173 for element in lattice.get_elements(): assert element.get_pv_name('readback')
import rml.machines def test_machine_load_elements(): lattice = rml.machines.get_elements(machine='SRI21', elem_type='BPM') assert len(lattice) == 173 for element in lattice.get_elements(): assert isinstance(element.get_pv_name('readback', 'x'), str) assert isinstance(element.get_pv_name('...
Test if pvs are loaded correctly from the database
Test if pvs are loaded correctly from the database
Python
apache-2.0
willrogers/pml,willrogers/pml,razvanvasile/RML
4a3df7842ab8f305ece134aa223801007d55c4f9
timm/utils/metrics.py
timm/utils/metrics.py
""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 ...
""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 ...
Fix topn metric view regression on PyTorch 1.7
Fix topn metric view regression on PyTorch 1.7
Python
apache-2.0
rwightman/pytorch-image-models,rwightman/pytorch-image-models
362c8dacda35bac24aa83e4fcaa2f6bac37150fd
tests/test_mw_util.py
tests/test_mw_util.py
"""Unit tests for cat2cohort.""" import unittest from mw_util import str2cat class TestMWutil(unittest.TestCase): """Test methods from mw_util.""" pass
"""Unit tests for cat2cohort.""" import unittest from mw_util import str2cat class TestMWutil(unittest.TestCase): """Test methods from mw_util.""" def test_str2cat(self): """Test str2cat.""" values = [ ('A', 'Category:A'), ('Category:B', 'Category:B'), ] ...
Add unit test for str2cat method.
Add unit test for str2cat method.
Python
mit
Commonists/wm_metrics,danmichaelo/wm_metrics,Commonists/wm_metrics,Commonists/wm_metrics,danmichaelo/wm_metrics,danmichaelo/wm_metrics,danmichaelo/wm_metrics,Commonists/wm_metrics
ebf52caf6ee09ef1f15cb88815a1fb8008899c79
tests/test_reactjs.py
tests/test_reactjs.py
# -*- coding: utf-8 -*- import dukpy class TestReactJS(object): def test_hello_world(self): jsx = dukpy.jsx_compile('var react_hello = <h1>Hello, world!</h1>;') jsi = dukpy.JSInterpreter() result = jsi.evaljs([ ''' var React = require('react/react'), Re...
# -*- coding: utf-8 -*- import dukpy class TestReactJS(object): def test_hello_world(self): jsx = dukpy.jsx_compile('var react_hello = <h1>Hello, world!</h1>;') jsi = dukpy.JSInterpreter() result = jsi.evaljs([ ''' var React = require('react/react'), Re...
Add tests for a React Component
Add tests for a React Component
Python
mit
amol-/dukpy,amol-/dukpy,amol-/dukpy
484e5693b2f3e0bc8c238cd64afeaad17bfa6673
skimage/viewer/qt/QtCore.py
skimage/viewer/qt/QtCore.py
from . import qt_api if qt_api == 'pyside': from PySide.QtCore import * elif qt_api == 'pyqt': from PyQt4.QtCore import * else: # Mock objects Qt = None def pyqtSignal(*args, **kwargs): pass
from . import qt_api if qt_api == 'pyside': from PySide.QtCore import * elif qt_api == 'pyqt': from PyQt4.QtCore import * else: # Mock objects for buildbot (which doesn't have Qt, but imports viewer). class Qt(object): TopDockWidgetArea = None BottomDockWidgetArea = None LeftDoc...
Add attributes to Mock object to fix Travis build
Add attributes to Mock object to fix Travis build
Python
bsd-3-clause
ajaybhat/scikit-image,chintak/scikit-image,warmspringwinds/scikit-image,vighneshbirodkar/scikit-image,SamHames/scikit-image,SamHames/scikit-image,SamHames/scikit-image,michaelpacer/scikit-image,jwiggins/scikit-image,rjeli/scikit-image,blink1073/scikit-image,almarklein/scikit-image,bsipocz/scikit-image,almarklein/scikit...
2a32fc912a5839f627a216918e4671e6547ee53b
tests/utils/driver.py
tests/utils/driver.py
import os from importlib import import_module from .testdriver import TestDriver class Driver(TestDriver): drivers = {} def __new__(cls, type, *args, **kwargs): if type not in cls.drivers: try: mod = import_module('onitu.drivers.{}.tests.driver'. ...
import os import pkg_resources from .testdriver import TestDriver class Driver(TestDriver): drivers = {} def __new__(cls, name, *args, **kwargs): entry_points = pkg_resources.iter_entry_points('onitu.tests') tests_modules = {e.name: e for e in entry_points} if name not in tests_modu...
Load tests helpers using entry_points
Load tests helpers using entry_points
Python
mit
onitu/onitu,onitu/onitu,onitu/onitu
86f6191867141d7a7a165b227255d7b4406eb4f4
accounts/utils.py
accounts/utils.py
""" Utility functions for the accounts app. """ from django.core.exceptions import ObjectDoesNotExist def get_user_city(user): """Return the user's city. If unavailable, return an empty string.""" # If the profile is absent (i.e. superuser), return None. try: city = user.common_profile.city e...
""" Utility functions for the accounts app. """ from django.core.exceptions import ObjectDoesNotExist def get_user_city(user): """Return the user's city. If unavailable, return an empty string.""" # If the profile is absent (i.e. superuser), return None. try: city = user.common_profile.city e...
Fix crash on non-logged in users.
Fix crash on non-logged in users.
Python
agpl-3.0
osamak/student-portal,osamak/student-portal,osamak/student-portal,osamak/student-portal,enjaz/enjaz,enjaz/enjaz,enjaz/enjaz,enjaz/enjaz,osamak/student-portal,enjaz/enjaz
6795e112e4f7037449850a361ab6b2f85fc2a66e
service/settings/staging.py
service/settings/staging.py
from service.settings.production import * ALLOWED_HOSTS = [ 'fantastic-doodle--staging.herokuapp.com', ]
from service.settings.production import * ALLOWED_HOSTS = [ 'fantastic-doodle--staging.herokuapp.com', '.herokuapp.com', ]
Add .herokuapp.com to ALLOWED_HOSTS to support review apps
Add .herokuapp.com to ALLOWED_HOSTS to support review apps
Python
unlicense
Mystopia/fantastic-doodle
3800c095f58e9bc2ca8c580537ea576049bbfe2d
sell/urls.py
sell/urls.py
from django.conf.urls import url from sell import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^personal/$', views.personal_data), url(r'^books/$', views.books), url(r'^summary/$', views.summary), ]
from django.conf.urls import url from sell import views urlpatterns = [ url(r'^$', views.index), url(r'^personal/$', views.personal_data), url(r'^books/$', views.books), url(r'^summary/$', views.summary), ]
Remove unnecessary URL name in Sell app
Remove unnecessary URL name in Sell app
Python
agpl-3.0
m4tx/egielda,m4tx/egielda,m4tx/egielda
c47c043e76ac037456b8e966a5f9d60a151e3120
elodie/geolocation.py
elodie/geolocation.py
from os import path from ConfigParser import ConfigParser import requests import sys def reverse_lookup(lat, lon): if(lat is None or lon is None): return None if not path.exists('./config.ini'): return None config = ConfigParser() config.read('./config.ini') if('MapQuest' ...
from os import path from ConfigParser import ConfigParser import requests import sys def reverse_lookup(lat, lon): if(lat is None or lon is None): return None config_file = '%s/config.ini' % path.dirname(path.dirname(path.abspath(__file__))) if not path.exists(config_file): return None ...
Use absolute path for config file so it works with apps like Hazel
Use absolute path for config file so it works with apps like Hazel
Python
apache-2.0
zserg/elodie,zingo/elodie,jmathai/elodie,jmathai/elodie,zingo/elodie,zserg/elodie,zserg/elodie,jmathai/elodie,zserg/elodie,jmathai/elodie,zingo/elodie
4fd47cf73d59cb9e9d83cea12026878f65df858a
numscons/core/allow_undefined.py
numscons/core/allow_undefined.py
import os from subprocess import Popen, PIPE def get_darwin_version(): p = Popen(["sw_vers", "-productVersion"], stdout = PIPE, stderr = PIPE) st = p.wait() if st: raise RuntimeError( "Could not execute sw_vers -productVersion to get version") verstring = p.stdout.next() a...
"""This module handle platform specific link options to allow undefined symbols in shared libraries and dynamically loaded libraries.""" import os from subprocess import Popen, PIPE def get_darwin_version(): p = Popen(["sw_vers", "-productVersion"], stdout = PIPE, stderr = PIPE) st = p.wait() if st: ...
Add docstring + fix missing import in allow_udnefined module.
Add docstring + fix missing import in allow_udnefined module.
Python
bsd-3-clause
cournape/numscons,cournape/numscons,cournape/numscons
4e0ec0fdf791fc9af1e83171b54054bd53d5536b
django_evolution/compat/apps.py
django_evolution/compat/apps.py
try: from django.apps.registry import apps get_apps = apps.get_apps cache = None except ImportError: from django.db.models.loading import cache get_apps = cache.get_apps apps = None def get_app(app_label, emptyOK=False): """Return the app with the given label. This returns the app f...
try: from django.apps.registry import apps # Django >= 1.7 get_apps = apps.get_apps cache = None except ImportError: from django.db.models.loading import cache # Django < 1.7 get_apps = cache.get_apps apps = None def get_app(app_label, emptyOK=False): """Return the app with the g...
Fix the new get_app compatibility function.
Fix the new get_app compatibility function. The get_app compatibility function was trying to call get_apps() on the apps variable, instead of calling the extracted version that was pre-computed. Now it uses the correct versions.
Python
bsd-3-clause
beanbaginc/django-evolution
82ae5e5cf3da57af771aa688ec7d951879423578
big_o/test/test_complexities.py
big_o/test/test_complexities.py
import unittest import numpy as np from numpy.testing import assert_array_almost_equal from big_o import complexities class TestComplexities(unittest.TestCase): def test_compute(self): x = np.linspace(10, 100, 100) y = 3.0 * x + 2.0 linear = complexities.Linear() linear.fit(x, y)...
import unittest import numpy as np from numpy.testing import assert_array_almost_equal from big_o import complexities class TestComplexities(unittest.TestCase): def test_compute(self): desired = [ (lambda x: 2.+x*0., complexities.Constant), (lambda x: 5.*x+3., complexities.Linear...
Add compute test cases for all complexity classes
Add compute test cases for all complexity classes
Python
bsd-3-clause
pberkes/big_O
219c474860ca7674070ef19fa95f0282b7c92399
mpages/admin.py
mpages/admin.py
from django.contrib import admin from .models import Page, PageRead, Tag class PageAdmin(admin.ModelAdmin): search_fields = ["title"] list_display = ["title", "parent", "updated"] prepopulated_fields = {"slug": ("title",)} readonly_fields = ["updated"] ordering = ["parent", "title"] filter_ho...
from django.contrib import admin from .models import Page, PageRead, Tag class PageAdmin(admin.ModelAdmin): search_fields = ["title"] list_display = ["title", "parent", "updated"] prepopulated_fields = {"slug": ("title",)} readonly_fields = ["updated"] ordering = ["parent", "title"] filter_ho...
Order parents in Admin select field
Order parents in Admin select field
Python
bsd-3-clause
ahernp/DMCM,ahernp/DMCM,ahernp/DMCM
f76783ddb616c74e22feb003cb12952375cad658
corehq/apps/hqwebapp/encoders.py
corehq/apps/hqwebapp/encoders.py
import json import datetime from django.utils.encoding import force_unicode from django.utils.functional import Promise class LazyEncoder(json.JSONEncoder): """Taken from https://github.com/tomchristie/django-rest-framework/issues/87 This makes sure that ugettext_lazy refrences in a dict are properly evaluate...
import json import datetime from decimal import Decimal from django.utils.encoding import force_unicode from django.utils.functional import Promise class DecimalEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Decimal): return str(obj) return super(DecimalEncoder, ...
Fix for json encoding Decimal values
Fix for json encoding Decimal values
Python
bsd-3-clause
SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,SEL-Columbia/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare...
991973e554758e7a9881453d7668925902e610b9
tests.py
tests.py
#!/usr/bin/env python import unittest import git_mnemonic as gm class GitMnemonicTests(unittest.TestCase): def test_encode(self): self.assertTrue(gm.encode("master")) def test_decode(self): self.assertTrue(gm.decode("bis alo ama aha")) def test_invertible(self): once = gm.encode...
#!/usr/bin/env python import unittest import git_mnemonic as gm class GitMnemonicTests(unittest.TestCase): def test_encode(self): self.assertTrue(gm.encode("master")) def test_decode(self): self.assertTrue(gm.decode("bis alo ama aha")) def test_invertible(self): once = gm.encode...
Make unittest test runner work in older pythons
Make unittest test runner work in older pythons
Python
mit
glenjamin/git-mnemonic
cb08d25f49b8b4c5177c8afdd9a69330992ee854
tests/replay/test_replay.py
tests/replay/test_replay.py
# -*- coding: utf-8 -*- """ test_replay ----------- """ import pytest from cookiecutter import replay, main, exceptions def test_get_replay_file_name(): """Make sure that replay.get_file_name generates a valid json file path.""" assert replay.get_file_name('foo', 'bar') == 'foo/bar.json' @pytest.fixture(...
# -*- coding: utf-8 -*- """ test_replay ----------- """ import pytest from cookiecutter import replay, main, exceptions def test_get_replay_file_name(): """Make sure that replay.get_file_name generates a valid json file path.""" assert replay.get_file_name('foo', 'bar') == 'foo/bar.json' @pytest.fixture(...
Add tests for a correct behaviour in cookiecutter.main for replay
Add tests for a correct behaviour in cookiecutter.main for replay
Python
bsd-3-clause
christabor/cookiecutter,luzfcb/cookiecutter,hackebrot/cookiecutter,cguardia/cookiecutter,pjbull/cookiecutter,dajose/cookiecutter,michaeljoseph/cookiecutter,moi65/cookiecutter,terryjbates/cookiecutter,takeflight/cookiecutter,terryjbates/cookiecutter,luzfcb/cookiecutter,agconti/cookiecutter,cguardia/cookiecutter,christab...
9547988a1a9ef8faf22d9bfa881f4e542637fd46
utils.py
utils.py
import xmlrpclib import cPickle import subprocess from time import sleep p = None s = None def start_plot_server(): global p if p is None: p = subprocess.Popen(["python", "plot_server.py"]) def stop_plot_server(): if p is not None: p.terminate() sleep(0.01) p.kill() def p...
import xmlrpclib import cPickle import subprocess from time import sleep p = None s = None def start_plot_server(): global p if p is None: p = subprocess.Popen(["python", "plot_server.py"]) def stop_plot_server(): if p is not None: p.terminate() sleep(0.01) p.kill() def p...
Establish connection only when needed
Establish connection only when needed
Python
bsd-3-clause
certik/mhd-hermes,certik/mhd-hermes
f3b9cc6392e4c271ae11417357ecdc196f1c3ae7
python_scripts/extractor_python_readability_server.py
python_scripts/extractor_python_readability_server.py
#!/usr/bin/python import sys import os import glob #sys.path.append(os.path.join(os.path.dirname(__file__), "gen-py")) sys.path.append(os.path.join(os.path.dirname(__file__),"gen-py/thrift_solr/")) sys.path.append(os.path.dirname(__file__) ) from thrift.transport import TSocket from thrift.server import TServer #im...
#!/usr/bin/python import sys import os import glob #sys.path.append(os.path.join(os.path.dirname(__file__), "gen-py")) sys.path.append(os.path.join(os.path.dirname(__file__),"gen-py/thrift_solr/")) sys.path.append(os.path.dirname(__file__) ) from thrift.transport import TSocket from thrift.transport import TTranspor...
Use the TBinaryProtocolAccelerated protocol instead of TBinaryProtocol to improve performance.
Use the TBinaryProtocolAccelerated protocol instead of TBinaryProtocol to improve performance.
Python
agpl-3.0
AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT...
3ce1b928f36c314ab07c334843b2db96626f469e
kyokai/asphalt.py
kyokai/asphalt.py
""" Asphalt framework mixin for Kyokai. """ import logging import asyncio from functools import partial from typing import Union from asphalt.core import Component, resolve_reference, Context from typeguard import check_argument_types from kyokai.app import Kyokai from kyokai.protocol import KyokaiProtocol from kyok...
""" Asphalt framework mixin for Kyokai. """ import logging import asyncio from functools import partial from typing import Union from asphalt.core import Component, resolve_reference, Context from typeguard import check_argument_types from kyokai.app import Kyokai from kyokai.protocol import KyokaiProtocol from kyok...
Make this into a partial to get the protocol correctly.
Make this into a partial to get the protocol correctly.
Python
mit
SunDwarf/Kyoukai
b352c3e1f5e8812d29f2e8a1bca807bea5da8cc4
test/test_hx_launcher.py
test/test_hx_launcher.py
import pytest_twisted from hendrix.ux import main from hendrix.options import HendrixOptionParser def test_no_arguments_gives_help_text(mocker): class MockFile(object): @classmethod def write(cls, whatever): cls.things_written = whatever class MockStdOut(object): @class...
from hendrix.options import HendrixOptionParser from hendrix.ux import main def test_no_arguments_gives_help_text(mocker): class MockFile(object): @classmethod def write(cls, whatever): cls.things_written = whatever class MockStdOut(object): @classmethod def write...
Test for the hx launcher.
Test for the hx launcher.
Python
mit
hangarunderground/hendrix,hendrix/hendrix,hangarunderground/hendrix,hendrix/hendrix,jMyles/hendrix,hendrix/hendrix,jMyles/hendrix,hangarunderground/hendrix,hangarunderground/hendrix,jMyles/hendrix
ad21c9255f6246944cd032ad50082c0aca46fcb3
neurokernel/tools/mpi.py
neurokernel/tools/mpi.py
#!/usr/bin/env python """ MPI utilities. """ from mpi4py import MPI import twiggy class MPIOutput(twiggy.outputs.Output): """ Output messages to a file via MPI I/O. """ def __init__(self, name, format, comm, mode=MPI.MODE_CREATE | MPI.MODE_WRONLY, close_atexit=True)...
#!/usr/bin/env python """ MPI utilities. """ from mpi4py import MPI import twiggy class MPIOutput(twiggy.outputs.Output): """ Output messages to a file via MPI I/O. """ def __init__(self, name, format, comm, mode=MPI.MODE_CREATE | MPI.MODE_WRONLY, close_atexit=True)...
Call MPIOutput.file.Sync() in MPIOutput.file._write() to prevent log lines from intermittently being lost.
Call MPIOutput.file.Sync() in MPIOutput.file._write() to prevent log lines from intermittently being lost.
Python
bsd-3-clause
cerrno/neurokernel
4485b65722645d6c9617b5ff4aea6d62ee8a9adf
bumblebee_status/modules/contrib/optman.py
bumblebee_status/modules/contrib/optman.py
"""Displays currently active gpu by optimus-manager Requires the following packages: * optimus-manager """ import subprocess import core.module import core.widget class Module(core.module.Module): def __init__(self, config, theme): super().__init__(config, theme, core.widget.Widget(self.output)) ...
"""Displays currently active gpu by optimus-manager Requires the following packages: * optimus-manager """ import core.module import core.widget import util.cli class Module(core.module.Module): def __init__(self, config, theme): super().__init__(config, theme, core.widget.Widget(self.output)) ...
Use the existing util.cli module
Use the existing util.cli module
Python
mit
tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status
3307bfb7075a527dc7805da2ff735f461f5fc02f
employees/models.py
employees/models.py
from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Role(models.Model): name = models.CharField(max_length=100) def __str__(self): ret...
from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Role(models.Model): name = models.CharField(max_length=100) def __str__(self): ret...
Change categories field to non required.
Change categories field to non required.
Python
mit
neosergio/allstars
b8bc10e151f12e2bfe2c03765a410a04325a3233
satchmo/product/templatetags/satchmo_product.py
satchmo/product/templatetags/satchmo_product.py
from django import template from django.conf import settings from django.core import urlresolvers from django.template import Context, Template from django.utils.translation import get_language, ugettext_lazy as _ from satchmo.configuration import config_value from satchmo.product.models import Category from satchmo.sh...
from django import template from django.conf import settings from django.core import urlresolvers from django.template import Context, Template from django.utils.translation import get_language, ugettext_lazy as _ from satchmo.configuration import config_value from satchmo.product.models import Category from satchmo.sh...
Change the is_producttype template tag to return a boolean rather than a string.
Change the is_producttype template tag to return a boolean rather than a string. --HG-- extra : convert_revision : svn%3Aa38d40e9-c014-0410-b785-c606c0c8e7de/satchmo/trunk%401200
Python
bsd-3-clause
Ryati/satchmo,ringemup/satchmo,Ryati/satchmo,dokterbob/satchmo,twidi/satchmo,twidi/satchmo,dokterbob/satchmo,ringemup/satchmo
b4247769fcaa67d09e0f38d1283cf4f28ddc350e
cookiecutter/extensions.py
cookiecutter/extensions.py
# -*- coding: utf-8 -*- """Jinja2 extensions.""" import json from jinja2.ext import Extension class JsonifyExtension(Extension): """Jinja2 extension to convert a python object to json.""" def __init__(self, environment): """Initilize extension with given environment.""" super(JsonifyExtens...
# -*- coding: utf-8 -*- """Jinja2 extensions.""" import json from jinja2.ext import Extension class JsonifyExtension(Extension): """Jinja2 extension to convert a Python object to JSON.""" def __init__(self, environment): """Initialize the extension with the given environment.""" super(Json...
Fix typo and improve grammar in doc string
Fix typo and improve grammar in doc string
Python
bsd-3-clause
michaeljoseph/cookiecutter,dajose/cookiecutter,audreyr/cookiecutter,hackebrot/cookiecutter,audreyr/cookiecutter,hackebrot/cookiecutter,luzfcb/cookiecutter,pjbull/cookiecutter,dajose/cookiecutter,pjbull/cookiecutter,luzfcb/cookiecutter,michaeljoseph/cookiecutter
42ec5ed6d56fcc59c99d175e1c9280d00cd3bef1
tests/test_published_results.py
tests/test_published_results.py
""" To test if the new code produces the same precision values on the published results.""" from __future__ import division, print_function import pytest import numpy as np import eniric.Qcalculator as Q import eniric.IOmodule as IO from bin.prec_1 import calc_prec1 # For python2.X compatibility file_error_to_catch...
""" To test if the new code produces the same precision values on the published results.""" from __future__ import division, print_function import pytest import numpy as np import eniric.Qcalculator as Q import eniric.IOmodule as IO from bin.prec_1 import calc_prec1 # For python2.X compatibility file_error_to_catch...
Add known offset for known bad calibration.
Add known offset for known bad calibration. Former-commit-id: afa3d6a66e32bbcc2b20f00f7e63fba5cb45882e [formerly 0470ca22b8a24205d2eb1c66caee912c990da0b3] [formerly c23210f4056c27e61708da2f2440bce3eda151a8 [formerly 5c0a6b9c0fefd2b88b9382d4a6ed98d9eac626df]] Former-commit-id: 8bfdaa1f7940b26aee05f20e801616f4a8d1d55d ...
Python
mit
jason-neal/eniric,jason-neal/eniric
f3df3b2b8e1167e953457a85f2297d28b6a39729
examples/Micro.Blog/microblog.py
examples/Micro.Blog/microblog.py
from getpass import getpass from bessie import BaseClient import config class MicroBlogApi(BaseClient): endpoints = config.available_endpoints separator = '/' base_url='https://micro.blog' def __init__(self, path='', token=''): self.token = token super(self.__class__, self).__init__(path, token=token) #...
from getpass import getpass from bessie import BaseClient import config class MicroBlogApi(BaseClient): endpoints = config.available_endpoints separator = '/' base_url='https://micro.blog' def __init__(self, path='', path_params=None, token=''): self.token = token super(self.__class__, self).__init__(path...
Include path_params in override constructor
Include path_params in override constructor
Python
mit
andymitchhank/bessie
c9980756dcee82cc570208e73ec1a2112aea0155
tvtk/tests/test_scene.py
tvtk/tests/test_scene.py
""" Tests for the garbage collection of Scene objects. """ # Authors: Deepak Surti, Ioannis Tziakos # Copyright (c) 2015, Enthought, Inc. # License: BSD Style. import unittest import weakref import gc from traits.etsconfig.api import ETSConfig from tvtk.pyface.scene import Scene from tvtk.tests.common import restore...
""" Tests for the garbage collection of Scene objects. """ # Authors: Deepak Surti, Ioannis Tziakos # Copyright (c) 2015, Enthought, Inc. # License: BSD Style. import unittest import weakref import gc from traits.etsconfig.api import ETSConfig from tvtk.pyface.scene import Scene from tvtk.tests.common import restore...
Add weakref assertion in test case
Add weakref assertion in test case
Python
bsd-3-clause
alexandreleroux/mayavi,dmsurti/mayavi,dmsurti/mayavi,alexandreleroux/mayavi,liulion/mayavi,liulion/mayavi
74b2883c3371304e8f5ea95b0454fb006d85ba3d
mapentity/urls.py
mapentity/urls.py
from django.conf import settings from django.conf.urls import patterns, url from . import app_settings from .views import (map_screenshot, convert, history_delete, serve_secure_media, JSSettings) _MEDIA_URL = settings.MEDIA_URL.replace(app_settings['ROOT_URL'], '')[1:] urlpatterns = patterns( ...
from django.conf import settings from django.conf.urls import patterns, url from . import app_settings from .views import (map_screenshot, convert, history_delete, serve_secure_media, JSSettings) _MEDIA_URL = settings.MEDIA_URL.replace(app_settings['ROOT_URL'], '') if _MEDIA_URL.startswith('/'): ...
Remove leading and trailing slash of MEDIA_URL
Remove leading and trailing slash of MEDIA_URL Conflicts: mapentity/static/mapentity/Leaflet.label
Python
bsd-3-clause
Anaethelion/django-mapentity,Anaethelion/django-mapentity,makinacorpus/django-mapentity,makinacorpus/django-mapentity,Anaethelion/django-mapentity,makinacorpus/django-mapentity
6953b831c3c48a3512a86ca9e7e92edbf7a62f08
tests/integration/test_sqs.py
tests/integration/test_sqs.py
import os from asyncaws import SQS from tornado.testing import AsyncTestCase, gen_test aws_key_id = os.environ['AWS_ACCESS_KEY_ID'] aws_key_secret = os.environ['AWS_SECRET_ACCESS_KEY'] aws_region = os.environ['AWS_REGION'] class TestSQS(AsyncTestCase): sqs = SQS(aws_key_id, aws_key_secret, aws_region, async=Fals...
import os from asyncaws import SQS from tornado.testing import AsyncTestCase, gen_test from random import randint aws_key_id = os.environ['AWS_ACCESS_KEY_ID'] aws_key_secret = os.environ['AWS_SECRET_ACCESS_KEY'] aws_region = os.environ['AWS_REGION'] aws_test_account_id = "637085312181" class TestSQS(AsyncTestCase): ...
Add correct setUp/tearDown methods for integration sqs test
Add correct setUp/tearDown methods for integration sqs test
Python
mit
MA3STR0/AsyncAWS
7dd17cc10f7e0857ab3017177d6c4abeb115ff07
south/models.py
south/models.py
from django.db import models from south.db import DEFAULT_DB_ALIAS class MigrationHistory(models.Model): app_name = models.CharField(max_length=255) migration = models.CharField(max_length=255) applied = models.DateTimeField(blank=True) @classmethod def for_migration(cls, migration, database): ...
from django.db import models from south.db import DEFAULT_DB_ALIAS # If we detect Django 1.7 or higher, then exit # Placed here so it's guaranteed to be imported on Django start import django if django.VERSION[0] > 1 or (django.VERSION[0] == 1 and django.VERSION[1] > 6): raise RuntimeError("South does not support ...
Add explicit version check for Django 1.7 or above
Add explicit version check for Django 1.7 or above
Python
apache-2.0
smartfile/django-south,smartfile/django-south
fe85f1f135d2a7831afee6c8ab0bad394beb8aba
src/ais.py
src/ais.py
class MonsterAI(object): def __init__(self, level): self.owner = None self.level = level def take_turn(self): self.owner.log.log_begin_turn(self.owner.oid) self._take_turn() def _take_turn(self): raise NotImplementedError('Subclass this before usage please.') clas...
from src.constants import * class MonsterAI(object): def __init__(self, level): self.owner = None self.level = level def take_turn(self): self.owner.log.log_begin_turn(self.owner.oid) self._take_turn() def _take_turn(self): raise NotImplementedError('Subclass this...
Add throwing item usage to test AI
Add throwing item usage to test AI Unforutnately the item isn't evicted from the inventory on usage, so the guy with the throwing item can kill everybody, but it's working - he does throw it!
Python
mit
MoyTW/RL_Arena_Experiment
fe78335e4f469e22f9a1de7a1e5ddd52021a7f0f
linesep.py
linesep.py
STARTER = -1 SEPARATOR = 0 TERMINATOR = 1 def readlines(fp, sep, mode=TERMINATOR, retain=True, size=512): if mode < 0: return _readlines_start(fp, sep, retain, size) elif mode == 0: return _readlines_sep(fp, sep, size) else: return _readlines_term(fp, sep, retain, size) def _readli...
def read_begun(fp, sep, retain=True, size=512): # Omits empty leading entry entries = read_separated(fp, sep, size=size) e = next(entries) if e: yield e for e in entries: if retain: e = sep + e yield e def read_separated(fp, sep, size=512): buff = '' for ...
Use three public functions instead of one
Use three public functions instead of one
Python
mit
jwodder/linesep
e9ae6b7f92ee0a4585adc11e695cc15cbe425e23
morepath/app.py
morepath/app.py
from .interfaces import IRoot, IApp from .publish import publish from .request import Request from .traject import Traject from comparch import ClassRegistry, Lookup, ChainClassLookup known_apps = {} class App(IApp, ClassRegistry): def __init__(self, name='', parent=None): super(App, self).__init__() ...
from .interfaces import IRoot, IApp from .publish import publish from .request import Request from .traject import Traject from comparch import ClassRegistry, Lookup, ChainClassLookup known_apps = {} class App(IApp, ClassRegistry): def __init__(self, name='', parent=None): super(App, self).__init__() ...
Remove root that wasn't used.
Remove root that wasn't used.
Python
bsd-3-clause
faassen/morepath,morepath/morepath,taschini/morepath
a7938ed9ec814fa9cf53272ceb65e84d11d50dc1
moto/s3/urls.py
moto/s3/urls.py
from __future__ import unicode_literals from moto.compat import OrderedDict from .responses import S3ResponseInstance url_bases = [ "https?://s3(.*).amazonaws.com", "https?://(?P<bucket_name>[a-zA-Z0-9\-_.]*)\.?s3(.*).amazonaws.com" ] url_paths = OrderedDict([ # subdomain bucket ('{0}/$', S3ResponseI...
from __future__ import unicode_literals from .responses import S3ResponseInstance url_bases = [ "https?://s3(.*).amazonaws.com", "https?://(?P<bucket_name>[a-zA-Z0-9\-_.]*)\.?s3(.*).amazonaws.com" ] url_paths = { # subdomain bucket '{0}/$': S3ResponseInstance.bucket_response, # subdomain key of ...
Fix s3 url regex to ensure path-based bucket and key does not catch.
Fix s3 url regex to ensure path-based bucket and key does not catch.
Python
apache-2.0
william-richard/moto,kefo/moto,botify-labs/moto,2rs2ts/moto,dbfr3qs/moto,im-auld/moto,william-richard/moto,william-richard/moto,Affirm/moto,kefo/moto,botify-labs/moto,Brett55/moto,ZuluPro/moto,ZuluPro/moto,okomestudio/moto,spulec/moto,whummer/moto,william-richard/moto,kefo/moto,kefo/moto,ZuluPro/moto,dbfr3qs/moto,heddl...
429c2548835aef1cb1655229ee11f42ccf189bd1
shopping_list.py
shopping_list.py
shopping_list = [] def show_help(): print("What should we pick up at the store?") print("Enter DONE to stop. Enter HELP for this help. Enter SHOW to see your current list.")
shopping_list = [] def show_help(): print("What should we pick up at the store?") print("Enter DONE to stop. Enter HELP for this help. Enter SHOW to see your current list.") def add_to_list(item): shopping_list.append(item) print("Added! List has {} items.".format(len(shopping_list)))
Add an item to the shopping list.
Add an item to the shopping list.
Python
mit
adityatrivedi/shopping-list
39ce4e74a6b7115a35260fa2722ace1792cb1780
python/count_triplets.py
python/count_triplets.py
#!/bin/python3 import math import os import random import re import sys from collections import Counter def countTriplets(arr, r): potential_triplets_with_middle = Counter() potential_triplets_with_end = Counter() total_triplets = 0 for num in arr: # num completed potential_triplets_with_end[n...
#!/bin/python3 import math import os import random import re import sys from collections import Counter def countTriplets(arr, r): potential_triplets_with_middle = Counter() potential_triplets_with_end = Counter() total_triplets = 0 for num in arr: # num completed potential_triplets_with_end[...
Remove debug output and pycodestyle
Remove debug output and pycodestyle
Python
mit
rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank
5dd78f614e5882bc2a3fcae24117a26ee34371ac
register-result.py
register-result.py
#!/usr/bin/env python import json import socket import sys if len(sys.argv) < 4: print("Error: Usage <register-result> <client> <name> <output> <status> <ttl>") sys.exit(128) check_client = sys.argv[1] check_name = sys.argv[2] check_output = sys.argv[3] check_status = int(sys.argv[4]) check_ttl = int(sys.arg...
#!/usr/bin/env python import json import socket import sys if len(sys.argv) < 4: print("Error: Usage <register-result> <client> <name> <output> <status> <ttl>") sys.exit(128) check_client = sys.argv[1] check_name = sys.argv[2] check_output = sys.argv[3] check_status = int(sys.argv[4]) check_ttl = int(sys.arg...
Fix mistake with socket constructor
Fix mistake with socket constructor
Python
mit
panubo/docker-monitor,panubo/docker-monitor,panubo/docker-monitor
5e57dce84ffe7be7e699af1e2be953d5a65d8435
tests/test_module.py
tests/test_module.py
#!/usr/bin/env python # # Author: Mike McKerns (mmckerns @caltech and @uqfoundation) # Copyright (c) 2008-2014 California Institute of Technology. # License: 3-clause BSD. The full license text is available at: # - http://trac.mystic.cacr.caltech.edu/project/pathos/browser/dill/LICENSE import sys import dill import ...
#!/usr/bin/env python # # Author: Mike McKerns (mmckerns @caltech and @uqfoundation) # Copyright (c) 2008-2014 California Institute of Technology. # License: 3-clause BSD. The full license text is available at: # - http://trac.mystic.cacr.caltech.edu/project/pathos/browser/dill/LICENSE import sys import dill import ...
Add code to clean up
Add code to clean up
Python
bsd-3-clause
wxiang7/dill,mindw/dill
66a6223ca2c512f3f39ecb4867547a440611713b
nisl/__init__.py
nisl/__init__.py
""" Machine Learning module for NeuroImaging in python ================================================== See http://nisl.github.com for complete documentation. """ #from . import check_build #from .base import clone try: from numpy.testing import nosetester class NoseTester(nosetester.NoseTester): ...
""" Machine Learning module for NeuroImaging in python ================================================== See http://nisl.github.com for complete documentation. """ try: import numpy except ImportError: print 'Numpy could not be found, please install it properly to use nisl.' try: import scipy except Im...
Add an error message when trying to load nisl without having Numpy, Scipy and Sklearn installed.
Add an error message when trying to load nisl without having Numpy, Scipy and Sklearn installed.
Python
bsd-3-clause
abenicho/isvr
910e1a1762dac1d62c8a6749286c436d6c2b28d9
UM/Operations/RemoveSceneNodeOperation.py
UM/Operations/RemoveSceneNodeOperation.py
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import Operation from UM.Scene.Selection import Selection from UM.Application import Application ## An operation that removes a SceneNode from the scene. class RemoveSceneNodeOperation(Operation.Operation): ...
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import Operation from UM.Scene.Selection import Selection from UM.Application import Application ## An operation that removes a SceneNode from the scene. class RemoveSceneNodeOperation(Operation.Operation): ...
Update convex hull of the group when removing a node from the group
Update convex hull of the group when removing a node from the group CURA-2573
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
a17f711a6e055a9de4674e4c35570a2c6d6f0335
ttysend.py
ttysend.py
from __future__ import print_function import sys import os import fcntl import termios import argparse class RootRequired(Exception): """Our standard exception.""" pass def send(data, tty): """Send each char of data to tty.""" if(os.getuid() != 0): raise RootRequired('Only root can send in...
#!/usr/bin/env python from __future__ import print_function import sys import os import fcntl import termios import argparse class RootRequired(Exception): """Our standard exception.""" pass def send(data, tty): if len(data): # Handle trailing newline if data[-1][-1] != '\n': ...
Move newline handling to a function.
Move newline handling to a function. Allows library users to choose to force trailing newlines.
Python
mit
RichardBronosky/ttysend
782c1b8379d38f99de413398919aa797af0df645
plot_s_curve.py
plot_s_curve.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import matplotlib.pyplot as plt from numpy import array, log import sys x = [] y = [] infile = open(sys.argv[1]) for line in infile: data = line.replace('\n','').split() print(data) try : x.append(float(data[0])) y.append(float(data[1])) ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import matplotlib.pyplot as plt from numpy import array, log import sys import os import matplotlib.animation as animation fig = plt.figure() inpath = sys.argv[1] if os.path.isfile(inpath): print('Visiting {}'.format(inpath)) filenames = [inpath] else: _fil...
Use animation if dirname is provided
Use animation if dirname is provided
Python
mit
M2-AAIS/BAD
3053219149f7dac7ab073fc24488116b1b280b77
money_rounding.py
money_rounding.py
def get_price_without_vat(price_to_show, vat_percent): raise NotImplementedError() def get_price_without_vat_from_other_valuta(conversion_rate, origin_price, origin_vat, other_vat): raise NotImplementedError()
def show_pretty_price(value): raise NotImplementedError()
Use function described in readme
Use function described in readme
Python
mit
coolshop-com/coolshop-application-assignment
ea7200bc9774f69562b37f177ad18ca606998dfa
perfrunner/utils/debug.py
perfrunner/utils/debug.py
import glob import shutil from optparse import OptionParser from perfrunner.helpers.remote import RemoteHelper from perfrunner.settings import ClusterSpec def get_options(): usage = '%prog -c cluster' parser = OptionParser(usage) parser.add_option('-c', dest='cluster_spec_fname', ...
import glob import os.path import shutil from optparse import OptionParser from perfrunner.helpers.remote import RemoteHelper from perfrunner.settings import ClusterSpec def get_options(): usage = '%prog -c cluster' parser = OptionParser(usage) parser.add_option('-c', dest='cluster_spec_fname', ...
Archive logs from the tools
Archive logs from the tools Change-Id: I184473d20cc2763fbc97c993bfcab36b80d1c864 Reviewed-on: http://review.couchbase.org/76571 Tested-by: Build Bot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com> Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com>
Python
apache-2.0
couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner
22e82e3fb6949efe862216feafaedb2da9b19c62
filehandler.py
filehandler.py
import csv import sys import urllib from scheduleitem import ScheduleItem from team import Team def read(uri): """Open a File or a Web URL""" if uri.startswith('http://') or uri.startswith('https://'): return open_url(uri) else: return open_file(uri) def open_url(url): """Return the...
import csv import sys import urllib.error import urllib.request from scheduleitem import ScheduleItem from team import Team def read(uri): """Open a File or a Web URL""" if uri.startswith('http://') or uri.startswith('https://'): return open_url(uri) else: return open_local_file(uri) d...
Update file handlers to use Python3 urllib
Update file handlers to use Python3 urllib
Python
mit
brianjbuck/robie
7b4b2fcbcb9a95c07f09b71305afa0c5ce95fe99
tenant_schemas/routers.py
tenant_schemas/routers.py
from django.conf import settings class TenantSyncRouter(object): """ A router to control which applications will be synced, depending if we are syncing the shared apps or the tenant apps. """ def allow_syncdb(self, db, model): # the imports below need to be done here else django <1.5 goes...
from django.conf import settings class TenantSyncRouter(object): """ A router to control which applications will be synced, depending if we are syncing the shared apps or the tenant apps. """ def allow_migrate(self, db, model): # the imports below need to be done here else django <1.5 goe...
Add database router allow_migrate() for Django 1.7
Add database router allow_migrate() for Django 1.7
Python
mit
goodtune/django-tenant-schemas,Mobytes/django-tenant-schemas,kajarenc/django-tenant-schemas,honur/django-tenant-schemas,mcanaves/django-tenant-schemas,ArtProcessors/django-tenant-schemas,goodtune/django-tenant-schemas,ArtProcessors/django-tenant-schemas,bernardopires/django-tenant-schemas,bernardopires/django-tenant-sc...
b3acf639f310019d042bbe24e653a6f79c240858
setup.py
setup.py
from distutils.core import Extension, setup from Cython.Build import cythonize try: from Cython.Distutils import build_ext except ImportError: use_cython = False else: use_cython = True if use_cython: extensions = [ Extension('mathix.vector', ['mathix/vector.pyx']), ] cmdclass = { ...
from distutils.core import Extension, setup try: from Cython.Distutils import build_ext except ImportError: use_cython = False else: use_cython = True if use_cython: extensions = [ Extension('mathix.vector', ['mathix/vector.pyx']), ] cmdclass = { 'build_ext': build_ext } ...
Remove the importing of the "cythonize" function.
Remove the importing of the "cythonize" function.
Python
mit
PeithVergil/cython-example
d63d391d5b9ee221c0cd67e030895f4598430f08
onetime/models.py
onetime/models.py
from datetime import datetime from django.db import models from django.contrib.auth.models import User class Key(models.Model): user = models.ForeignKey(User) key = models.CharField(max_length=40) created = models.DateTimeField(auto_now_add=True) usage_left = models.IntegerField(null=True, default=1) ...
from datetime import datetime from django.db import models from django.contrib.auth.models import User class Key(models.Model): user = models.ForeignKey(User) key = models.CharField(max_length=40) created = models.DateTimeField(auto_now_add=True) usage_left = models.IntegerField(null=True, default=1) ...
Update key usage when the usage_left counter is still greater than zero.
Update key usage when the usage_left counter is still greater than zero.
Python
bsd-3-clause
uploadcare/django-loginurl,vanschelven/cmsplugin-journal,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,fajran/django-loginurl,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-web...
c8a0f4f439c2123c9b7f9b081f91d75b1f9a8a13
dmoj/checkers/linecount.py
dmoj/checkers/linecount.py
from re import split as resplit from typing import Callable, Union from dmoj.result import CheckerResult from dmoj.utils.unicode import utf8bytes verdict = u"\u2717\u2713" def check(process_output: bytes, judge_output: bytes, point_value: float, feedback: bool = True, match: Callable[[bytes, bytes], bool]...
from re import split as resplit from typing import Callable, Union from dmoj.result import CheckerResult from dmoj.utils.unicode import utf8bytes verdict = u"\u2717\u2713" def check(process_output: bytes, judge_output: bytes, point_value: float, feedback: bool = True, **kwargs) -> Union[CheckerResult, boo...
Remove the match param to fix RCE.
Remove the match param to fix RCE.
Python
agpl-3.0
DMOJ/judge,DMOJ/judge,DMOJ/judge
973641c7d68f4b1505541a06ec46901b412ab56b
tests/test_constraints.py
tests/test_constraints.py
import unittest import numpy as np from constraints import (generate_constraints_function, generate_constraint_gradients_function, ) from robot_arm import RobotArm class TestConstraintFunctions(unittest.TestCase): def setUp(self): self.lengths = (3, 2, 2,) self.destinati...
import unittest import numpy as np from constraints import (generate_constraints_function, generate_constraint_gradients_function, ) from robot_arm import RobotArm class TestConstraintFunctions(unittest.TestCase): def setUp(self): self.lengths = (3, 2, 2,) self.destinati...
Test LICQ condition of constraint gradient
Test LICQ condition of constraint gradient
Python
mit
JakobGM/robotarm-optimization
c8c9c42f14c742c6fcb180b7a3cc1bab1655ac46
projections/simpleexpr.py
projections/simpleexpr.py
import numpy as np import numpy.ma as ma import projections.r2py.reval as reval import projections.r2py.rparser as rparser class SimpleExpr(): def __init__(self, name, expr): self.name = name self.tree = reval.make_inputs(rparser.parse(expr)) lokals = {} exec(reval.to_py(self.tree, name), lokals) ...
import numpy as np import numpy.ma as ma import projections.r2py.reval as reval import projections.r2py.rparser as rparser class SimpleExpr(): def __init__(self, name, expr): self.name = name self.tree = reval.make_inputs(rparser.parse(expr)) lokals = {} exec(reval.to_py(self.tree, name), lokals) ...
Improve determination of array shape for constant expressions
Improve determination of array shape for constant expressions When Evaluating a constant expression, I only used to look at the first column in the df dictionary. But that could also be a constant or expression. So look instead at all columns and find the first numpy array.
Python
apache-2.0
ricardog/raster-project,ricardog/raster-project,ricardog/raster-project,ricardog/raster-project,ricardog/raster-project
632180274abe4cf91f65cf0e84f817dc7124e293
zerver/migrations/0108_fix_default_string_id.py
zerver/migrations/0108_fix_default_string_id.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-08-24 02:39 from __future__ import unicode_literals from django.db import migrations def fix_realm_string_ids(apps, schema_editor): # type: (StateApps, DatabaseSchemaEditor) -> None Realm = apps.get_model('zerver', 'Realm') if Realm.objects.coun...
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-08-24 02:39 from __future__ import unicode_literals from django.db import migrations from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps def fix_realm_string_ids(apps, schema_editor...
Add imports needed for new migration.
mypy: Add imports needed for new migration.
Python
apache-2.0
eeshangarg/zulip,Galexrt/zulip,shubhamdhama/zulip,punchagan/zulip,Galexrt/zulip,tommyip/zulip,brainwane/zulip,tommyip/zulip,zulip/zulip,brainwane/zulip,punchagan/zulip,eeshangarg/zulip,rht/zulip,timabbott/zulip,rht/zulip,zulip/zulip,andersk/zulip,synicalsyntax/zulip,brainwane/zulip,rht/zulip,eeshangarg/zulip,rishig/zul...
91ef89371f7ba99346ba982a3fdb7fc2105a9840
superdesk/users/__init__.py
superdesk/users/__init__.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from .users ...
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from .users ...
Make UsersResource reusable for LDAP
Make UsersResource reusable for LDAP
Python
agpl-3.0
ioanpocol/superdesk-core,plamut/superdesk-core,akintolga/superdesk-core,ancafarcas/superdesk-core,ancafarcas/superdesk-core,nistormihai/superdesk-core,superdesk/superdesk-core,sivakuna-aap/superdesk-core,superdesk/superdesk-core,mdhaman/superdesk-core,petrjasek/superdesk-core,mdhaman/superdesk-core,mugurrus/superdesk-c...
05e19922a5a0f7268ce1a34e25e5deb8e9a2f5d3
sfmtools.py
sfmtools.py
""" Utility functions for PhotoScan processing """ import os, sys import PhotoScan def align_and_clean_photos(chunk): ncameras = len(chunk.cameras) for frame in chunk.frames: frame.matchPhotos() chunk.alignCameras() for camera in chunk.cameras: if camera.transform is None: ...
""" Utility functions for PhotoScan processing """ import os, sys import PhotoScan def align_and_clean_photos(chunk): ncameras = len(chunk.cameras) for frame in chunk.frames: frame.matchPhotos() chunk.alignCameras() for camera in chunk.cameras: if camera.transform is None: ...
Check for trailing slash in path
Check for trailing slash in path
Python
mit
rmsare/sfmtools
0bd84e74a30806f1e317288aa5dee87b4c669790
shcol/config.py
shcol/config.py
# -*- coding: utf-8 -*- # Copyright (c) 2013-2015, Sebastian Linke # Released under the Simplified BSD license # (see LICENSE file for details). """ Constants that are used by `shcol` in many places. This is meant to modified (if needed) only *before* running `shcol`, since most of these constants are only read durin...
# -*- coding: utf-8 -*- # Copyright (c) 2013-2015, Sebastian Linke # Released under the Simplified BSD license # (see LICENSE file for details). """ Constants that are used by `shcol` in many places. This is meant to modified (if needed) only *before* running `shcol`, since most of these constants are only read durin...
Use output stream's encoding (if any). Blindly using UTF-8 would break output on Windows terminals.
Use output stream's encoding (if any). Blindly using UTF-8 would break output on Windows terminals.
Python
bsd-2-clause
seblin/shcol
49a275a268fba520252ee864c39934699c053d13
csunplugged/resources/views/barcode_checksum_poster.py
csunplugged/resources/views/barcode_checksum_poster.py
"""Module for generating Barcode Checksum Poster resource.""" from PIL import Image from utils.retrieve_query_parameter import retrieve_query_parameter def resource_image(request, resource): """Create a image for Barcode Checksum Poster resource. Args: request: HTTP request object (QueryDict). ...
"""Module for generating Barcode Checksum Poster resource.""" from PIL import Image from utils.retrieve_query_parameter import retrieve_query_parameter def resource(request, resource): """Create a image for Barcode Checksum Poster resource. Args: request: HTTP request object (QueryDict). res...
Update barcode resource to new resource specification
Update barcode resource to new resource specification
Python
mit
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
12f3bb8c82b97496c79948d323f7076b6618293a
saleor/graphql/scalars.py
saleor/graphql/scalars.py
from graphene.types import Scalar from graphql.language import ast class AttributesFilterScalar(Scalar): @staticmethod def coerce_filter(value): if isinstance(value, tuple) and len(value) == 2: return ":".join(value) serialize = coerce_filter parse_value = coerce_filter @sta...
from graphene.types import Scalar from graphql.language import ast class AttributesFilterScalar(Scalar): @staticmethod def parse_literal(node): if isinstance(node, ast.StringValue): splitted = node.value.split(":") if len(splitted) == 2: return tuple(splitted) ...
Fix parsing attributes filter values in GraphQL API
Fix parsing attributes filter values in GraphQL API
Python
bsd-3-clause
KenMutemi/saleor,KenMutemi/saleor,jreigel/saleor,itbabu/saleor,maferelo/saleor,maferelo/saleor,jreigel/saleor,jreigel/saleor,HyperManTT/ECommerceSaleor,mociepka/saleor,UITools/saleor,UITools/saleor,maferelo/saleor,car3oon/saleor,itbabu/saleor,UITools/saleor,HyperManTT/ECommerceSaleor,car3oon/saleor,car3oon/saleor,UIToo...
5b8ff4276fbe92d5ccd5fa63fecccc5ff7d571a9
quokka/core/tests/test_models.py
quokka/core/tests/test_models.py
# coding: utf-8 from . import BaseTestCase from ..models import Channel class TestCoreModels(BaseTestCase): def setUp(self): # Create method was not returning the created object with # the create() method self.channel, new = Channel.objects.get_or_create( title=u'Monkey Island...
# coding: utf-8 from . import BaseTestCase from ..models import Channel class TestChannel(BaseTestCase): def setUp(self): # Create method was not returning the created object with # the create() method self.parent, new = Channel.objects.get_or_create( title=u'Father', ...
Add more core tests / Rename test
Add more core tests / Rename test
Python
mit
romulocollopy/quokka,felipevolpone/quokka,lnick/quokka,ChengChiongWah/quokka,felipevolpone/quokka,wushuyi/quokka,wushuyi/quokka,cbeloni/quokka,felipevolpone/quokka,CoolCloud/quokka,ChengChiongWah/quokka,lnick/quokka,romulocollopy/quokka,Ckai1991/quokka,cbeloni/quokka,CoolCloud/quokka,alexandre/quokka,felipevolpone/quok...
3037562643bc1ddaf081a6fa9c757aed4101bb53
robots/urls.py
robots/urls.py
try: from django.conf.urls import patterns, url except ImportError: from django.conf.urls.defaults import patterns, url urlpatterns = patterns( 'robots.views', url(r'^$', 'rules_list', name='robots_rule_list'), )
from django.conf.urls import url from robots.views import rules_list urlpatterns = [ url(r'^$', rules_list, name='robots_rule_list'), ]
Fix warnings about URLconf in Django 1.9
Fix warnings about URLconf in Django 1.9 * django.conf.urls.patterns will be removed in Django 1.10 * Passing a dotted path and not a view function will be deprecated in Django 1.10
Python
bsd-3-clause
jezdez/django-robots,jezdez/django-robots,jscott1971/django-robots,jscott1971/django-robots,jazzband/django-robots,jazzband/django-robots
76243416f36a932c16bee93cc753de3d71168f0b
manager/__init__.py
manager/__init__.py
import os from flask import Flask from flask.ext.assets import Bundle, Environment from flask.ext.login import LoginManager from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) # Load the app config app.config.from_object("config.Config") assets = Environment(app) db= SQLAlchemy(app) login = LoginMana...
import os from flask import Flask from flask.ext.assets import Bundle, Environment from flask.ext.login import LoginManager from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) # Load the app config app.config.from_object("config.Config") assets = Environment(app) db= SQLAlchemy(app) login = LoginMana...
Add user table to module init
Add user table to module init
Python
mit
hreeder/ignition,hreeder/ignition,hreeder/ignition
aba5ae9736b064fd1e3541de3ef36371d92fc875
RandoAmisSecours/admin.py
RandoAmisSecours/admin.py
# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2013 Rémi Duraffort # This file is part of RandoAmisSecours. # # RandoAmisSecours is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of...
# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2013 Rémi Duraffort # This file is part of RandoAmisSecours. # # RandoAmisSecours is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of...
Fix import when using python3.3
Fix import when using python3.3
Python
agpl-3.0
ivoire/RandoAmisSecours,ivoire/RandoAmisSecours
b9e1b34348444c4c51c8fd30ff7882552e21939b
temba/msgs/migrations/0094_auto_20170501_1641.py
temba/msgs/migrations/0094_auto_20170501_1641.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-05-01 16:41 from __future__ import unicode_literals from django.db import migrations, models import temba.utils.models class Migration(migrations.Migration): dependencies = [ ('msgs', '0093_populate_translatables'), ] operations = [ ...
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-05-01 16:41 from __future__ import unicode_literals from django.db import migrations, models import temba.utils.models class Migration(migrations.Migration): dependencies = [ ('msgs', '0093_populate_translatables'), ] operations = [ ...
Change order of operations within migration so breaking schema changes come last
Change order of operations within migration so breaking schema changes come last
Python
agpl-3.0
pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro
3c9da01bee3d157e344f3ad317b777b3977b2e4d
account_invoice_start_end_dates/models/account_move.py
account_invoice_start_end_dates/models/account_move.py
# Copyright 2019 Akretion France <https://akretion.com/> # @author: Alexis de Lattre <alexis.delattre@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, models from odoo.exceptions import UserError class AccountMove(models.Model): _inherit = "account.move" def ...
# Copyright 2019 Akretion France <https://akretion.com/> # @author: Alexis de Lattre <alexis.delattre@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, models from odoo.exceptions import UserError class AccountMove(models.Model): _inherit = "account.move" def ...
Use super() instead of super(classname, self)
Use super() instead of super(classname, self)
Python
agpl-3.0
OCA/account-closing,OCA/account-closing
d0919465239399f1ab6d65bbd8c42b1b9657ddb6
scripts/utils.py
scripts/utils.py
#!/usr/bin/env python3 # Touhou Community Reliant Automatic Patcher # Scripts # # ---- # """Utility functions shared among all the scripts.""" from collections import OrderedDict import json import os json_load_params = { 'object_pairs_hook': OrderedDict } def patch_files_filter(files): """Filters all file ...
#!/usr/bin/env python3 # Touhou Community Reliant Automatic Patcher # Scripts # # ---- # """Utility functions shared among all the scripts.""" from collections import OrderedDict import json import os json_load_params = { 'object_pairs_hook': OrderedDict } def patch_files_filter(files): """Filters all file ...
Allow to override the JSON loading and dumping parameters.
scripts: Allow to override the JSON loading and dumping parameters.
Python
unlicense
VBChunguk/thcrap,thpatch/thcrap,VBChunguk/thcrap,thpatch/thcrap,thpatch/thcrap,thpatch/thcrap,thpatch/thcrap,VBChunguk/thcrap
b0254fd4090c0d17f60a87f3fe5fe28c0382310e
scripts/v0to1.py
scripts/v0to1.py
#!/usr/bin/env python import sys import h5py infiles = sys.argv[1:] for infile in infiles: with h5py.File(infile, 'a') as h5: print(infile) if 'format-version' in h5.attrs and h5.attrs['format-version'] < 1: if 'matrix' in h5 and not 'pixels' in h5: print('renaming mat...
#!/usr/bin/env python import sys import h5py infiles = sys.argv[1:] for infile in infiles: with h5py.File(infile, 'a') as h5: print(infile) if 'format-version' in h5.attrs and h5.attrs['format-version'] < 1: if 'matrix' in h5 and not 'pixels' in h5: print('renaming mat...
Drop old names from v0
Drop old names from v0
Python
bsd-3-clause
mirnylab/cooler
43350965e171e6a3bfd89af3dd192ab5c9281b3a
vumi/blinkenlights/tests/test_message20110818.py
vumi/blinkenlights/tests/test_message20110818.py
from twisted.trial.unittest import TestCase import vumi.blinkenlights.message20110818 as message import time class TestMessage(TestCase): def test_to_dict(self): now = time.time() datapoint = ("vumi.w1.a_metric", now, 1.5) msg = message.MetricMessage() msg.append(datapoint) ...
from twisted.trial.unittest import TestCase import vumi.blinkenlights.message20110818 as message import time class TestMessage(TestCase): def test_to_dict(self): now = time.time() datapoint = ("vumi.w1.a_metric", now, 1.5) msg = message.MetricMessage() msg.append(datapoint) ...
Add test for extend method.
Add test for extend method.
Python
bsd-3-clause
TouK/vumi,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,TouK/vumi,harrissoerja/vumi,TouK/vumi,harrissoerja/vumi,harrissoerja/vumi
159d09e18dc3b10b7ba3c104a2761f300d50ff28
organizer/models.py
organizer/models.py
from django.db import models # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Tag(models.Model): name = models.CharField( max_length=31, unique=True) slug = models.SlugField( max_length=31, unique=True, help_text='A label for URL config...
from django.db import models # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Tag(models.Model): name = models.CharField( max_length=31, unique=True) slug = models.SlugField( max_length=31, unique=True, help_text='A label for URL config...
Add options to NewsLink model fields.
Ch03: Add options to NewsLink model fields. [skip ci] Field options allow us to easily customize behavior of a field. Verbose name documentation: https://docs.djangoproject.com/en/1.8/ref/models/fields/#verbose-name https://docs.djangoproject.com/en/1.8/topics/db/models/#verbose-field-names The max_length f...
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
761fbb68f72ff8f425ad40670ea908b4959d3292
specchio/main.py
specchio/main.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import time from watchdog.observers import Observer from specchio.handlers import SpecchioEventHandler from specchio.utils import init_logger, logger def main(): """Main function for specchio Example: specchio test/ user@host:test/ :return: Non...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import time from watchdog.observers import Observer from specchio.handlers import SpecchioEventHandler from specchio.utils import init_logger, logger def main(): """Main function for specchio Example: specchio test/ user@host:test/ :return: Non...
Fix the output when there is wrong usage
Fix the output when there is wrong usage
Python
mit
brickgao/specchio
34960807eac1818a8167ff015e941c42be8827da
checkenv.py
checkenv.py
from colorama import Fore from pkgutil import iter_modules def check_import(packagename): """ Checks that a package is present. Returns true if it is available, and false if not available. """ if packagename in (name for _, name, _ in iter_modules()): return True else: return F...
from colorama import Fore, Style from pkgutil import iter_modules def check_import(packagename): """ Checks that a package is present. Returns true if it is available, and false if not available. """ if packagename in (name for _, name, _ in iter_modules()): return True else: r...
Reset colors at the end
Reset colors at the end
Python
mit
ericmjl/data-testing-tutorial,ericmjl/data-testing-tutorial
dfa752590c944fc07253c01c3d99b640a46dae1d
jinja2_time/jinja2_time.py
jinja2_time/jinja2_time.py
# -*- coding: utf-8 -*- import arrow from jinja2 import nodes from jinja2.ext import Extension class TimeExtension(Extension): tags = set(['now']) def __init__(self, environment): super(TimeExtension, self).__init__(environment) # add the defaults to the environment environment.ext...
# -*- coding: utf-8 -*- import arrow from jinja2 import nodes from jinja2.ext import Extension class TimeExtension(Extension): tags = set(['now']) def __init__(self, environment): super(TimeExtension, self).__init__(environment) # add the defaults to the environment environment.ext...
Implement parser method for optional offset
Implement parser method for optional offset
Python
mit
hackebrot/jinja2-time
d68f28581cd3c3f57f7c41adbd65676887a51136
opps/channels/tests/test_forms.py
opps/channels/tests/test_forms.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.test import TestCase from django.contrib.sites.models import Site from django.contrib.auth import get_user_model from opps.channels.models import Channel from opps.channels.forms import ChannelAdminForm class ChannelFormTest(TestCase): def setUp(self): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.test import TestCase from django.contrib.sites.models import Site from django.contrib.auth import get_user_model from opps.channels.models import Channel from opps.channels.forms import ChannelAdminForm class ChannelFormTest(TestCase): def setUp(self): ...
Add test check readonly field slug of channel
Add test check readonly field slug of channel
Python
mit
jeanmask/opps,opps/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,williamroot/opps,opps/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,opps/opps,jeanmask/opps,opps/opps
b97115679929dfe4f69618f756850617f265048f
service/pixelated/config/site.py
service/pixelated/config/site.py
from twisted.web.server import Site, Request class AddCSPHeaderRequest(Request): CSP_HEADER_VALUES = "default-src 'self'; style-src 'self' 'unsafe-inline'" def process(self): self.setHeader('Content-Security-Policy', self.CSP_HEADER_VALUES) self.setHeader('X-Content-Security-Policy', self.CSP...
from twisted.web.server import Site, Request class AddSecurityHeadersRequest(Request): CSP_HEADER_VALUES = "default-src 'self'; style-src 'self' 'unsafe-inline'" def process(self): self.setHeader('Content-Security-Policy', self.CSP_HEADER_VALUES) self.setHeader('X-Content-Security-Policy', se...
Rename class to match intent
Rename class to match intent
Python
agpl-3.0
pixelated-project/pixelated-user-agent,pixelated/pixelated-user-agent,pixelated-project/pixelated-user-agent,pixelated-project/pixelated-user-agent,pixelated-project/pixelated-user-agent,pixelated/pixelated-user-agent,pixelated-project/pixelated-user-agent,pixelated/pixelated-user-agent,pixelated/pixelated-user-agent,p...
4b245b9a859552adb9c19fafc4bdfab5780782f2
d1_common_python/src/d1_common/__init__.py
d1_common_python/src/d1_common/__init__.py
# -*- coding: utf-8 -*- # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2016 DataONE # # Licensed under the Apache License, Version 2.0 ...
# -*- coding: utf-8 -*- # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2016 DataONE # # Licensed under the Apache License, Version 2.0 ...
Add logging NullHandler to prevent "no handler found" errors
Add logging NullHandler to prevent "no handler found" errors This fixes the issue where "no handler found" errors would be printed by the library if library clients did not set up logging.
Python
apache-2.0
DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python
af8a96e08029e2dc746cfa1ecbd7a6d02be1c374
InvenTree/company/forms.py
InvenTree/company/forms.py
""" Django Forms for interacting with Company app """ # -*- coding: utf-8 -*- from __future__ import unicode_literals from InvenTree.forms import HelperForm from .models import Company from .models import SupplierPart from .models import SupplierPriceBreak class EditCompanyForm(HelperForm): """ Form for editin...
""" Django Forms for interacting with Company app """ # -*- coding: utf-8 -*- from __future__ import unicode_literals from InvenTree.forms import HelperForm from .models import Company from .models import SupplierPart from .models import SupplierPriceBreak class EditCompanyForm(HelperForm): """ Form for editin...
Add option to edit currency
Add option to edit currency
Python
mit
SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree
824c46b7d3953e1933a72def4edf058a577487ea
byceps/services/attendance/transfer/models.py
byceps/services/attendance/transfer/models.py
""" byceps.services.attendance.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from attr import attrib, attrs from ....services.seating.models.seat import Seat from ....services.user.models.user import User @...
""" byceps.services.attendance.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from dataclasses import dataclass from ....services.seating.models.seat import Seat from ....services.user.models.user import User ...
Use `dataclass` instead of `attr` for attendance model
Use `dataclass` instead of `attr` for attendance model
Python
bsd-3-clause
m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps
7d52ee6030b2e59a6b6cb6dce78686e8d551281b
examples/horizontal_boxplot.py
examples/horizontal_boxplot.py
""" Horizontal boxplot with observations ==================================== _thumb: .7, .37 """ import numpy as np import seaborn as sns import matplotlib.pyplot as plt sns.set(style="ticks") # Initialize the figure f, ax = plt.subplots(figsize=(7, 6)) ax.set_xscale("log") # Load the example planets dataset planet...
""" Horizontal boxplot with observations ==================================== _thumb: .7, .37 """ import numpy as np import seaborn as sns import matplotlib.pyplot as plt sns.set(style="ticks") # Initialize the figure with a logarithmic x axis f, ax = plt.subplots(figsize=(7, 6)) ax.set_xscale("log") # Load the exa...
Fix comments in horizontal boxplot example
Fix comments in horizontal boxplot example
Python
bsd-3-clause
mwaskom/seaborn,phobson/seaborn,arokem/seaborn,lukauskas/seaborn,anntzer/seaborn,arokem/seaborn,sauliusl/seaborn,mwaskom/seaborn,phobson/seaborn,petebachant/seaborn,anntzer/seaborn,lukauskas/seaborn
ca4be3892ec0c1b5bc337a9fae10503b5f7f765a
bika/lims/browser/validation.py
bika/lims/browser/validation.py
from Products.Archetypes.browser.validation import InlineValidationView as _IVV from Acquisition import aq_inner from Products.CMFCore.utils import getToolByName import json SKIP_VALIDATION_FIELDTYPES = ('image', 'file', 'datetime', 'reference') class InlineValidationView(_IVV): def __call__(self, uid, fname, v...
from Products.Archetypes.browser.validation import InlineValidationView as _IVV from Acquisition import aq_inner from Products.CMFCore.utils import getToolByName import json SKIP_VALIDATION_FIELDTYPES = ('image', 'file', 'datetime', 'reference') class InlineValidationView(_IVV): def __call__(self, uid, fname, v...
Revert "Inline Validation fails silently if request is malformed"
Revert "Inline Validation fails silently if request is malformed" This reverts commit 723e4eb603568d3a60190d8d292cc335a74b79d5.
Python
agpl-3.0
labsanmartin/Bika-LIMS,veroc/Bika-LIMS,veroc/Bika-LIMS,rockfruit/bika.lims,veroc/Bika-LIMS,labsanmartin/Bika-LIMS,anneline/Bika-LIMS,DeBortoliWines/Bika-LIMS,DeBortoliWines/Bika-LIMS,anneline/Bika-LIMS,DeBortoliWines/Bika-LIMS,anneline/Bika-LIMS,rockfruit/bika.lims,labsanmartin/Bika-LIMS
6949339cda8c60b74341f854d9a00aa8abbfe4d5
test/level_sets_measure_test.py
test/level_sets_measure_test.py
__author__ = 'intsco' import cPickle from engine.pyIMS.image_measures.level_sets_measure import measure_of_chaos_dict from unittest import TestCase import unittest from os.path import join, realpath, dirname class MeasureOfChaosDictTest(TestCase): def setUp(self): self.rows, self.cols = 65, 65 s...
import unittest import numpy as np from ..image_measures.level_sets_measure import measure_of_chaos, _nan_to_zero class MeasureOfChaosTest(unittest.TestCase): def test__nan_to_zero_with_ge_zero(self): ids = ( np.zeros(1), np.ones(range(1, 10)), np.arange(1024 * 1024) ...
Implement first tests for _nan_to_zero
Implement first tests for _nan_to_zero - Remove outdated dict test class - write some test methods
Python
apache-2.0
andy-d-palmer/pyIMS,alexandrovteam/pyImagingMSpec
12f4b26d98c3ba765a11efeca3b646b5e9d0a0fb
running.py
running.py
import tcxparser from configparser import ConfigParser from datetime import datetime import urllib.request import dateutil.parser t = '1984-06-02T19:05:00.000Z' # Darksky weather API # Create config file manually parser = ConfigParser() parser.read('slowburn.config', encoding='utf-8') darksky_key = parser.get('darksky...
import tcxparser from configparser import ConfigParser from datetime import datetime import urllib.request import dateutil.parser t = '1984-06-02T19:05:00.000Z' # Darksky weather API # Create config file manually parser = ConfigParser() parser.read('slowburn.config', encoding='utf-8') darksky_key = parser.get('darksky...
Use TCX coordinates to fetch local weather
Use TCX coordinates to fetch local weather
Python
mit
briansuhr/slowburn
5a7b13e26e94d03bc92600d9c24b3b2e8bc4321c
dstar_lib/aprsis.py
dstar_lib/aprsis.py
import aprslib import logging import nmea class AprsIS: logger = None def __init__(self, callsign, password): self.logger = logging.getLogger(__name__) self.aprs_connection = aprslib.IS(callsign, password) self.aprs_connection.connect() def send_beacon(self, callsign, sfx, message, gpgga): position = nm...
import aprslib import logging import nmea class AprsIS: logger = None def __init__(self, callsign, password): self.logger = logging.getLogger(__name__) self.aprs_connection = aprslib.IS(callsign, password) self.aprs_connection.connect() def send_beacon(self, callsign, sfx, message, gpgga): position = nm...
Fix an issue with the new aprslib
Fix an issue with the new aprslib
Python
mit
elielsardanons/dstar_sniffer,elielsardanons/dstar_sniffer
132b148ca8701ee867b7a08432a3595a213ce470
cedexis/radar/tests/test_cli.py
cedexis/radar/tests/test_cli.py
import unittest import types import cedexis.radar.cli class TestCommandLineInterface(unittest.TestCase): def test_main(self): self.assertTrue(isinstance(cedexis.radar.cli.main, types.FunctionType))
import unittest from unittest.mock import patch, MagicMock, call import types from pprint import pprint import cedexis.radar.cli class TestCommandLineInterface(unittest.TestCase): def test_main(self): self.assertTrue(isinstance(cedexis.radar.cli.main, types.FunctionType)) @patch('logging.getLogger')...
Add unit test for overrides
Add unit test for overrides
Python
mit
cedexis/cedexis.radar
70f167d3d5a7540fb3521b82ec70bf7c6db09a99
tests/test_contrib.py
tests/test_contrib.py
from __future__ import print_function import cooler.contrib.higlass as cch import h5py import os.path as op testdir = op.realpath(op.dirname(__file__)) def test_data_retrieval(): data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000kb.multires.cool') f = h5py.File(data_fil...
from __future__ import print_function import cooler.contrib.higlass as cch import cooler.contrib.recursive_agg_onefile as ra import h5py import os.path as op testdir = op.realpath(op.dirname(__file__)) def test_data_retrieval(): data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000...
Add test for recursive agg
Add test for recursive agg
Python
bsd-3-clause
mirnylab/cooler
27a0165d45f52114ebb65d59cf8e4f84f3232881
tests/test_lattice.py
tests/test_lattice.py
import rml.lattice def test_create_lattice(): l = rml.lattice.Lattice() assert(len(l)) == 0 def test_non_negative_lattice(): l = rml.lattice.Lattice() assert(len(l)) >= 0
import rml.lattice import rml.element def test_create_lattice(): l = rml.lattice.Lattice() assert(len(l)) == 0 def test_non_negative_lattice(): l = rml.lattice.Lattice() assert(len(l)) >= 0 def test_lattice_with_one_element(): l = rml.lattice.Lattice() element_length = 1.5 e = rml.eleme...
Test simple lattice with one element.
Test simple lattice with one element.
Python
apache-2.0
willrogers/pml,willrogers/pml,razvanvasile/RML
7591189527ad05be62a561afadf70b217d725b1f
scrapi/processing/osf/__init__.py
scrapi/processing/osf/__init__.py
from scrapi.processing.osf import crud from scrapi.processing.osf import collision from scrapi.processing.base import BaseProcessor class OSFProcessor(BaseProcessor): NAME = 'osf' def process_normalized(self, raw_doc, normalized): if crud.is_event(normalized): crud.create_event(normalized...
from scrapi.processing.osf import crud from scrapi.processing.osf import collision from scrapi.processing.base import BaseProcessor class OSFProcessor(BaseProcessor): NAME = 'osf' def process_normalized(self, raw_doc, normalized): if crud.is_event(normalized): crud.create_event(normalized...
Make sure to keep certain report fields out of resources
Make sure to keep certain report fields out of resources
Python
apache-2.0
alexgarciac/scrapi,erinspace/scrapi,icereval/scrapi,mehanig/scrapi,felliott/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi,mehanig/scrapi,ostwald/scrapi,fabianvf/scrapi,CenterForOpenScience/scrapi,felliott/scrapi,jeffreyliu3230/scrapi
166e0980fc20b507763395297e8a67c7dcb3a3da
examples/neural_network_inference/onnx_converter/small_example.py
examples/neural_network_inference/onnx_converter/small_example.py
import torch import torch.nn as nn import torch.nn.functional as F from onnx_coreml import convert # Step 0 - (a) Define ML Model class small_model(nn.Module): def __init__(self): super(small_model, self).__init__() self.fc1 = nn.Linear(768, 256) self.fc2 = nn.Linear(256, 10) def forwa...
import torch import torch.nn as nn import torch.nn.functional as F from onnx_coreml import convert # Step 0 - (a) Define ML Model class small_model(nn.Module): def __init__(self): super(small_model, self).__init__() self.fc1 = nn.Linear(768, 256) self.fc2 = nn.Linear(256, 10) def forwa...
Update the example with latest interface
Update the example with latest interface Update the example with the latest interface of the function "convert"
Python
bsd-3-clause
apple/coremltools,apple/coremltools,apple/coremltools,apple/coremltools
967ea6b083437cbe6c87b173567981e1ae41fefc
project/wsgi/tomodev.py
project/wsgi/tomodev.py
""" WSGI config for project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting....
""" WSGI config for project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting....
Set Python path inside WSGI application
Set Python path inside WSGI application
Python
agpl-3.0
ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,matijapretnar/projekt-tomo,matijapretnar/projekt-tomo
2198ae847cb257d210c043bb08d52206df749a24
Jeeves/jeeves.py
Jeeves/jeeves.py
import discord import asyncio import random import configparser import json def RunBot(config_file): config = configparser.ConfigParser() config.read(config_file) client = discord.Client() @client.event async def on_ready(): print('------') print('Logged in as %s (%s)' % (client.u...
import discord import asyncio import random import configparser import json def RunBot(config_file): config = configparser.ConfigParser() config.read(config_file) client = discord.Client() @client.event async def on_ready(): print('------') print('Logged in as %s (%s)' % (client.u...
Change knugen command to use array in config/data.json instead of hardcoded array.
Change knugen command to use array in config/data.json instead of hardcoded array.
Python
mit
havokoc/MyManJeeves
74728ef66fd13bfd7ad01f930114c2375e752d13
examples/skel.py
examples/skel.py
try: import _path except NameError: pass import pygame import spyral import sys SIZE = (640, 480) BG_COLOR = (0, 0, 0) class Game(spyral.Scene): """ A Scene represents a distinct state of your game. They could be menus, different subgames, or any other things which are mostly distinct. A ...
try: import _path except NameError: pass import pygame import spyral import sys SIZE = (640, 480) BG_COLOR = (0, 0, 0) class Game(spyral.Scene): """ A Scene represents a distinct state of your game. They could be menus, different subgames, or any other things which are mostly distinct. A ...
Remove some accidentally committed code.
Remove some accidentally committed code.
Python
lgpl-2.1
platipy/spyral
b881247b182a45774ed494146904dcf2b1826d5e
sla_bot.py
sla_bot.py
import discord import asyncio client = discord.Client() @client.event async def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id) print('------') @client.event async def on_message(message): if message.content.startswith('!test'): await client.send_message(me...
import asyncio import discord from discord.ext import commands bot = commands.Bot(command_prefix='!', description='test') @bot.event async def on_ready(): print('Logged in as') print(bot.user.name) print(bot.user.id) print('------') @bot.command() async def test(): await bot.say('Hello W...
Switch to Bot object instead of Client
Switch to Bot object instead of Client Better reflects examples in discord.py project
Python
mit
EsqWiggles/SLA-bot,EsqWiggles/SLA-bot
e4d746ba6c5b842529c9dafb31a90bdd31fee687
performanceplatform/__init__.py
performanceplatform/__init__.py
# Namespace package: https://docs.python.org/2/library/pkgutil.html try: import pkg_resources pkg_resources.declare_namespace(__name__) except ImportError: from pkgutil import extend_path __path__ = extend_path(__path__, __name__)
__import__('pkg_resources').declare_namespace(__name__)
Fix namespacing for PyPi installs
Fix namespacing for PyPi installs See https://github.com/alphagov/performanceplatform-client/pull/5
Python
mit
alphagov/performanceplatform-collector,alphagov/performanceplatform-collector,alphagov/performanceplatform-collector