commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
81246153033d38132903759cb7e33cf86c26a548 | Make sure HH:MM values are allowed | michaelrice/graphite-api,alphapigger/graphite-api,Knewton/graphite-api,vladimir-smirnov-sociomantic/graphite-api,hubrick/graphite-api,GeorgeJahad/graphite-api,absalon-james/graphite-api,raintank/graphite-api,winguru/graphite-api,DaveBlooman/graphite-api,absalon-james/graphite-api,alphapigger/graphite-api,raintank/graph... | tests/test_attime.py | tests/test_attime.py | import datetime
import time
from graphite_api.render.attime import parseATTime
from . import TestCase
class AtTestCase(TestCase):
def test_parse(self):
for value in [
str(int(time.time())),
'20140319',
'20130319+1y',
'20130319+1mon',
'20130319+... | import datetime
import time
from graphite_api.render.attime import parseATTime
from . import TestCase
class AtTestCase(TestCase):
def test_parse(self):
for value in [
str(int(time.time())),
'20140319',
'20130319+1y',
'20130319+1mon',
'20130319+... | apache-2.0 | Python |
9cacbe61d8161f3bd2135f01c19a95fdb27e4597 | add avatar test | happyraul/tv | tests/test_basics.py | tests/test_basics.py | import unittest
from flask import current_app
from app import create_app, db
from app.models import User
class BasicsTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('test')
self.app_context = self.app.app_context()
self.app_context.push()
db.create_al... | import unittest
from flask import current_app
from app import create_app, db
class BasicsTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('test')
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
def tearDown(self):
... | apache-2.0 | Python |
21d45e38d07a413aeeb19e10a68e540d1f6d5851 | Remove last references to flatpage so it doesnt show up on admin page | tic-ull/portal-del-investigador,tic-ull/portal-del-investigador,tic-ull/portal-del-investigador,tic-ull/portal-del-investigador | core/forms.py | core/forms.py | # -*- encoding: UTF-8 -*-
from core import settings as stCore
from django import forms
from django.conf import settings as st
from flatpages_i18n.forms import FlatpageForm
from django.contrib.sites.models import Site
from django.forms.widgets import HiddenInput, MultipleHiddenInput
class PageForm(FlatpageForm):
... | # -*- encoding: UTF-8 -*-
from core import settings as stCore
from django import forms
from django.conf import settings as st
from django.contrib.flatpages.admin import FlatpageForm
from django.contrib.sites.models import Site
from django.forms.widgets import HiddenInput, MultipleHiddenInput
class PageForm(FlatpageF... | agpl-3.0 | Python |
0cd0763a0dfaeb564866680fd2314223c9f0a635 | Test cache type | lord63/me-api | tests/test_config.py | tests/test_config.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from me_api.app import create_app
from me_api.configs import DevelopConfig, ProductionConfig, TestingConfig
def test_develop_config():
app = create_app(DevelopConfig)
assert app.config['DEBUG'] is True
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from me_api.app import create_app
from me_api.configs import DevelopConfig, ProductionConfig, TestingConfig
def test_develop_config():
app = create_app(DevelopConfig)
assert app.config['DEBUG'] is True
d... | mit | Python |
ac0f0780beb61cab95809b2e0d02e5dab481e225 | Add py solution for 678. Valid Parenthesis String | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | py/valid-parenthesis-string.py | py/valid-parenthesis-string.py | class Solution(object):
def checkValidString(self, s):
"""
:type s: str
:rtype: bool
"""
lowest, highest = 0, 0
for c in s:
if c == '(':
lowest += 1
highest += 1
elif c == ')':
if lowest > 0:
... | from collections import Counter
class Solution(object):
def dfs(self, s, pos, stack):
if stack + self.min_possible_opening[-1] - self.min_possible_opening[pos] > self.max_possible_closing[-1] - self.max_possible_closing[pos]:
return False
if stack + self.max_possible_opening[-1] - self.m... | apache-2.0 | Python |
0087867be1a299d78361b76f7b1a628597502eb5 | Fix TestAnonymousAccessControl (#1035) | intel-hpdd/intel-manager-for-lustre,intel-hpdd/intel-manager-for-lustre,intel-hpdd/intel-manager-for-lustre | tests/integration/shared_storage_configuration/test_anonymous_access_control.py | tests/integration/shared_storage_configuration/test_anonymous_access_control.py | from testconfig import config
from django.utils.unittest import skip
from tests.integration.core.chroma_integration_testcase import ChromaIntegrationTestCase
class TestAnonymousAccessControl(ChromaIntegrationTestCase):
manager = config["chroma_managers"][0]
SETTINGS_DIR = "/usr/share/chroma-manager"
de... | from testconfig import config
from django.utils.unittest import skip
from tests.integration.core.chroma_integration_testcase import ChromaIntegrationTestCase
class TestAnonymousAccessControl(ChromaIntegrationTestCase):
manager = config["chroma_managers"][0]
SETTINGS_DIR = "/usr/share/chroma-manager"
de... | mit | Python |
a135a19960d77951c49f72ecbd9ddd88a86b2efc | Initialize mailchimp properly. | stefanhahmann/pybossa,geotagx/pybossa,PyBossa/pybossa,PyBossa/pybossa,jean/pybossa,OpenNewsLabs/pybossa,jean/pybossa,stefanhahmann/pybossa,OpenNewsLabs/pybossa,inteligencia-coletiva-lsd/pybossa,inteligencia-coletiva-lsd/pybossa,geotagx/pybossa,Scifabric/pybossa,Scifabric/pybossa | pybossa/newsletter/__init__.py | pybossa/newsletter/__init__.py | # -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2014 SF Isle of Man Limited
#
# PyBossa is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at... | # -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2014 SF Isle of Man Limited
#
# PyBossa is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at... | agpl-3.0 | Python |
655020d7382e22b585cf29f6ad75b321d625a309 | change tempfile.tempdir to tempfile.gettempdir() | MSLNZ/msl-package-manager | tests/test_create.py | tests/test_create.py | import os
import pytest
import shutil
import tempfile
import msl.package_manager as pm
def test_create():
filename = 'akjdSKmkmklmKMgvrd4ESExKOKuh'
pm.create(names=filename, author='Joe', email='a.b@c.com', path=tempfile.gettempdir())
path = os.path.join(tempfile.gettempdir(), 'msl-'+filename)
assert... | import os
import pytest
import shutil
import tempfile
import msl.package_manager as pm
def test_create():
filename = 'akjdSKmkmklmKMgvrd4ESExKOKuh'
pm.create(names=filename, author='Joe', email='a.b@c.com', path=tempfile.gettempdir())
path = os.path.join(tempfile.tempdir, 'msl-'+filename)
assert os.p... | mit | Python |
2a68b28933fac820a257b31e15216543cca244fc | add tests for Collection metadata | Kitware/girder,manthey/girder,jbeezley/girder,RafaelPalomar/girder,RafaelPalomar/girder,jbeezley/girder,girder/girder,girder/girder,girder/girder,manthey/girder,jbeezley/girder,Kitware/girder,Kitware/girder,RafaelPalomar/girder,Kitware/girder,RafaelPalomar/girder,jbeezley/girder,RafaelPalomar/girder,manthey/girder,gird... | test/test_collection.py | test/test_collection.py | import pytest
import json
from girder.models.collection import Collection
from pytest_girder.assertions import assertStatusOk
@pytest.fixture
def collections(db):
yield [
Collection().createCollection('private collection', public=False),
Collection().createCollection('public collection', public=T... | import pytest
from girder.models.collection import Collection
from pytest_girder.assertions import assertStatusOk
@pytest.fixture
def collections(db):
yield [
Collection().createCollection('private collection', public=False),
Collection().createCollection('public collection', public=True)
]
... | apache-2.0 | Python |
7ae0fcbec2dd7c3525a232b2bea019451b92cadc | Add test for url property of Thumbnail | relekang/python-thumbnails,python-thumbnails/python-thumbnails | tests/test_images.py | tests/test_images.py | # -*- coding: utf-8 -*-
import os
import unittest
from thumbnails.images import Thumbnail
class ThumbnailTestCase(unittest.TestCase):
def setUp(self):
self.instance = Thumbnail(['n', 'ame'])
self.instance.size = 200, 400
def test_name(self):
self.assertEqual(self.instance.name, 'n/a... | # -*- coding: utf-8 -*-
import os
import unittest
from thumbnails.images import Thumbnail
class ThumbnailTestCase(unittest.TestCase):
def setUp(self):
self.instance = Thumbnail(['n', 'ame'])
self.instance.size = 200, 400
def test_name(self):
self.assertEqual(self.instance.name, 'n/a... | mit | Python |
c6ba25a5dc73e84a7a3948893faeb5afc839e788 | remove unsed import | mupi/timtec,AllanNozomu/tecsaladeaula,AllanNozomu/tecsaladeaula,hacklabr/timtec,virgilio/timtec,mupi/timtec,virgilio/timtec,hacklabr/timtec,mupi/timtec,mupi/tecsaladeaula,GustavoVS/timtec,GustavoVS/timtec,virgilio/timtec,mupi/escolamupi,mupi/tecsaladeaula,mupi/escolamupi,AllanNozomu/tecsaladeaula,GustavoVS/timtec,hackl... | tests/test_models.py | tests/test_models.py | import pytest
from os.path import join, dirname
from model_mommy import mommy
from django.core.files.base import ContentFile
from core.models import TimtecUser, CourseStudent
@pytest.mark.django_db
def test_lesson_counts(settings):
lesson = mommy.make('Lesson')
video = mommy.make('Video')
activity = momm... | import pytest
from os.path import join, dirname
from model_mommy import mommy
from django.core.files.base import ContentFile
from core.models import TimtecUser, Course, CourseStudent
@pytest.mark.django_db
def test_lesson_counts(settings):
lesson = mommy.make('Lesson')
video = mommy.make('Video')
activit... | agpl-3.0 | Python |
d43f07de64907f0f0487516d7bb850e0688af074 | append default domain when sign up as a user. | tobyqin/testcube,tobyqin/testcube,tobyqin/testcube,tobyqin/testcube | testcube/users/forms.py | testcube/users/forms.py | from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from testcube.utils import get_domain
class SignUpForm(UserCreationForm):
email = forms.EmailField(max_length=254, required=True)
class Meta:
model = User
fields = ('us... | from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
email = forms.EmailField(max_length=254, required=True)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'passwor... | mit | Python |
379a46c5679c693ba997688111b73bd3b4e7a39b | Format test file | AndersonMasese/Myshop,AndersonMasese/Myshop,AndersonMasese/Myshop | tests/test_myshop.py | tests/test_myshop.py | import unittest
import urllib
from flask_testing import LiveServerTestCase
from flask_testing import TestCase
from flask import Flask
from main import *
from redundant import *
class Myshop(TestCase):
'''class defining tests for the myshop application'''
render_templates = False
def create_app(self):
... | import unittest
import urllib
from flask_testing import LiveServerTestCase
from flask_testing import TestCase
from flask import Flask
from main import *
from person import *
from shopping_list import *
from redundant import *
class Myshop(TestCase):
'''class defining tests for the myshop application'''
render... | mit | Python |
f26741ab40a4d1238cc9b68d4e36c3a25b51a7d2 | expand test | numerodix/luna,numerodix/luna | tests/test_parser.py | tests/test_parser.py | from luna.ast import Boolean
from luna.ast import Expr
from luna.ast import Infix
from luna.ast import Nil
from luna.ast import Number
from luna.ast import Operator
def test_nil(parse):
assert Expr(Nil()) == parse('nil')
def test_false(parse):
assert Expr(Boolean('false')) == parse('false')
def test_true(pa... | from luna.ast import Boolean
from luna.ast import Expr
from luna.ast import Infix
from luna.ast import Nil
from luna.ast import Number
from luna.ast import Operator
def test_nil(parse):
assert Expr(Nil()) == parse('nil')
def test_false(parse):
assert Expr(Boolean('false')) == parse('false')
def test_true(pa... | mit | Python |
a029c644a5649d0b6955b8897b03d00e676b6d7d | add --test-dependencies switch to update subcommand; fixes #370 | autopulated/yotta,BlackstoneEngineering/yotta,ARMmbed/yotta,ARMmbed/yotta,BlackstoneEngineering/yotta,autopulated/yotta | yotta/update.py | yotta/update.py | # Copyright 2014 ARM Limited
#
# Licensed under the Apache License, Version 2.0
# See LICENSE file for details.
# standard library modules, , ,
import logging
# validate, , validate things, internal
from .lib import validate
def addOptions(parser):
parser.add_argument('component', default=None, nargs='?',
... | # Copyright 2014 ARM Limited
#
# Licensed under the Apache License, Version 2.0
# See LICENSE file for details.
# standard library modules, , ,
import logging
# validate, , validate things, internal
from .lib import validate
def addOptions(parser):
parser.add_argument('component', default=None, nargs='?',
... | apache-2.0 | Python |
7bcd6b385a26c21a425998e48f3e6b88e54fd0b2 | Update player.py | mamantoha/poker-player-monty-python | player.py | player.py |
class Player:
VERSION = "Default Python folding player"
def betRequest(self, game_state):
return 250
def showdown(self, game_state):
pass
|
class Player:
VERSION = "Default Python folding player"
def betRequest(self, game_state):
return 0
def showdown(self, game_state):
pass
| mit | Python |
c75b52409a2e5683e2ee647a1111ff12c7117ad4 | test on live | szepnapot/poker-player-pypoker | player.py | player.py | from __future__ import print_function
import sys
import traceback
from game_state import GameState
def warning(*objs):
print("WARNING: ", *objs, file=sys.stderr)
traceback.print_exc()
class Player:
VERSION = "Default Python folding player"
def preFlopBet(self):
stack = self.state.get_s... | from __future__ import print_function
import sys
import traceback
from game_state import GameState
def warning(*objs):
print("WARNING: ", *objs, file=sys.stderr)
traceback.print_exc()
class Player:
VERSION = "Default Python folding player"
def preFlopBet(self):
stack = self.state.get_s... | mit | Python |
9c982053f4d9c9696214d7c20ab32204d27e4a94 | Bump version number for 1.6 release candidate. | dex4er/django,dex4er/django,django-nonrel/django,felixjimenez/django,django-nonrel/django,dex4er/django,felixjimenez/django,django-nonrel/django,django-nonrel/django,redhat-openstack/django,redhat-openstack/django,redhat-openstack/django,felixjimenez/django,redhat-openstack/django,felixjimenez/django | django/__init__.py | django/__init__.py | VERSION = (1, 6, 0, 'rc', 1)
def get_version(*args, **kwargs):
# Don't litter django/__init__.py with all the get_version stuff.
# Only import if it's actually called.
from django.utils.version import get_version
return get_version(*args, **kwargs)
| VERSION = (1, 6, 0, 'beta', 4)
def get_version(*args, **kwargs):
# Don't litter django/__init__.py with all the get_version stuff.
# Only import if it's actually called.
from django.utils.version import get_version
return get_version(*args, **kwargs)
| bsd-3-clause | Python |
cb6276a380c306eb1b993b101bbe3f36e2ec36ee | remove useless rand | knifeofdreams/poker-player-thedeadparrot | player.py | player.py | import json
import logging
from random import randint
from config import Config
import sys
from ranking_helper import RankingHelper
logging.basicConfig(format='%(levelname)s %(lineno)d:%(funcName)s %(message)s')
log = logging.getLogger('player.Player')
log.addHandler(logging.StreamHandler(sys.stderr))
log.setLevel(l... | import json
import logging
from random import randint
from config import Config
import sys
from ranking_helper import RankingHelper
logging.basicConfig(format='%(levelname)s %(lineno)d:%(funcName)s %(message)s')
log = logging.getLogger('player.Player')
log.addHandler(logging.StreamHandler(sys.stderr))
log.setLevel(l... | mit | Python |
ce0c8e192fb1846f62dd3fb29d90dbc8d2803d70 | add whitespace between functions | zerovm/zpm,zerovm/zerovm-cli,zerovm/zerovm-cli,zerovm/zerovm-cli,zerovm/zerovm-cli,zerovm/zpm,zerovm/zpm,zerovm/zpm,zerovm/zerovm-cli,zerovm/zerovm-cli,zerovm/zpm,zerovm/zpm | zpm/commands.py | zpm/commands.py | # Copyright 2014 Rackspace, 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 agreed to in... | # Copyright 2014 Rackspace, 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 agreed to in... | apache-2.0 | Python |
e2f213a7bce005fb0b0826cffd9956a1955c86eb | remove test | zhexiao/ezhost | tests/test_server.py | tests/test_server.py | """
This test is for command line args
"""
import unittest
if __name__ == '__main__':
unittest.main()
| """
This test is for command line args
"""
import unittest
import argparse
import configparser
from ezhost.BigDataArchi import BigDataArchi
class ServerTest(unittest.TestCase):
parser = argparse.ArgumentParser()
parser.add_argument(
'-s', '--server',
help='服务器代替名',
)
def test_big... | mit | Python |
fc0f25b907414d82c92ce930347dd438def973d8 | Improve exception handling and logging | xchewtoyx/dns-update | dnsupdater/main.py | dnsupdater/main.py | import socket
import urllib2
from cement.core import controller, foundation, handler
IP_DETECT_URL = 'http://%s/myip/'
IP_DETECT_HOST = 'rgh-go-sandpit.appspot.com'
IP_UPDATE_URL = (
'http://svc.joker.com/nic/update?username=%s&password=%s&hostname=%s')
class DNSUpdateController(controller.CementBaseController):
... | import socket
import urllib2
from cement.core import controller, foundation, handler
IP_DETECT_URL = 'http://%s/myip/'
IP_DETECT_HOST = 'rgh-go-sandpit.appspot.com'
IP_UPDATE_URL = (
'http://svc.joker.com/nic/update?username=%s&password=%s&hostname=%s')
class DNSUpdateController(controller.CementBaseController):
... | mit | Python |
3863ed89b20be2dbc14e0723fd2c7cdce1027c34 | simplify test | svenkreiss/html5validator,svenkreiss/html5validator | tests/test_simple.py | tests/test_simple.py | """Do an integration test. Only use simple html files."""
import subprocess
def test_valid():
assert subprocess.call(['html5validator', '--root=tests/valid/']) == 0
def test_invalid():
assert subprocess.call(['html5validator', '--root=tests/invalid/']) == 1
| """Do an integration test. Only use simple html files."""
import subprocess
def test_valid():
subprocess.check_call(['html5validator', '--root=tests/valid/'])
def test_invalid():
try:
subprocess.check_call(['html5validator', '--root=tests/invalid/'])
except subprocess.CalledProcessError, e:
... | mit | Python |
3dcee6501d3b3b56425c0b5383555dd95038071d | fix single test: .fetch method no longer needed | vanatteveldt/xtas,vanatteveldt/xtas,vanatteveldt/xtas | tests/test_single.py | tests/test_single.py | from nose.tools import assert_equal
from xtas.tasks import tokenize
def test_tokenize():
tokens = tokenize("My hovercraft is full of eels.")
expected = "My hovercraft is full of eels .".split()
for obs, exp in zip(tokens, expected):
assert_equal(obs, {"token": exp})
| from nose.tools import assert_equal
from xtas.tasks import tokenize
class MockDocument(object):
def __init__(self, text):
self.text = text
def fetch(self):
return self.text
def test_tokenize():
doc = MockDocument("My hovercraft is full of eels.")
tokens = tokenize(doc)
expected... | apache-2.0 | Python |
98de8e3d64ba23ac5eb1828d9af28574eaf16fcc | Update tomorrow.py | madisonmay/Tomorrow,kantale/Tomorrow | tomorrow/tomorrow.py | tomorrow/tomorrow.py | from functools import wraps
from concurrent.futures import ThreadPoolExecutor
class Tomorrow():
def __init__(self, future, timeout):
self._future = future
self._timeout = timeout
def __getattr__(self, name):
result = self._wait()
return result.__getattribute__(name)
def... | from functools import wraps
from concurrent.futures import ThreadPoolExecutor
class Tomorrow():
def __init__(self, future, timeout):
self._future = future
self._timeout = timeout
def __getattr__(self, name):
result = self._future.result(self._timeout)
return result.__getattr... | mit | Python |
b35cf1c6297e03623a1dc15a774638561889c87f | enable dj_static | flenter/versioning_service,flenter/versioning_service | versioning_service/wsgi.py | versioning_service/wsgi.py | """
WSGI config for versioning_service 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_APP... | """
WSGI config for versioning_service 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_APP... | mit | Python |
68b31d16841e42b10f850bfc48ea3ab30855939a | Update downloader.py | labodiattila/vdrlogo | downloader.py | downloader.py | #!/usr/bin/python
import urllib2,json,time,vdrlogo,os
def lyngsat_download(country_list):
#Download logo HTML
code_list = country_list.split(",")
for num in range(0,len(code_list)):
vdrlogo.run_cmd("wget -q " + vdrlogo.lyngsat_logo_URL + code_list[num] + ".html -O out.html")
vdrlogo.run_cmd('cat out.html | gre... | #!/usr/bin/python
import urllib2,json,time,vdrlogo,os
def lyngsat_download(country_list):
#Download logo HTML
code_list = country_list.split(",")
for num in range(0,len(code_list)):
vdrlogo.run_cmd("wget -q " + vdrlogo.lyngsat_logo_URL + code_list[num] + ".html -O out.html")
vdrlogo.run_cmd('cat out.html | gre... | mit | Python |
6125445556c93670ec0eaf73b77c4dad0c0a160c | switch to markdown | jabbalaci/Bash-Utils,jabbalaci/Bash-Utils,jabbalaci/Bash-Utils,jabbalaci/Bash-Utils,jabbalaci/Bash-Utils,jabbalaci/Bash-Utils | markdown.py | markdown.py | #!/usr/bin/env python
"""
Markdown previewer
==================
Author: Laszlo Szathmary, 2011--2012 (jabba.laci@gmail.com)
Website: https://ubuntuincident.wordpress.com/2011/05/05/readme-markdown-on-github/
GitHub: https://github.com/jabbalaci/Bash-Utils
Preview markdown files.
Usage:
------
Put it in your ~/bin ... | #!/usr/bin/env python
"""
Markdown previewer
==================
Author: Laszlo Szathmary, 2011--2012 (jabba.laci@gmail.com)
Website: https://ubuntuincident.wordpress.com/2011/05/05/readme-markdown-on-github/
GitHub: https://github.com/jabbalaci/Bash-Utils
Preview markdown files.
Usage:
------
Put it in your ~/bin ... | mit | Python |
91cc1811248d3ea72139ca24ad95a135d1407272 | Update about_asserts.py | yashwanthbabu/python_koans_python2_solutions,yashwanthbabu/python_koans_python2_solutions | python2/koans/about_asserts.py | python2/koans/about_asserts.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutAsserts(Koan):
def test_assert_truth(self):
"""
We shall contemplate truth by testing reality, via asserts.
"""
# Confused? This video should help:
#
# http://bit.ly/about_assert... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutAsserts(Koan):
def test_assert_truth(self):
"""
We shall contemplate truth by testing reality, via asserts.
"""
# Confused? This video should help:
#
# http://bit.ly/about_assert... | mit | Python |
53ea9a9074d40abbf774d92beef9ade8bf548209 | Modify parameter handling for foreign function calls | pdarragh/Viper | viper/interpreter/value.py | viper/interpreter/value.py | from .environment import Environment
from viper.parser.ast.nodes import AST, Parameter
from inspect import signature
from typing import Callable, List
class Value:
pass
class TupleVal(Value):
def __init__(self, *vals: Value):
self.vals = list(vals)
def __repr__(self) -> str:
return f"... | from .environment import Environment
from viper.parser.ast.nodes import AST, Parameter
from inspect import signature
from typing import Callable, List
class Value:
pass
class TupleVal(Value):
def __init__(self, *vals: Value):
self.vals = list(vals)
def __repr__(self) -> str:
return f"... | apache-2.0 | Python |
74e4fb53988f1012692d3878c59741a1b1345b2c | remove unused imports | ckan/ckanext-qa,ckan/ckanext-qa,ckan/ckanext-qa | tests/test_extension.py | tests/test_extension.py | from paste.deploy import appconfig
import paste.fixture
from ckan.config.middleware import make_app
from ckan.tests import conf_dir, url_for, CreateTestData
from ckan import model
from ckan.lib.dictization.model_dictize import package_dictize
class TestQAController:
@classmethod
def setup_class(cls):
... | from paste.deploy import appconfig
import paste.fixture
import json
from ckan.config.middleware import make_app
from ckan.tests import conf_dir, url_for, CreateTestData
from ckan import model
from ckan.lib.dictization.model_dictize import package_dictize
from ckanext.qa.reports import (
five_stars, broken_resource... | mit | Python |
fb571cfb92c07846d6b1c7946c0838eccf780ae1 | Clean up project deletion (#3212) | dstufft/warehouse,dstufft/warehouse,pypa/warehouse,pypa/warehouse,pypa/warehouse,dstufft/warehouse,pypa/warehouse,dstufft/warehouse | warehouse/utils/project.py | warehouse/utils/project.py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Li... | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Li... | apache-2.0 | Python |
f982578a182df7448bdc118955b2e23567c73bf9 | update test for utilities | TheGhouls/oct,karec/oct,karec/oct,TheGhouls/oct,TheGhouls/oct | tests/test_utilities.py | tests/test_utilities.py | import os
import sys
import shutil
import tarfile
import unittest
from oct.utilities.commands import main
class UtilitiesTest(unittest.TestCase):
def setUp(self):
self.valid_dir = '/tmp/create-test'
self.invalid_dir = '/create-test'
self.test_dir = '/tmp/utiles_tests'
sys.argv =... | import os
import sys
import shutil
import unittest
from oct.utilities.commands import main
class UtilitiesTest(unittest.TestCase):
def setUp(self):
self.valid_dir = '/tmp/create-test'
self.invalid_dir = '/create-test'
self.test_dir = '/tmp/utiles_tests'
sys.argv = sys.argv[:1]
... | mit | Python |
2d1175ace7c4221793c23ae576538f840660eecd | Bump version to 13.21.0 | hhursev/recipe-scraper | recipe_scrapers/__version__.py | recipe_scrapers/__version__.py | __version__ = "13.21.0"
| __version__ = "13.20.0"
| mit | Python |
5acdcc184f701528102a81e39e9873e18e3ff443 | fix UnicodeEncodeError writing SVG string to .svg file, fixes #489 | ipython/ipython,ipython/ipython | IPython/frontend/qt/svg.py | IPython/frontend/qt/svg.py | """ Defines utility functions for working with SVG documents in Qt.
"""
# System library imports.
from IPython.external.qt import QtCore, QtGui, QtSvg
def save_svg(string, parent=None):
""" Prompts the user to save an SVG document to disk.
Parameters:
-----------
string : basestring
A Python... | """ Defines utility functions for working with SVG documents in Qt.
"""
# System library imports.
from IPython.external.qt import QtCore, QtGui, QtSvg
def save_svg(string, parent=None):
""" Prompts the user to save an SVG document to disk.
Parameters:
-----------
string : basestring
A Python... | bsd-3-clause | Python |
404742c3f7cad7a60bcd137bf6c757d02c3ddd09 | change default value for campaign pct complete | unicef/rhizome,unicef/rhizome,unicef/rhizome,unicef/rhizome | datapoints/migrations/0019_campaign_management_dash_pct_complete.py | datapoints/migrations/0019_campaign_management_dash_pct_complete.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('datapoints', '0018_delete_campaignabstracted'),
]
operations = [
migrations.AddField(
model_name='campaign',
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('datapoints', '0018_delete_campaignabstracted'),
]
operations = [
migrations.AddField(
model_name='campaign',
... | agpl-3.0 | Python |
00c8a227a8e067f7f8b2a1b37f11fd8792c081b0 | Add dockerfile to experiment admin | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | polyaxon/experiments/admin.py | polyaxon/experiments/admin.py | from django.contrib import admin
from experiments.models import (
Experiment,
ExperimentJob,
ExperimentJobStatus,
ExperimentMetric,
ExperimentStatus
)
from jobs.admin import JobStatusAdmin
from libs.admin import DiffModelAdmin
class ExperimentAdmin(DiffModelAdmin):
readonly_fields = DiffModel... | from django.contrib import admin
from experiments.models import (
Experiment,
ExperimentJob,
ExperimentJobStatus,
ExperimentMetric,
ExperimentStatus
)
from jobs.admin import JobStatusAdmin
from libs.admin import DiffModelAdmin
class ExperimentAdmin(DiffModelAdmin):
readonly_fields = DiffModel... | apache-2.0 | Python |
32637c1e9a37dc416df802805420d38f9af18d79 | Print the discovered queues in alphabetical order for convenience | thread/django-lightweight-queue,thread/django-lightweight-queue | django_lightweight_queue/management/commands/queue_configuration.py | django_lightweight_queue/management/commands/queue_configuration.py | from django.core.management.base import BaseCommand
from ... import app_settings
from ...utils import get_backend, load_extra_config
from ...cron_scheduler import get_cron_config
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('--config', action='store', default=None,
... | from django.core.management.base import BaseCommand
from ... import app_settings
from ...utils import get_backend, load_extra_config
from ...cron_scheduler import get_cron_config
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('--config', action='store', default=None,
... | bsd-3-clause | Python |
b8f2b300a32fe775a5942d634c296a2d12cdbf7c | Fix recommendation engine | machinalis/machinalis-movie-reviews,machinalis/machinalis-movie-reviews,machinalis/machinalis-movie-reviews | movie_recommendations/recommendation_engines.py | movie_recommendations/recommendation_engines.py | import sys
from sqlalchemy import or_
from sqlalchemy.sql.expression import func
from movie_recommendations import app, db, models
def random_choice(user):
"""Picks a random set of movies"""
return models.Movie.query.order_by(func.random())
def facebook_recommendations(user):
"""Picks movies based on... | import sys
from sqlalchemy import or_
from sqlalchemy.sql.expression import func
from movie_recommendations import app, db, models
def random_choice(user):
"""Picks a random set of movies"""
return models.Movie.query.order_by(func.random())
def facebook_recommendations(user):
"""Picks movies based on... | bsd-3-clause | Python |
e1e7b72685df12d1d7d782e03878253663a4c790 | Fix script that removes numerals from people's locations. | campbe13/openhatch,heeraj123/oh-mainline,moijes12/oh-mainline,ojengwa/oh-mainline,Changaco/oh-mainline,vipul-sharma20/oh-mainline,campbe13/openhatch,SnappleCap/oh-mainline,SnappleCap/oh-mainline,waseem18/oh-mainline,eeshangarg/oh-mainline,moijes12/oh-mainline,waseem18/oh-mainline,sudheesh001/oh-mainline,onceuponatimefo... | mysite/scripts/remove_numbers_from_locations.py | mysite/scripts/remove_numbers_from_locations.py | import re
import mysite
Person = mysite.profile.models.Person
people_with_weird_locations = Person.objects.filter(location_display_name__regex=', [0-9][0-9],')
for p in people_with_weird_locations:
location_pieces = re.split(r', \d\d,', p.location_display_name)
unweirded_location = ",".join(location_pieces)
... | import re
import mysite
Person = mysite.profile.models.Person
people_with_weird_locations = Person.objects.filter(location_display_name__regex=', [0-9][0-9],')
for p in people_with_weird_locations:
location_pieces = re.split(r', \d\d', p.location_display_name)
unweirded_location = "".join(location_pieces)
... | agpl-3.0 | Python |
907c1d8a5960becb5699d9a06a80f7f00853e332 | Change exception types in network_segment_range | openstack/neutron-lib,openstack/neutron-lib,openstack/neutron-lib,openstack/neutron-lib | neutron_lib/exceptions/network_segment_range.py | neutron_lib/exceptions/network_segment_range.py | # Copyright (c) 2018 Intel Corporation.
#
# 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 la... | # Copyright (c) 2018 Intel Corporation.
#
# 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 la... | apache-2.0 | Python |
71c8149ef637d594a8c818977ac0cbb6fb471e4c | make the collector match for filename when used | alfredodeza/merfi | merfi/collector.py | merfi/collector.py | from __future__ import with_statement
import os
import re
class FileCollector(list):
def __init__(self, config=None):
config = config or {}
self.user_match = config.get('filename')
self.case_insensitive = config.get('ignorecase')
self.path = self._abspath(config.get('path', '.'))
... | from __future__ import with_statement
import os
import re
class FileCollector(list):
def __init__(self, config=None):
config = config or {}
self.user_match = config.get('match')
self.case_insensitive = config.get('ignorecase')
self.path = self._abspath(config.get('path', '.'))
... | mit | Python |
225eb2acd9857e56611d20f3bb2708188068b066 | Add dock tests | rossant/phy,kwikteam/phy,kwikteam/phy,rossant/phy,rossant/phy,kwikteam/phy | phy/gui/tests/test_dock.py | phy/gui/tests/test_dock.py | # -*- coding: utf-8 -*-
"""Test dock."""
#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------
from pytest import mark
from vispy import app
from ..qt import Qt
from ..dock import DockWindow
from phy... | # -*- coding: utf-8 -*-
"""Test dock."""
#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------
from pytest import mark
from vispy import app
from ..dock import DockWindow
from ...utils._color import ... | bsd-3-clause | Python |
e16112627669de0c914f52a497f20c6f5185ec08 | Bump version | thombashi/pingparsing,thombashi/pingparsing | pingparsing/__version__.py | pingparsing/__version__.py | # encoding: utf-8
from datetime import datetime
__author__ = "Tsuyoshi Hombashi"
__copyright__ = "Copyright 2016-{}, {}".format(datetime.now().year, __author__)
__license__ = "MIT License"
__version__ = "0.13.8"
__maintainer__ = __author__
__email__ = "tsuyoshi.hombashi@gmail.com"
| # encoding: utf-8
from datetime import datetime
__author__ = "Tsuyoshi Hombashi"
__copyright__ = "Copyright 2016-{}, {}".format(datetime.now().year, __author__)
__license__ = "MIT License"
__version__ = "0.13.7"
__maintainer__ = __author__
__email__ = "tsuyoshi.hombashi@gmail.com"
| mit | Python |
0f7bfdaf96c785b983a64555fec94120a963b72a | fix confusing typo in config-example | macks22/dblp,macks22/dblp | pipeline/config-example.py | pipeline/config-example.py | import os
pjoin = os.path.join
base_dir = '/data/username/aminer-network'
data_dir = pjoin(base_dir, 'data')
originals_dir = pjoin(data_dir, 'original-data')
base_csv_dir = pjoin(data_dir, 'base-csv')
filtered_dir = pjoin(data_dir, 'filtered-csv')
repdoc_dir = pjoin(data_dir, 'repdocs')
graph_dir = pjoin(data_dir, 'gr... | import os
pjoin = os.path.join
base_dir = '/data/username/aminer-network'
data_dir = pjoin(base_dir, 'data')
originals_dir = pjoin(base_dir, 'original-data')
base_csv_dir = pjoin(data_dir, 'base-csv')
filtered_dir = pjoin(data_dir, 'filtered-csv')
repdoc_dir = pjoin(data_dir, 'repdocs')
graph_dir = pjoin(data_dir, 'gr... | mit | Python |
5c4f0d7c954120a6dada09ce5628e76939be7304 | Exit with a exitcode if restricted mail don't recipients | webkom/holonet,webkom/holonet,webkom/holonet | holonet/core/handler.py | holonet/core/handler.py | # -*- coding: utf8 -*-
import sys
from django.conf import settings
from holonet.core.tasks import (index_blacklisted_mail, index_bounce_mail, index_spam,
send_blacklist_notification, send_bounce_notification,
send_spam_notification)
from holonet.mapping... | # -*- coding: utf8 -*-
from django.conf import settings
from holonet.core.tasks import (index_blacklisted_mail, index_bounce_mail, index_spam,
send_blacklist_notification, send_bounce_notification,
send_spam_notification)
from holonet.mappings.helpers im... | mit | Python |
ae5a3780818af8297598808b55ac2875992a8200 | Add auto_enroll_email() | fghaas/edx-shopify,hastexo/edx-shopify | edx_shopify/utils.py | edx_shopify/utils.py | import hashlib, base64, hmac
from django.core.validators import validate_email
from django.contrib.auth.models import User
from opaque_keys.edx.locations import SlashSeparatedCourseKey
from courseware.courses import get_course_by_id
from lms.djangoapps.instructor.enrollment import (
get_user_email_language,
en... | import hashlib, base64, hmac
def hmac_is_valid(key, msg, hmac_to_verify):
hash = hmac.new(key, msg, hashlib.sha256)
hmac_calculated = base64.b64encode(hash.digest())
return hmac_calculated == hmac_to_verify
| agpl-3.0 | Python |
73413baa59e522177574a550093b8d161408e79b | Add required imports to plugin.events | SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree | InvenTree/plugin/events.py | InvenTree/plugin/events.py | """
Import helper for events
"""
from plugin.base.event.events import process_event, register_event, trigger_event
__all__ = [
'process_event',
'register_event',
'trigger_event',
]
| """
Import helper for events
"""
from plugin.base.event.events import trigger_event
__all__ = [
'trigger_event',
]
| mit | Python |
6f93fe8f66ff660cc6ce0df555d6722e6ccbfe20 | fix the password setting in DeviceOwner creation | jonboiser/kolibri,benjaoming/kolibri,jonboiser/kolibri,christianmemije/kolibri,whitzhu/kolibri,ralphiee22/kolibri,rtibbles/kolibri,MingDai/kolibri,MingDai/kolibri,lyw07/kolibri,learningequality/kolibri,learningequality/kolibri,mrpau/kolibri,jtamiace/kolibri,aronasorman/kolibri,jayoshih/kolibri,ralphiee22/kolibri,jayosh... | kolibri/plugins/setup_wizard/views.py | kolibri/plugins/setup_wizard/views.py | from __future__ import absolute_import, print_function, unicode_literals
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.views.generic.base import TemplateView
from kolibri.auth.models import DeviceOwner
from rest_framework import viewsets
class DeviceOwnerCreateView(Tem... | from __future__ import absolute_import, print_function, unicode_literals
from django.http import HttpResponse
from django.views.generic.base import TemplateView
from kolibri.auth.models import DeviceOwner
from rest_framework import viewsets
class DeviceOwnerCreateView(TemplateView):
template_name = "setup_wizard... | mit | Python |
f4997509d78ba80c2b53fb5fdced6c60654d926a | Split names on whitespace and/or capital letters | thatalextaylor/delphi-395 | delphi-395.py | delphi-395.py | import argparse, os, re
from jinja2 import Environment, PackageLoader
from yaml import load, dump, Loader
from uuid import uuid4
def get_config():
parser = argparse.ArgumentParser(description='Construct Delphi classes from a YAML template.')
parser.add_argument('source_files', metavar='SOURCE', type=file, nar... | import argparse, os
from jinja2 import Environment, PackageLoader
from yaml import load, dump, Loader
from uuid import uuid4
def get_config():
parser = argparse.ArgumentParser(description='Construct Delphi classes from a YAML template.')
parser.add_argument('source_files', metavar='SOURCE', type=file, nargs='... | mit | Python |
d1d76dddeaa183e3b80eba17be1c06b117223c90 | Update af_prepGrpAB.py | aaronfang/personal_scripts | scripts/af_prepGrpAB.py | scripts/af_prepGrpAB.py | # ------------------------------------------
# af_prepGrpA.py
# Summary: This script allows user to relocate the pivot point of a asset.
# 1, Make outliner structure as famity name.
# 2, Select the group node in asset level.
# 3, Run the following script.
import pymel.core as pm
import maya.mel as mm
# add '_grp' to ... | # ------------------------------------------
# af_prepGrpA.py
# Summary: This script allows user to relocate the pivot point of a asset.
# 1, Make outliner structure as famity name.
# 2, Select the group node in asset level.
# 3, Run the following script.
import pymel.core as pm
import maya.mel as mm
# add '_grp' to ... | mit | Python |
b23c843fda57e0ffa56aaf430d9a590e2ed0ec9a | Check variable for None value before null string when filtering tail numbers | rjurney/Agile_Data_Code_2,naoyak/Agile_Data_Code_2,rjurney/Agile_Data_Code_2,naoyak/Agile_Data_Code_2,rjurney/Agile_Data_Code_2,naoyak/Agile_Data_Code_2,rjurney/Agile_Data_Code_2,naoyak/Agile_Data_Code_2 | ch06/extract_airlines.py | ch06/extract_airlines.py | # Load the on-time parquet file
on_time_dataframe = spark.read.parquet('data/on_time_performance.parquet')
# The first step is easily expressed as SQL: get all unique tail numbers for each airline
on_time_dataframe.registerTempTable("on_time_performance")
carrier_airplane = spark.sql(
"SELECT DISTINCT Carrier, TailN... | # Load the on-time parquet file
on_time_dataframe = spark.read.parquet('data/on_time_performance.parquet')
# The first step is easily expressed as SQL: get all unique tail numbers for each airline
on_time_dataframe.registerTempTable("on_time_performance")
carrier_airplane = spark.sql(
"SELECT DISTINCT Carrier, TailN... | mit | Python |
e8e552b72fe5b48386bdf5fb2165b187213ea5b6 | FIX check invoice has vat tax | jobiols/odoo-argentina,ingadhoc/odoo-argentina,bmya/odoo-argentina,adhoc-dev/odoo-argentina,jobiols/odoo-argentina,bmya/odoo-argentina,adhoc-dev/odoo-argentina | l10n_ar_account/models/res_company.py | l10n_ar_account/models/res_company.py | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import fields, models, api
from opene... | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import fields, models, api
from opene... | agpl-3.0 | Python |
fd7167e675820d23401c9b138bf862160836905a | fix typo in `python -m IPython.kernel` | ipython/ipython,ipython/ipython | IPython/kernel/__main__.py | IPython/kernel/__main__.py | if __name__ == '__main__':
from ipython_kernel import kernelapp as app
app.launch_new_instance()
| if __name__ == '__main__':
from ipython_kernel.zmq import kernelapp as app
app.launch_new_instance()
| bsd-3-clause | Python |
8e93e044e0bfceedaa0c6500633b841397305183 | Update queryTesting.py | dbmi-pitt/DIKB-Micropublication,dbmi-pitt/DIKB-Micropublication,dbmi-pitt/DIKB-Micropublication | scripts/queryTesting.py | scripts/queryTesting.py | import sys, os, datetime
sys.path.append('.')
from SPARQLWrapper import SPARQLWrapper, JSON
QUERIES_PATH = "../queries/"
def readCSVfromDir(inputdir):
queriesD = {}
for fname in os.listdir(inputdir):
if fname.endswith(".sparql"):
with open(inputdir + fname) as f:
query = ... | import sys, os, datetime
sys.path.append('.')
from SPARQLWrapper import SPARQLWrapper, JSON
QUERIES_PATH = "../queries/"
def readCSVfromDir(inputdir):
queriesD = {}
for fname in os.listdir(inputdir):
if fname.endswith(".sparql"):
with open(inputdir + fname) as f:
query = ... | apache-2.0 | Python |
2ec2a954904d773c374f0a4c72fc8a162347e7a2 | Add some constants | lakewik/storj-gui-client | UI/resources/constants.py | UI/resources/constants.py | # -*- coding: utf-8 -*-
SAVE_PASSWORD_HASHED = True
MAX_RETRIES_DOWNLOAD_FROM_SAME_FARMER = 3
MAX_RETRIES_UPLOAD_TO_SAME_FARMER = 3
MAX_RETRIES_NEGOTIATE_CONTRACT = 1000
MAX_RETRIES_GET_FILE_POINTERS = 100
FILE_POINTERS_REQUEST_DELAY = 1
# int: file pointers request delay, in seconds.
MAX_DOWNLOAD_REQUEST_BLOCK_SIZE... | # -*- coding: utf-8 -*-
SAVE_PASSWORD_HASHED = True
MAX_RETRIES_DOWNLOAD_FROM_SAME_FARMER = 3
MAX_RETRIES_UPLOAD_TO_SAME_FARMER = 3
MAX_RETRIES_NEGOTIATE_CONTRACT = 1000
MAX_RETRIES_GET_FILE_POINTERS = 100
FILE_POINTERS_REQUEST_DELAY = 1
# int: file pointers request delay, in seconds.
MAX_DOWNLOAD_REQUEST_BLOCK_SIZE... | mit | Python |
d8d2c50c008796f1a9f0362abf36fc78ebaa8c70 | add newline | ssadedin/seqr,ssadedin/seqr,ssadedin/seqr,ssadedin/seqr,ssadedin/seqr | seqr/views/react_app.py | seqr/views/react_app.py | import json
import re
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.core.serializers.json import DjangoJSONEncoder
from django.middleware.csrf import rotate_token
from django.template import loader
from django.http import HttpResponse
from settings imp... | import json
import re
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.core.serializers.json import DjangoJSONEncoder
from django.middleware.csrf import rotate_token
from django.template import loader
from django.http import HttpResponse
from settings imp... | agpl-3.0 | Python |
67d714c8c2d4f8094b1e68bc6614b2bf02694b50 | Fix typo | MACSIFS/IFS,MACSIFS/IFS,MACSIFS/IFS,MACSIFS/IFS | server/api/v0/course.py | server/api/v0/course.py | from flask_restful import Resource, reqparse, abort
from flask.ext.login import current_user, login_required
from server.models import db, Course, Lecturer
class CourseListResource(Resource):
def get(self):
argparser = reqparse.RequestParser()
argparser.add_argument('lecturer', location='args', t... | from flask_restful import Resource, reqparse, abort
from flask.ext.login import current_user, login_required
from server.models import db, Course, Lecturer
class CourseListResource(Resource):
def get(self):
argparser = reqparse.RequestParser()
argparser.add_argument('lecturer', location='args', t... | mit | Python |
73356e9831b9538b5275a809e09eebb23813f84e | add timeout when fetching a page | sdpython/jyquickhelper,sdpython/jyquickhelper,sdpython/jyquickhelper | _unittests/test_jspy/test_render_nb_json.py | _unittests/test_jspy/test_render_nb_json.py | """
@brief test log(time=2s)
"""
import unittest
from jyquickhelper import JSONJS
class TestRenderNbJson(unittest.TestCase):
def test_render_nb_json(self):
f = JSONJS(dict(a="a"))
assert f
if hasattr(f, "_ipython_display_"):
f._ipython_display_()
else:
... | """
@brief test log(time=2s)
"""
import unittest
from pyquickhelper.loghelper import fLOG
from jyquickhelper import JSONJS
class TestRenderNbJson(unittest.TestCase):
def test_render_nb_json(self):
fLOG(
__file__,
self._testMethodName,
OutputPrint=__name__ == "__ma... | mit | Python |
339508769edd9b17b9d382d99681702a07eaf5a7 | Update __init__.py | ggreco77/GWsky | GWsky/__init__.py | GWsky/__init__.py | from .version import __version__
| from GWsky import coverage
from GWsky import UserValues
from .version import __version__
| bsd-2-clause | Python |
26c9618e63858578e93e692da43871ec9edf39c4 | fix import path. | ashleysommer/sanic,channelcat/sanic,lixxu/sanic,yunstanford/sanic,jrocketfingers/sanic,channelcat/sanic,r0fls/sanic,r0fls/sanic,lixxu/sanic,yunstanford/sanic,channelcat/sanic,Tim-Erwin/sanic,ai0/sanic,lixxu/sanic,ai0/sanic,yunstanford/sanic,ashleysommer/sanic,channelcat/sanic,yunstanford/sanic,lixxu/sanic,Tim-Erwin/san... | sanic/__main__.py | sanic/__main__.py | from argparse import ArgumentParser
from importlib import import_module
from sanic.log import log
from sanic.app import Sanic
if __name__ == "__main__":
parser = ArgumentParser(prog='sanic')
parser.add_argument('--host', dest='host', type=str, default='127.0.0.1')
parser.add_argument('--port', dest='port'... | from argparse import ArgumentParser
from importlib import import_module
from sanic.log import log
from sanic.sanic import Sanic
if __name__ == "__main__":
parser = ArgumentParser(prog='sanic')
parser.add_argument('--host', dest='host', type=str, default='127.0.0.1')
parser.add_argument('--port', dest='por... | mit | Python |
db67f3e779b0a8a89f9ab253f33c4c809f375c80 | modify clean.py to look for files only in current dir | SasView/sasview,SasView/sasview,lewisodriscoll/sasview,lewisodriscoll/sasview,lewisodriscoll/sasview,SasView/sasview,SasView/sasview,SasView/sasview,lewisodriscoll/sasview,SasView/sasview,lewisodriscoll/sasview | sansview/clean.py | sansview/clean.py | """
Remove all compiled code.
"""
import os
filedirs = ['.']
for d in filedirs:
files = os.listdir(d)
for f in files:
if f.find('.pyc')>0:
print "Removed", f
os.remove(os.path.join(d,f)) | """
Remove all compiled code.
"""
import os
filedirs = ['.', 'perspectives', 'perspectives/fitting']
for d in filedirs:
files = os.listdir(d)
for f in files:
if f.find('.pyc')>0:
print "Removed", f
os.remove(os.path.join(d,f)) | bsd-3-clause | Python |
12879534e2ec41a2abf2edd908e2488c4ebac620 | Fix cheroot.test.conftest doc spelling | cherrypy/cheroot | cheroot/test/conftest.py | cheroot/test/conftest.py | """Pytest configuration module.
Contains fixtures, which are tightly bound to the Cheroot framework
itself, useless for end-users' app testing.
"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import threading
import time
import pytest
from ..server import Gateway, HTTPServ... | """Pytest configuration module.
Contains fixtures, which are tightly bound to the Cheroot framework
itself, useless for end-users' app testing.
"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import threading
import time
import pytest
from ..server import Gateway, HTTPServ... | bsd-3-clause | Python |
869d5671f47ba23d456bbe5ac732c7858bbc473e | Fix argument indentation in group entity doc | openfisca/openfisca-core,openfisca/openfisca-core | openfisca_core/entities/group_entity.py | openfisca_core/entities/group_entity.py | from openfisca_core.entities import Entity, Role
class GroupEntity(Entity):
"""Represents an entity containing several other entities with different roles.
A :class:`.GroupEntity` represents an :class:`.Entity` containing
several other :class:`.Entity` with different :class:`.Role`, and on
which calc... | from openfisca_core.entities import Entity, Role
class GroupEntity(Entity):
"""Represents an entity containing several other entities with different roles.
A :class:`.GroupEntity` represents an :class:`.Entity` containing
several other :class:`.Entity` with different :class:`.Role`, and on
which calc... | agpl-3.0 | Python |
407a403a4eac078da4679ecb790b440e89ff0aa1 | Update imagecodecs/__init__.py | cgohlke/imagecodecs,cgohlke/imagecodecs,cgohlke/imagecodecs | imagecodecs/__init__.py | imagecodecs/__init__.py | # -*- coding: utf-8 -*-
# imagecodecs/__init__.py
try:
from ._imagecodecs import __doc__, __version__
from ._imagecodecs import *
except ImportError as error:
import warnings
warnings.warn("""
%s
*******************************************************************
The _imagecodecs Cython extension mo... | # -*- coding: utf-8 -*-
# imagecodecs/__init__.py
try:
from ._imagecodecs import __doc__, __version__
from ._imagecodecs import *
except ImportError as error:
import warnings
warnings.warn("""
%s
*******************************************************************
The _imagecodecs Cython extension mo... | bsd-3-clause | Python |
e1421a5ee384d3d76a28bc15223eaf9cdc451988 | Set version to 0.1.3. | alecthomas/importmagic,pombredanne/importmagic,birkenfeld/importmagic | importmagic/__init__.py | importmagic/__init__.py | """Python Import Magic - automagically add, remove and manage imports
This module just exports the main API of importmagic.
"""
__author__ = 'Alec Thomas <alec@swapoff.org>'
__version__ = '0.1.3'
from importmagic.importer import Import, Imports, get_update, update_imports
from importmagic.index import SymbolIndex
fr... | """Python Import Magic - automagically add, remove and manage imports
This module just exports the main API of importmagic.
"""
__author__ = 'Alec Thomas <alec@swapoff.org>'
__version__ = '0.1.2'
from importmagic.importer import Import, Imports, get_update, update_imports
from importmagic.index import SymbolIndex
fr... | bsd-2-clause | Python |
290eb456204274d155cca5daa90ef5b43ccf427f | update to 1.8.6.4 | lewzylu/coscmd | coscmd/cos_global.py | coscmd/cos_global.py | Version = "1.8.6.4"
| Version = "1.8.6.3"
| mit | Python |
e6b8eb0921987168ed826c2cd97edcf6f163934b | remove awkward HTML detection. | openspending/spendb,USStateDept/FPA_Core,USStateDept/FPA_Core,nathanhilbert/FPA_Core,nathanhilbert/FPA_Core,CivicVision/datahub,spendb/spendb,johnjohndoe/spendb,johnjohndoe/spendb,openspending/spendb,CivicVision/datahub,pudo/spendb,CivicVision/datahub,spendb/spendb,nathanhilbert/FPA_Core,pudo/spendb,openspending/spendb... | openspending/lib/unicode_dict_reader.py | openspending/lib/unicode_dict_reader.py | # work around python2's csv.py's difficulty with utf8
# partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support
import csv
class EmptyCSVError(Exception):
pass
class UnicodeDictReader(object):
def __init__(self, fp, encoding='utf8', **kwargs):
... | # work around python2's csv.py's difficulty with utf8
# partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support
import csv
class EmptyCSVError(Exception):
pass
class CSVisHTML(Exception):
pass
class UnicodeDictReader(object):
def __init__(s... | agpl-3.0 | Python |
8f56ccddf8acd97c779616d6408b876c349458be | Update version to 0.4.1 | uezo/minette-python | minette/version.py | minette/version.py | __version__ = "0.4.1"
| __version__ = "0.4.dev7"
| apache-2.0 | Python |
c8f71e5dbaf8997198d3fff3c441f673983e8a34 | Add missing type hints | homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps | byceps/services/attendance/service.py | byceps/services/attendance/service.py | """
byceps.services.attendance.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
"""
from typing import Dict, List, Sequence
from ...services.seating.models.seat import Seat
from ...services.seating import seat_service
from ...services.seating.transfer.models import SeatID
from ..... | """
byceps.services.attendance.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
"""
from typing import Dict, List, Sequence
from ...services.seating.models.seat import Seat
from ...services.seating import seat_service
from ...services.seating.transfer.models import SeatID
from ..... | bsd-3-clause | Python |
c9b8914528f70fc8444a913a0934a0e44bff67c1 | bump version number to 0.2.0 | pytorch/vision,pytorch/vision,pytorch/vision,pytorch/vision,jrdurrant/vision,pytorch/vision,pytorch/vision | torchvision/__init__.py | torchvision/__init__.py | from torchvision import models
from torchvision import datasets
from torchvision import transforms
from torchvision import utils
__version__ = '0.2.0'
_image_backend = 'PIL'
def set_image_backend(backend):
"""
Specifies the package used to load images.
Args:
backend (string): Name of the image ... | from torchvision import models
from torchvision import datasets
from torchvision import transforms
from torchvision import utils
__version__ = '0.1.9'
_image_backend = 'PIL'
def set_image_backend(backend):
"""
Specifies the package used to load images.
Args:
backend (string): Name of the image ... | bsd-3-clause | Python |
dbc09d03f62bf2d5ee1661492a4c20a7942f81a9 | Enable tests for list slice getting with 3rd arg. | tuc-osg/micropython,mhoffma/micropython,trezor/micropython,blazewicz/micropython,AriZuu/micropython,kerneltask/micropython,swegener/micropython,MrSurly/micropython,mhoffma/micropython,hiway/micropython,alex-robbins/micropython,henriknelson/micropython,tuc-osg/micropython,adafruit/micropython,selste/micropython,ryannath... | tests/basics/list_slice.py | tests/basics/list_slice.py | # test list slices, getting values
x = list(range(10))
a = 2
b = 4
c = 3
print(x[:])
print(x[::])
print(x[::c])
print(x[:b])
print(x[:b:])
print(x[:b:c])
print(x[a])
print(x[a:])
print(x[a::])
print(x[a::c])
print(x[a:b])
print(x[a:b:])
print(x[a:b:c])
# these should not raise IndexError
print([][1:])
print([][-1:])
... | # test slices; only 2 argument version supported by Micro Python at the moment
x = list(range(10))
a = 2
b = 4
c = 3
print(x[:])
print(x[::])
#print(x[::c])
print(x[:b])
print(x[:b:])
#print(x[:b:c])
print(x[a])
print(x[a:])
print(x[a::])
#print(x[a::c])
print(x[a:b])
print(x[a:b:])
#print(x[a:b:c])
# these should not... | mit | Python |
44dbb16521d4fb1ceeb453d6ebab5c9161c260c5 | add gen_funcs | ickc/pantable | tests/files/native_test.py | tests/files/native_test.py | from pathlib import Path
import sys
import inspect
from typing import Tuple
from panflute import convert_text
from pantable.ast import PanTable
EXT = 'native'
DIR = Path(__file__).parent / EXT
def gen_funcs():
paths = list(Path(DIR).glob(f'*.{EXT}'))
paths.sort()
for path in paths:
print(f'''de... | from pathlib import Path
import sys
import inspect
from typing import Tuple
from panflute import convert_text
from pantable.ast import PanTable
def read(path: Path) -> Tuple[str, str]:
'''test parsing native table into Pantable
'''
print(f'Testing case {path}...', file=sys.stderr)
with open(path, 'r... | bsd-3-clause | Python |
fe3b309ae6935de3b3787cc11f5482963b65c5a6 | Fix indentation | damngamerz/coala-bears,seblat/coala-bears,coala/coala-bears,refeed/coala-bears,srisankethu/coala-bears,Shade5/coala-bears,arjunsinghy96/coala-bears,kaustubhhiware/coala-bears,mr-karan/coala-bears,sounak98/coala-bears,aptrishu/coala-bears,shreyans800755/coala-bears,srisankethu/coala-bears,ankit01ojha/coala-bears,vijeth-... | tests/js/JSHintBearTest.py | tests/js/JSHintBearTest.py | import os
from bears.js.JSHintBear import JSHintBear
from tests.LocalBearTestHelper import verify_local_bear
from coalib.misc.ContextManagers import prepare_file
test_file1 = """
var name = (function() { return 'Anton' }());
""".splitlines(keepends=True)
test_file2 = """
function () {
}()
""".splitlines(keepends=Tr... | import os
from bears.js.JSHintBear import JSHintBear
from tests.LocalBearTestHelper import verify_local_bear
from coalib.misc.ContextManagers import prepare_file
test_file1 = """
var name = (function() { return 'Anton' }());
""".splitlines(keepends=True)
test_file2 = """
function () {
}()
""".splitlines(keepends=Tr... | agpl-3.0 | Python |
49236730ca67124b5c65a742ef0bd5ea3e894bbe | use ' from django.utils.safestring' for 'mark_safe' | jrief/djangocms-cascade,jrief/djangocms-cascade,jrief/djangocms-cascade | cmsplugin_cascade/leaflet/settings.py | cmsplugin_cascade/leaflet/settings.py | from django.utils.safestring import mark_safe
CASCADE_PLUGINS = ['map']
def set_defaults(config):
config.setdefault('leaflet', {})
config['leaflet'].setdefault('tilesURL', 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'),
config['leaflet'].setdefault('default_position', {'lat': 30.0, 'lng': -40.0, 'zo... | from django import VERSION as DJANGO_VERSION
if DJANGO_VERSION < (2, 0):
from django.utils.text import mark_safe
else:
from django.utils.safestring import mark_safe
CASCADE_PLUGINS = ['map']
def set_defaults(config):
config.setdefault('leaflet', {})
config['leaflet'].setdefault('tilesURL', 'http://{s}... | mit | Python |
cdcc34eca763bfe7ab3611cc764587f8dd2885db | Fix bgsubtraction in case of all-nans. | VisualComputingInstitute/BiternionNets-ROS,VisualComputingInstitute/BiternionNets-ROS,VisualComputingInstitute/BiternionNets-ROS,VisualComputingInstitute/BiternionNets-ROS | scripts/common.py | scripts/common.py | import numpy as np
def deg2bit(deg):
rad = np.deg2rad(deg)
return np.array([np.cos(rad), np.sin(rad)]).T
def bit2deg(angles_bit):
return (np.rad2deg(np.arctan2(angles_bit[:,1], angles_bit[:,0])) + 360) % 360
def flipbiternions(bits):
bits = bits.copy()
bits[:,1] *= -1
return bits
def ensemble_degree... | import numpy as np
def deg2bit(deg):
rad = np.deg2rad(deg)
return np.array([np.cos(rad), np.sin(rad)]).T
def bit2deg(angles_bit):
return (np.rad2deg(np.arctan2(angles_bit[:,1], angles_bit[:,0])) + 360) % 360
def flipbiternions(bits):
bits = bits.copy()
bits[:,1] *= -1
return bits
def ensemble_degree... | mit | Python |
b892b6ae8091f7e3c1091b95512350c7e4c086d6 | fix all v output filename | chendaniely/collegiate_times_sentiment | src/08-word_outputs.py | src/08-word_outputs.py | import pandas as pd
df = pd.read_csv('output/word_sentiments.csv')
print(pd.crosstab(df.swn_pos, df.pos_neg, margins=True))
# write out 2x2 table values
# pos_n pos_v neg_n neg_v
df.ix[(df.pos_neg == 'neg') & (df.swn_pos == 'n'), 'word'].to_csv('output/words_neg_n.csv', index=False)
df.ix[(df.pos_neg == 'neg') & (df... | import pandas as pd
df = pd.read_csv('output/word_sentiments.csv')
print(pd.crosstab(df.swn_pos, df.pos_neg, margins=True))
# write out 2x2 table values
# pos_n pos_v neg_n neg_v
df.ix[(df.pos_neg == 'neg') & (df.swn_pos == 'n'), 'word'].to_csv('output/words_neg_n.csv', index=False)
df.ix[(df.pos_neg == 'neg') & (df... | mit | Python |
351c05b6e474b266a7594a775cb48cd7cfe0b833 | Allow linear referencing on rings. | abali96/Shapely,mouadino/Shapely,mindw/shapely,abali96/Shapely,jdmcbr/Shapely,jdmcbr/Shapely,mindw/shapely,mouadino/Shapely | shapely/linref.py | shapely/linref.py | """Linear referencing
"""
from shapely.topology import Delegating
class LinearRefBase(Delegating):
def _validate_line(self, ob):
super(LinearRefBase, self)._validate(ob)
if not ob.geom_type in ['LinearRing', 'LineString', 'MultiLineString']:
raise TypeError("Only linear types support ... | """Linear referencing
"""
from shapely.topology import Delegating
class LinearRefBase(Delegating):
def _validate_line(self, ob):
super(LinearRefBase, self)._validate(ob)
try:
assert ob.geom_type in ['LineString', 'MultiLineString']
except AssertionError:
raise Type... | bsd-3-clause | Python |
9818fb927bcc096fbb6a3b075be867a5709c3d0f | Add Process to the simpy namespace. | Uzere/uSim | simpy/__init__.py | simpy/__init__.py | # encoding: utf-8
"""
With SimPy, simulating is fun again!
"""
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from simpy.core import Simulation, Process, Interrupt, Failure
__all__ = ['Simulation', 'Interrupt', 'Failure', 'test']
__version__ = '3.0a1'
def test():
"""Runs SimPy’s te... | # encoding: utf-8
"""
With SimPy, simulating is fun again!
"""
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from simpy.core import Simulation, Interrupt, Failure
__all__ = ['Simulation', 'Interrupt', 'Failure', 'test']
__version__ = '3.0a1'
def test():
"""Runs SimPy’s test suite ... | mit | Python |
6424400e3051069e02e9f2a3d37fc51a4526bebd | Remove unused imports | dbrattli/aioreactive | test/test_forward_pipe.py | test/test_forward_pipe.py | import pytest
import asyncio
import logging
from aioreactive.testing import VirtualTimeEventLoop
from aioreactive.core import AsyncObservable, run, AsyncAnonymousObserver, Operators as _
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
@pytest.yield_fixture()
def event_loop():
loop = V... | import pytest
import asyncio
import logging
from aioreactive.testing import VirtualTimeEventLoop
from aioreactive.core import AsyncObservable, run, subscribe, AsyncStream, AsyncAnonymousObserver, Operators as _
from aioreactive.operators.pipe import pipe
from aioreactive.operators.to_async_iterable import to_async_ite... | mit | Python |
81b5f66bb87d8c8d12839d892a49362c8883baea | Put back fixture | dimitri-yatsenko/datajoint-python,eywalker/datajoint-python,datajoint/datajoint-python | tests/test_reconnection.py | tests/test_reconnection.py | """
Collection of test cases to test connection module.
"""
from nose.tools import assert_true, assert_false, assert_equal, raises
import datajoint as dj
import numpy as np
from datajoint import DataJointError
from . import CONN_INFO, PREFIX
class TestReconnect:
"""
test reconnection
"""
def setup(... | """
Collection of test cases to test connection module.
"""
from nose.tools import assert_true, assert_false, assert_equal, raises
import datajoint as dj
import numpy as np
from datajoint import DataJointError
from . import CONN_INFO, PREFIX
class TestReconnect:
"""
test reconnection
"""
def setup(... | lgpl-2.1 | Python |
a66eb866d6d900fa65f41f93512469cab9527678 | remove test prefix from helper classes | jschnurr/scrapyscript | tests/test_scrapyscript.py | tests/test_scrapyscript.py | import unittest
from scrapy.settings import Settings
from scrapy.spiders import Spider
import scrapy
from scrapyscript import Job, Processor, ScrapyScriptException
class MySpider(Spider):
name = 'myspider'
def start_requests(self):
yield scrapy.Request(self.url)
def parse(self, response):
... | import unittest
from scrapy.settings import Settings
from scrapy.spiders import Spider
import scrapy
from scrapyscript import Job, Processor, ScrapyScriptException
class TestSpider(Spider):
name = 'myspider'
def start_requests(self):
yield scrapy.Request(self.url)
def parse(self, response):
... | mit | Python |
27ce7bdc43ecafa9e0393ac53ba562ee9400495d | Improve conf_vars context manager (#6658) | nathanielvarona/airflow,airbnb/airflow,wooga/airflow,cfei18/incubator-airflow,mtagle/airflow,apache/airflow,apache/airflow,apache/airflow,lyft/incubator-airflow,Fokko/incubator-airflow,wileeam/airflow,mtagle/airflow,apache/incubator-airflow,airbnb/airflow,danielvdende/incubator-airflow,mistercrunch/airflow,apache/incub... | tests/test_utils/config.py | tests/test_utils/config.py | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | apache-2.0 | Python |
6f6e16cfabb7c3ff3f634718b16f87bd7705d284 | Add a couple more test cases for item list | maxalbert/tohu | tests/v7/test_item_list.py | tests/v7/test_item_list.py | from .context import tohu
from tohu.v7.item_list import ItemList
def test_item_list():
values = [11, 55, 22, 66, 33]
item_list = ItemList(values)
assert item_list.items == values
assert item_list == values
assert len(item_list) == 5
assert item_list[3] == 66
assert [x for x in item_list] =... | from .context import tohu
from tohu.v7.item_list import ItemList
def test_item_list():
values = [11, 55, 22, 66, 33]
item_list = ItemList(values)
assert item_list.items == values
assert item_list == values
assert len(item_list) == 5
assert item_list[3] == 66
assert [x for x in item_list] =... | mit | Python |
bec44bf260dc118a3e5b18a77ad7eddc952396e5 | Update tests/webapi/test_start.py | CCI-Tools/cate-core,CCI-Tools/cate-core | tests/webapi/test_start.py | tests/webapi/test_start.py | import json
import os
import unittest
from tornado.testing import AsyncHTTPTestCase
from cate.webapi.start import create_application
NETCDF_TEST_FILE = os.path.join(os.path.dirname(__file__), '..', 'data', 'precip_and_temp.nc')
# For usage of the tornado.testing.AsyncHTTPTestCase see http://www.tornadoweb.org/en/st... | import json
import os
import unittest
from tornado.testing import AsyncHTTPTestCase
from cate.webapi.start import create_application
NETCDF_TEST_FILE = os.path.join(os.path.dirname(__file__), '..', 'data', 'precip_and_temp.nc')
# For usage of the tornado.testing.AsyncHTTPTestCase see http://www.tornadoweb.org/en/st... | mit | Python |
a10ffbe623583c7e2d8b84fe4da01b2191c80dfb | Fix mocked IPython when IPython not available | shaunstanislaus/pyexperiment,shaunstanislaus/pyexperiment,kinverarity1/pyexperiment,shaunstanislaus/pyexperiment,kinverarity1/pyexperiment,DeercoderResearch/pyexperiment,kinverarity1/pyexperiment,shaunstanislaus/pyexperiment,DeercoderResearch/pyexperiment,duerrp/pyexperiment,duerrp/pyexperiment,DeercoderResearch/pyexpe... | tests/test_interactive.py | tests/test_interactive.py | """Tests the interactive utilities
Written by Peter Duerr
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
import unittest
import mock
import six
import sys
from pyexperiment.utils.interactive import embed_interac... | """Tests the interactive utilities
Written by Peter Duerr
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
import unittest
import mock
import six
from pyexperiment.utils.interactive import embed_interactive
class... | mit | Python |
9d2cdc21e357912fb72453efac41156c129cce10 | add common respone type as a function | Kilerd/nougat | misuzu/response.py | misuzu/response.py | from json import dumps
from .config import STATUS_CODES
class Response:
__slots__ = ('body', 'status', 'content_type')
def __init__(self, body='', status=200, content_type='text/html'):
self.content_type = content_type
self.body = body
self.status = status
@property
def body_... | from json import dumps
from .config import STATUS_CODES
class Response:
__slots__ = ('body', 'status', 'content_type')
def __init__(self, body='', status=200, content_type='text/html'):
self.content_type = content_type
self.body = body
self.status = status
@property
def body_... | mit | Python |
78308c6d73473ab95c872731be21a7497feb874c | add ability to specify output filename and optionally not provide template | shapiromatron/docxUtils | docxUtils/reports.py | docxUtils/reports.py | import abc
import os
from io import BytesIO
from docx import Document
from docx.shared import Inches
from docx.enum.section import WD_ORIENT
class DOCXReport(object):
def __init__(self, root_path, context):
self.root_path = root_path
self.context = context
def build_report(self):
""... | import abc
import os
from io import BytesIO
from docx import Document
from docx.shared import Inches
from docx.enum.section import WD_ORIENT
class DOCXReport(object):
def __init__(self, root_path, context):
self.root_path = root_path
self.context = context
def build_report(self):
""... | mit | Python |
ac39315fa54e0ce5acb4ee47130742257bf41c16 | Fix committed real DBHOSTNAME. | MTDdk/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,methane/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,denkab/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,sagenschneider/FrameworkBenchmark... | flask/app.py | flask/app.py | from flask import Flask, jsonify, request
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from random import randint
try:
import MySQLdb
mysql_schema = "mysql:"
except ImportError:
mysql_schema = "mysql+pymysql:"
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']... | from flask import Flask, jsonify, request
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from random import randint
try:
import MySQLdb
mysql_schema = "mysql:"
except ImportError:
mysql_schema = "mysql+pymysql:"
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']... | bsd-3-clause | Python |
a063c63d702681384061067c72d8d83f0ddc59de | Bump version. | mocketize/python-mocket,mindflayer/python-mocket | mocket/__init__.py | mocket/__init__.py | try:
# Py2
from mocket import mocketize, Mocket, MocketEntry, Mocketizer
except ImportError:
# Py3
from mocket.mocket import mocketize, Mocket, MocketEntry, Mocketizer
__all__ = ("mocketize", "Mocket", "MocketEntry", "Mocketizer")
__version__ = "3.8.0"
| try:
# Py2
from mocket import mocketize, Mocket, MocketEntry, Mocketizer
except ImportError:
# Py3
from mocket.mocket import mocketize, Mocket, MocketEntry, Mocketizer
__all__ = ("mocketize", "Mocket", "MocketEntry", "Mocketizer")
__version__ = "3.7.3"
| bsd-3-clause | Python |
b88f381f5825851f444b7a119a1526907b5a0c14 | Fix check parameter | lord63/zhihudaily,lord63/zhihudaily,lord63/zhihudaily | fetch_data.py | fetch_data.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import click
from zhihudaily.crawler import Crawler
@click.group()
def cli():
"""Simple script to fetch the zhihudaily news.
\b
- init database(deault will fetch 10 days' news)
$ python fetch_date.py init
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import click
from zhihudaily.crawler import Crawler
@click.group()
def cli():
"""Simple script to fetch the zhihudaily news.
\b
- init database(deault will fetch 10 days' news)
$ python fetch_date.py init
... | mit | Python |
755438791ff532279c20e4f4060e62207b85d0ce | Add vendor field in sale airport model https://github.com/egenerat/flight-manager/issues/20 | egenerat/flight-manager,egenerat/flight-manager,egenerat/gae-django,egenerat/gae-django,egenerat/flight-manager,egenerat/gae-django,egenerat/flight-manager | fm/models.py | fm/models.py | # -*- coding: utf-8 -*-
from django.db import models
import base64
class Mission(models.Model):
expiry_date = models.DateTimeField()
origin_country = models.CharField(max_length=30, blank=True)
country_nb = models.PositiveSmallIntegerField()
city_name = models.CharField(max_length=30)
mission_nb ... | # -*- coding: utf-8 -*-
from django.db import models
import base64
class Mission(models.Model):
expiry_date = models.DateTimeField()
origin_country = models.CharField(max_length=30, blank=True)
country_nb = models.PositiveSmallIntegerField()
city_name = models.CharField(max_length=30)
mission_nb ... | mit | Python |
70b037496140dd2e9e6d71508835390f0c85bc02 | Change year to 2016, try to guess author details from git config | ksonj/skltn | skltn/metadata.py | skltn/metadata.py | # -*- coding: utf-8 -*-
"""Project metadata
Information describing the project.
"""
import subprocess
def get_author_detail(arg='name'):
p = subprocess.Popen(['git', 'config', 'user.{}'.format(arg)],
stdout=subprocess.PIPE)
try:
out, _ = p.communicate()
except:
ou... | # -*- coding: utf-8 -*-
"""Project metadata
Information describing the project.
"""
# The package name, which is also the "UNIX name" for the project.
package = 'my_module'
project = "My Awesome Module"
project_no_spaces = project.replace(' ', '')
version = '0.1.0'
description = 'It does cool things'
authors = ['John... | mit | Python |
f9012b88f60f8e4ac96cb55aea763edc74ad586e | Move remove code down to fix undefined var error | samdroid-apps/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit,samdroid-apps/sugar-toolkit-gtk3,godiard/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit,godiard/sugar-toolkit-gtk3,Daksh/sugar-toolkit-gtk3,manuq/sugar-toolkit-gt... | shell/view/BuddyIcon.py | shell/view/BuddyIcon.py | from sugar.canvas.MenuIcon import MenuIcon
from view.BuddyMenu import BuddyMenu
class BuddyIcon(MenuIcon):
def __init__(self, shell, menu_shell, friend):
MenuIcon.__init__(self, menu_shell, icon_name='stock-buddy',
color=friend.get_color(), size=96)
self._shell = shell
self._friend = friend
def set_p... | from sugar.canvas.MenuIcon import MenuIcon
from view.BuddyMenu import BuddyMenu
class BuddyIcon(MenuIcon):
def __init__(self, shell, menu_shell, friend):
MenuIcon.__init__(self, menu_shell, icon_name='stock-buddy',
color=friend.get_color(), size=96)
self._shell = shell
self._friend = friend
def set_p... | lgpl-2.1 | Python |
b7c13f0dbfe9535f022856ee8ffec9ac21473149 | fix model url | undertherain/benchmarker,undertherain/benchmarker,undertherain/benchmarker,undertherain/benchmarker | benchmarker/modules/problems/res10ssd/opencv.py | benchmarker/modules/problems/res10ssd/opencv.py | from pathlib import Path
import cv2
def get_kernel(params, unparsed_args=None):
proto = "res10_300x300_ssd_deploy.prototxt"
weights = "res10_300x300_ssd_iter_140000.caffemodel"
BASE = Path("~/.cache/benchmarker/models").expanduser()
PATH_PROTO = BASE.joinpath(proto)
PATH_WEIGHTS = BASE.joinpath(... | from pathlib import Path
import cv2
def get_kernel(params, unparsed_args=None):
proto = "res10_300x300_ssd_deploy.prototxt.txt"
weights = "res10_300x300_ssd_iter_140000.caffemodel"
BASE = Path("~/.cache/benchmarker/models").expanduser()
PATH_PROTO = BASE.joinpath(proto)
PATH_WEIGHTS = BASE.joinp... | mpl-2.0 | Python |
de0bbf978695d206189ee4effb124234968525cb | Add a view to display PDF receipts | hobarrera/django-afip,hobarrera/django-afip | django_afip/views.py | django_afip/views.py | from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View
from .pdf import generate_receipt_pdf
class ReceiptHTMLView(View):
"""Renders a receipt as HTML."""
def get(self, request, pk):
return HttpResponse(
generate_recei... | from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View
from .pdf import generate_receipt_pdf
class ReceiptHTMLView(View):
def get(self, request, pk):
return HttpResponse(
generate_receipt_pdf(pk, request, True),
)... | isc | Python |
03d8a4e20ee4b6fd49495b7b047ea78d0b9a5bb4 | Make source utf-8 encoded bytes. | DMOJ/judge,DMOJ/judge,DMOJ/judge | dmoj/graders/base.py | dmoj/graders/base.py | class BaseGrader(object):
def __init__(self, judge, problem, language, source):
if isinstance(source, unicode):
source = source.encode('utf-8')
self.source = source
self.language = language
self.problem = problem
self.judge = judge
self.binary = self._gene... | class BaseGrader(object):
def __init__(self, judge, problem, language, source):
self.source = source
self.language = language
self.problem = problem
self.judge = judge
self.binary = self._generate_binary()
self._terminate_grading = False
self._current_proc = N... | agpl-3.0 | Python |
6e3f5d2c05c2c58e0c7a683c4f949794f77091c4 | remove macro that Google ICU no longer looks at | tensorflow/text,tensorflow/text,tensorflow/text | third_party/icu/BUILD.bzl | third_party/icu/BUILD.bzl | """Builds ICU library."""
package(
default_visibility = ["//visibility:public"],
)
licenses(["notice"]) # Apache 2.0
exports_files([
"icu4c/LICENSE",
"icu4j/main/shared/licenses/LICENSE",
])
cc_library(
name = "headers",
hdrs = glob(["icu4c/source/common/unicode/*.h"]),
includes = [
... | """Builds ICU library."""
package(
default_visibility = ["//visibility:public"],
)
licenses(["notice"]) # Apache 2.0
exports_files([
"icu4c/LICENSE",
"icu4j/main/shared/licenses/LICENSE",
])
cc_library(
name = "headers",
hdrs = glob(["icu4c/source/common/unicode/*.h"]),
includes = [
... | apache-2.0 | Python |
a773d29d7bce78abea28209e53909ab52eee36a9 | Use flask's redirect() method to go to result link | AlexMathew/tcg-ui | routes.py | routes.py | from flask import Flask, render_template, redirect
from setup_cardsets import CardOperations
co = CardOperations()
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/rules')
def rules():
return render_template('rules.html')
@app.route('/setup')
def setup():
retur... | from flask import Flask, render_template
from setup_cardsets import CardOperations
co = CardOperations()
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/rules')
def rules():
return render_template('rules.html')
@app.route('/setup')
def setup():
return render_t... | mit | Python |
0d0f7c3328f73a55fe811d17b05ba543f16a0018 | Fix missed keys keys property | translationexchange/tml-python,translationexchange/tml-python | tml/translation/missed.py | tml/translation/missed.py | # encoding: UTF-8
from json import dumps
class MissedKeys(object):
""" Object append missed key"""
def __init__(self, client):
self.client = client
self.keys = []
def submit(self, missed_keys):
""" Submit keys over API
Args:
missed keys
"""
... | # encoding: UTF-8
from json import dumps
class MissedKeys(object):
""" Object append missed key"""
def __init__(self, client):
self.client = client
def submit(self, missed_keys):
""" Submit keys over API
Args:
missed keys
"""
return self.client.... | mit | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.