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 |
|---|---|---|---|---|---|---|---|---|
b3f4c5211d33d8242b863f812421b37b22cd91cc | update deps, setup.py | psolbach/metadoc | setup.py | setup.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
from subprocess import call
from setuptools import setup, find_packages
from setuptools.command.install import install as _install
version = '0.3.1'
def _post_install(dir):
call([sys.executable, 'setup_post.py'],
cwd=os.path.join(dir, 'metadoc... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
from subprocess import call
from setuptools import setup, find_packages
from setuptools.command.install import install as _install
version = '0.2.21'
def _post_install(dir):
call([sys.executable, 'setup_post.py'],
cwd=os.path.join(dir, 'metado... | mit | Python |
8978c1b49f43465bc3cd51b3ee51350d44ed9ae7 | Bump tqdm from 4.38.0 to 4.39.0 | glidernet/ogn-python,glidernet/ogn-python,Meisterschueler/ogn-python,Meisterschueler/ogn-python,glidernet/ogn-python,glidernet/ogn-python,Meisterschueler/ogn-python,Meisterschueler/ogn-python | setup.py | setup.py | #!/usr/bin/env python3
from os import path
from setuptools import setup, find_packages
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='ogn-python',
versio... | #!/usr/bin/env python3
from os import path
from setuptools import setup, find_packages
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='ogn-python',
versio... | agpl-3.0 | Python |
05295bfa9edf99dfe66d21025088e00ae6152bfa | bump version to 0.3.5 | MatthewCox/colour-valgrind | setup.py | setup.py | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
try:
from pypandoc import convert
read_md = lambda f: convert(f, 'rst')
except ImportError:
print("warning: pypandoc module not found,"
"could not convert markdown README to RST")
read_md = lambda f... | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
try:
from pypandoc import convert
read_md = lambda f: convert(f, 'rst')
except ImportError:
print("warning: pypandoc module not found,"
"could not convert markdown README to RST")
read_md = lambda f... | mit | Python |
57b17e6edcbe1e5400e3ede82292c1cd1c38f4e4 | Bump version | Contraz/demosys-py | setup.py | setup.py | from setuptools import setup, find_packages
from pip.req import parse_requirements
def reqs_from_requirements_file():
reqs = parse_requirements('requirements.txt', session='hack')
return [str(r.req) for r in reqs]
setup(
name="demosys-py",
version="0.1.2",
description="Modern OpenGL 4.1+ Prototy... | from setuptools import setup, find_packages
from pip.req import parse_requirements
def reqs_from_requirements_file():
reqs = parse_requirements('requirements.txt', session='hack')
return [str(r.req) for r in reqs]
setup(
name="demosys-py",
version="0.1.1",
description="Modern OpenGL 4.1+ Prototy... | isc | Python |
2cc2bf3665246f1876e9c25911baf6e418a356db | Add include_package_data=True to setup | lamenezes/simple-model | setup.py | setup.py | import os
import sys
from pathlib import Path
from shutil import rmtree
from setuptools import setup, find_packages, Command
from simple_model.__version__ import __version__
here = Path(__file__).absolute().parent
with open(here / 'README.rst') as f:
readme = '\n' + f.read()
class UploadCommand(Command):
""... | import os
import sys
from pathlib import Path
from shutil import rmtree
from setuptools import setup, find_packages, Command
from simple_model.__version__ import __version__
here = Path(__file__).absolute().parent
with open(here / 'README.rst') as f:
readme = '\n' + f.read()
class UploadCommand(Command):
""... | mit | Python |
e846fff0060a431187e607fa0852b00265aff709 | fix bug #141 | ranaroussi/qtpylib,ranaroussi/qtpylib,ranaroussi/qtpylib | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""QTPyLib: Quantitative Trading Python Library
(https://github.com/ranaroussi/qtpylib)
Simple, event-driven algorithmic trading system written in
Python 3, that supports backtesting and live trading using
Interactive Brokers for market data and order execution.
"""
from ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""QTPyLib: Quantitative Trading Python Library
(https://github.com/ranaroussi/qtpylib)
Simple, event-driven algorithmic trading system written in
Python 3, that supports backtesting and live trading using
Interactive Brokers for market data and order execution.
"""
from ... | apache-2.0 | Python |
990d1a364dcfd62e700daba9945c35f96fbdfa5b | Order the main extensions list by name. | GNOME/extensions-web,GNOME/extensions-web,GNOME/extensions-web,GNOME/extensions-web,magcius/sweettooth,magcius/sweettooth | sweettooth/extensions/urls.py | sweettooth/extensions/urls.py |
from django.conf.urls.defaults import patterns, include, url
from django.views.generic.simple import direct_to_template
from django.views.generic.list_detail import object_list
from extensions import views, models
upload_patterns = patterns('',
url(r'^$', views.upload_file, dict(pk=None), name='extensions-upload... |
from django.conf.urls.defaults import patterns, include, url
from django.views.generic.simple import direct_to_template
from django.views.generic.list_detail import object_list
from extensions import views, models
upload_patterns = patterns('',
url(r'^$', views.upload_file, dict(pk=None), name='extensions-upload... | agpl-3.0 | Python |
b5a4708009e78c5727f2a54c54056df21983e958 | Fix SlackOAuth | singingwolfboy/flask-dance-slack | slack.py | slack.py | import os
import sys
import logging
from werkzeug.contrib.fixers import ProxyFix
from werkzeug.urls import url_encode, url_decode
import flask
from flask import Flask, redirect, url_for
from flask_dance.consumer import OAuth2ConsumerBlueprint
from raven.contrib.flask import Sentry
from requests.auth import AuthBase
fro... | import os
import sys
import logging
from werkzeug.contrib.fixers import ProxyFix
import flask
from flask import Flask, redirect, url_for
from flask_dance.consumer import OAuth2ConsumerBlueprint
from raven.contrib.flask import Sentry
from requests.auth import AuthBase
log = logging.getLogger(__name__)
log.setLevel(logg... | mit | Python |
e145d8012efbfb373dfe566845f3957777a3da5a | Clean up an unnecessary variable. | mjessome/sqltd | sqltd.py | sqltd.py | #!/usr/bin/env python
import sqlite3
import sys
import re
def runPage(db, html):
def parseStrings(s, query=[False]):
output = ''
if s == '<sql>':
query[0] = True
elif s == '</sql>':
query[0] = False
... | #!/usr/bin/env python
import sqlite3
import sys
import re
def runPage(db, html):
def parseStrings(s, query=[False]):
output = ''
if s == '<sql>':
query[0] = True
elif s == '</sql>':
query[0] = False
... | mit | Python |
49e9fbbd00a7732faa716e5e930ec63dbaa18983 | fix gumbel unit test | kengz/Unity-Lab,kengz/Unity-Lab | test/lib/test_distribution.py | test/lib/test_distribution.py | from flaky import flaky
from slm_lab.lib import distribution
import pytest
import torch
@pytest.mark.parametrize('pdparam_type', [
'probs', 'logits'
])
def test_argmax(pdparam_type):
pdparam = torch.tensor([1.1, 10.0, 2.1])
# test both probs or logits
pd = distribution.Argmax(**{pdparam_type: pdparam}... | from flaky import flaky
from slm_lab.lib import distribution
import pytest
import torch
@pytest.mark.parametrize('pdparam_type', [
'probs', 'logits'
])
def test_argmax(pdparam_type):
pdparam = torch.tensor([1.1, 10.0, 2.1])
# test both probs or logits
pd = distribution.Argmax(**{pdparam_type: pdparam}... | mit | Python |
f27e08b0dcace5b9f49c5b2a211347a2f50f8254 | Use tags or direct url | atulya2109/Stats-Royale-Python | stats.py | stats.py | from bs4 import BeautifulSoup
import requests
def statsRoyale(tag):
if not tag.find('/') == -1:
tag = tag[::-1]
pos = tag.find('/')
tag = tag[:pos]
tag = tag[::-1]
link = 'http://statsroyale.com/profile/' + tag
response = (requests.get(link)).text
soup = BeautifulSoup(response, 'html.parser')
descriptio... | from bs4 import BeautifulSoup
import requests
def statsRoyale(tag):
link = 'http://statsroyale.com/profile/' + tag
response = (requests.get(link)).text
soup = BeautifulSoup(response, 'html.parser')
stats = {}
content = soup.find_all('div', {'class':'content'})
stats['clan'] = content[0].get_text()
if stats['cl... | mit | Python |
f8ae46f22a9b5b1fc8215ac26aed6dfddf25c224 | set AUTOSYNTH_MULTIPLE_COMMITS=true for context aware commits (#320) | googleapis/nodejs-cloud-container,googleapis/nodejs-cloud-container | synth.py | synth.py | import synthtool as s
import synthtool.gcp as gcp
import logging
import subprocess
logging.basicConfig(level=logging.DEBUG)
AUTOSYNTH_MULTIPLE_COMMITS = True
# Run the gapic generator
gapic = gcp.GAPICMicrogenerator()
version = 'v1'
library = gapic.typescript_library(
'container',
generator_args={
... | import synthtool as s
import synthtool.gcp as gcp
import logging
import subprocess
logging.basicConfig(level=logging.DEBUG)
# Run the gapic generator
gapic = gcp.GAPICMicrogenerator()
version = 'v1'
library = gapic.typescript_library(
'container',
generator_args={
"grpc-service-config": f"google/c... | apache-2.0 | Python |
d54d202970610a59cb7fd60e51483c6e0db93d60 | update synth scripts to document/utilize apiEndpoint instead of serviceAddress option (#2165) | googleapis/google-cloud-php-text-to-speech,googleapis/google-cloud-php-text-to-speech | synth.py | synth.py | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | apache-2.0 | Python |
30d108b3a206d938ef67c112bc6c953a12c606af | Allow specifying custom host and port when starting app | rlucioni/typesetter,rlucioni/typesetter,rlucioni/typesetter | tasks.py | tasks.py | """Task functions for use with Invoke."""
from invoke import task
@task
def clean(context):
cmd = '$(npm bin)/gulp clean'
context.run(cmd)
@task
def requirements(context):
steps = [
'pip install -r requirements.txt',
'npm install',
'$(npm bin)/bower install',
]
cmd = ' &... | """Task functions for use with Invoke."""
from invoke import task
@task
def clean(context):
cmd = '$(npm bin)/gulp clean'
context.run(cmd)
@task
def requirements(context):
steps = [
'pip install -r requirements.txt',
'npm install',
'$(npm bin)/bower install',
]
cmd = ' &... | mit | Python |
c05b06577785bdf34f1fcd051ecf6d4398d2f77e | Add new release task w/ API doc prebuilding | thusoy/paramiko,CptLemming/paramiko,rcorrieri/paramiko,redixin/paramiko,Automatic/paramiko,jaraco/paramiko,esc/paramiko,ameily/paramiko,zarr12steven/paramiko,dorianpula/paramiko,mirrorcoder/paramiko,jorik041/paramiko,thisch/paramiko,dlitz/paramiko,paramiko/paramiko,digitalquacks/paramiko,fvicente/paramiko,SebastianDeis... | tasks.py | tasks.py | from os.path import join
from shutil import rmtree, move
from invoke import Collection, ctask as task
from invocations import docs as _docs
from invocations.packaging import publish
d = 'sites'
# Usage doc/API site (published as docs.paramiko.org)
docs_path = join(d, 'docs')
docs_build = join(docs_path, '_build')
d... | from os.path import join
from invoke import Collection, ctask as task
from invocations import docs as _docs
d = 'sites'
# Usage doc/API site (published as docs.paramiko.org)
path = join(d, 'docs')
docs = Collection.from_module(_docs, name='docs', config={
'sphinx.source': path,
'sphinx.target': join(path, '... | lgpl-2.1 | Python |
b7e42d4a231cc1c34e193e2bd719c134f7f29b0a | Use a minimum of 1% completness to not ship empty translations. | agustin380/django-localflavor,jieter/django-localflavor,rsalmaso/django-localflavor,infoxchange/django-localflavor,maisim/django-localflavor,thor/django-localflavor,zarelit/django-localflavor,M157q/django-localflavor,django/django-localflavor | tasks.py | tasks.py | import os
import os.path
import sys
from invoke import run, task
@task
def clean():
run('git clean -Xfd')
@task
def test(country='all'):
print('Python version: ' + sys.version)
test_cmd = 'coverage run `which django-admin.py` test --settings=tests.settings'
flake_cmd = 'flake8 --ignore=W801,E128,E50... | import os
import os.path
import sys
from invoke import run, task
@task
def clean():
run('git clean -Xfd')
@task
def test(country='all'):
print('Python version: ' + sys.version)
test_cmd = 'coverage run `which django-admin.py` test --settings=tests.settings'
flake_cmd = 'flake8 --ignore=W801,E128,E50... | bsd-3-clause | Python |
f62626799eddfea04ffad5005de09305a18f287d | Add linux dependencies task. | okuser/okcupyd,okuser/okcupyd,IvanMalison/okcupyd,IvanMalison/okcupyd | tasks.py | tasks.py | from invoke import Collection, task, run
from okcupyd import tasks
ns = Collection()
ns.add_collection(tasks, name='okcupyd')
@ns.add_task
@task(default=True)
def install():
run("python setup.py install")
@ns.add_task
@task
def pypi():
run("python setup.py sdist upload -r pypi")
@ns.add_task
@task(alia... | from invoke import Collection, task, run
from okcupyd import tasks
ns = Collection()
ns.add_collection(tasks, name='okcupyd')
@ns.add_task
@task(default=True)
def install():
run("python setup.py install")
@ns.add_task
@task
def pypi():
run("python setup.py sdist upload -r pypi")
@ns.add_task
@task(alia... | mit | Python |
61deb461f2a36413cbb6108e7e0e86fc81f44891 | Update to work with invoke >= 0.13 | mopidy/mopidy,jcass77/mopidy,jcass77/mopidy,adamcik/mopidy,jodal/mopidy,jodal/mopidy,jcass77/mopidy,kingosticks/mopidy,adamcik/mopidy,kingosticks/mopidy,mopidy/mopidy,jodal/mopidy,kingosticks/mopidy,adamcik/mopidy,mopidy/mopidy | tasks.py | tasks.py | import sys
from invoke import run, task
@task
def docs(ctx, watch=False, warn=False):
if watch:
return watcher(docs)
run('make -C docs/ html', warn=warn)
@task
def test(ctx, path=None, coverage=False, watch=False, warn=False):
if watch:
return watcher(test, path=path, coverage=coverage)... | import sys
from invoke import run, task
@task
def docs(watch=False, warn=False):
if watch:
return watcher(docs)
run('make -C docs/ html', warn=warn)
@task
def test(path=None, coverage=False, watch=False, warn=False):
if watch:
return watcher(test, path=path, coverage=coverage)
path ... | apache-2.0 | Python |
45f098b3664a11ef51cd66a11773bab923b02c91 | Make all exceptions inherit from ValueError | arthurdejong/python-stdnum,arthurdejong/python-stdnum,arthurdejong/python-stdnum | stdnum/exceptions.py | stdnum/exceptions.py | # exceptions.py - collection of stdnum exceptions
# coding: utf-8
#
# Copyright (C) 2013-2022 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the ... | # exceptions.py - collection of stdnum exceptions
# coding: utf-8
#
# Copyright (C) 2013 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the Licen... | lgpl-2.1 | Python |
ad9f0c488bf761fe83714377fce06ed93d2ec5f3 | Update navigation controller | PHSCRC/boxbot | controller/navigation.py | controller/navigation.py | import asyncio
class DriveMotorControl:
def __init__(self, left=0, right=1):
self.loop = asyncio.get_event_loop()
self._left = open("/var/run/motor{}".format(left),"w")
self._right = open("/var/run/motor{}".format(right),"w")
self.__left = 0
self.__right = 0
self.loo... | import asyncio
class ControlProtocol:
def connection_made(transport):
pass
def connection_lost(exc):
pass
class DriveMotorControl:
def __init__(self, left=0, right=1):
self.loop = asyncio.get_event_loop()
left = open("/var/run/motor{}".format(left),"w")
right = ope... | mit | Python |
63a2deeb5602eb9834232a592bac16501bb8c8de | Fix program name when using __main__ | pjbull/cookiecutter,dajose/cookiecutter,michaeljoseph/cookiecutter,luzfcb/cookiecutter,terryjbates/cookiecutter,audreyr/cookiecutter,stevepiercy/cookiecutter,hackebrot/cookiecutter,stevepiercy/cookiecutter,pjbull/cookiecutter,dajose/cookiecutter,hackebrot/cookiecutter,luzfcb/cookiecutter,michaeljoseph/cookiecutter,terr... | cookiecutter/__main__.py | cookiecutter/__main__.py | """Allow cookiecutter to be executable through `python -m cookiecutter`."""
from __future__ import absolute_import
from .cli import main
if __name__ == "__main__": # pragma: no cover
main(prog_name="cookiecutter")
| """Allow cookiecutter to be executable through `python -m cookiecutter`."""
from __future__ import absolute_import
from .cli import main
if __name__ == "__main__":
main()
| bsd-3-clause | Python |
f4ba2cba93222b4dd494caf487cdd6be4309e41a | Update labels for application form | p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles | studygroups/forms.py | studygroups/forms.py | from django import forms
from studygroups.models import StudyGroupSignup, Application
from localflavor.us.forms import USPhoneNumberField
class ApplicationForm(forms.ModelForm):
mobile = USPhoneNumberField(required=False)
class Meta:
model = Application
labels = {
'name': 'Please t... | from django import forms
from studygroups.models import StudyGroupSignup, Application
from localflavor.us.forms import USPhoneNumberField
class ApplicationForm(forms.ModelForm):
mobile = USPhoneNumberField(required=False)
class Meta:
model = Application
labels = {
'name': 'Please t... | mit | Python |
95686be0b45e350791c85c757acd450623b14d60 | test OK | josuebrunel/yahoo-fantasy-sport,unpairestgood/yahoo-fantasy-sport,unpairestgood/yahoo-fantasy-sport,josuebrunel/yahoo-fantasy-sport | tests.py | tests.py | import pdb
import logging
import unittest
from yahoo_oauth import OAuth2, OAuth1
from fantasy_sport import FantasySport
from fantasy_sport.utils import pretty_json, pretty_xml
logging.getLogger('yahoo_oauth').setLevel(logging.WARNING)
class TestFantasySport(unittest.TestCase):
def setUp(self,):
oauth =... | import pdb
import logging
import unittest
from yahoo_oauth import OAuth2, OAuth1
from fantasy_sport import FantasySport
from fantasy_sport.utils import pretty_json, pretty_xml
logging.getLogger('yahoo_oauth').setLevel(logging.WARNING)
class TestFantasySport(unittest.TestCase):
def setUp(self,):
oauth =... | mit | Python |
90bbb6604fdbb16c5a9d4390a429f2ce1c31035c | Add more tests, pend all dysfunctional tests. | fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.me... | tests/acceptance/test_rate.py | tests/acceptance/test_rate.py | import re
from pytest import fixture
from pytest import mark
from adhocracy_core.testing import annotator_login
from .shared import wait
from .shared import get_column_listing
from .shared import get_list_element
from .shared import get_listing_create_form
from .shared import login_god
from .test_comment import creat... | from pytest import fixture
from pytest import mark
from adhocracy_core.testing import annotator_login
from .shared import wait
from .shared import get_column_listing
from .shared import get_list_element
from .shared import get_listing_create_form
from .shared import login_god
from .test_comment import create_comment
... | agpl-3.0 | Python |
dc57d4b95e39f756858dc1d73c8f221f0bb1956c | add stubs | vastcharade/Vintageous,wbcustc/Vintageous,guillermooo-forks/Vintageous,himacro/Vintageous,denim2x/Vintageous,guillermooo-forks/Vintageous,gerardroche/Vintageous,himacro/Vintageous,denim2x/Vintageous,guillermooo-forks/Vintageous,zhangtuoparis13/Vintageous,zhangtuoparis13/Vintageous,xushuwei202/Vintageous,xushuwei202/Vin... | tests/commands/test__vi_cc.py | tests/commands/test__vi_cc.py | import unittest
from Vintageous.vi.constants import _MODE_INTERNAL_NORMAL
from Vintageous.vi.constants import MODE_NORMAL
from Vintageous.vi.constants import MODE_VISUAL
from Vintageous.vi.constants import MODE_VISUAL_LINE
from Vintageous.tests.commands import set_text
from Vintageous.tests.commands import ad... | import unittest
from Vintageous.vi.constants import _MODE_INTERNAL_NORMAL
from Vintageous.vi.constants import MODE_NORMAL
from Vintageous.vi.constants import MODE_VISUAL
from Vintageous.vi.constants import MODE_VISUAL_LINE
from Vintageous.tests.commands import set_text
from Vintageous.tests.commands import ad... | mit | Python |
6755255332039ab3c0ea60346f61420b52e2f474 | Fix intermittent failure in l10n language selector test | sgarrity/bedrock,TheoChevalier/bedrock,craigcook/bedrock,mkmelin/bedrock,TheoChevalier/bedrock,Sancus/bedrock,hoosteeno/bedrock,sylvestre/bedrock,schalkneethling/bedrock,Sancus/bedrock,analytics-pros/mozilla-bedrock,sylvestre/bedrock,glogiotatidis/bedrock,jgmize/bedrock,kyoshino/bedrock,mkmelin/bedrock,gerv/bedrock,dav... | tests/functional/test_l10n.py | tests/functional/test_l10n.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(b... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(b... | mpl-2.0 | Python |
da6c8f6daee4baa3798ab2c4b49fbc780e46ee3a | Rename test case for ObjectLoader to match | ironfroggy/straight.plugin,pombredanne/straight.plugin | tests.py | tests.py | #!/usr/bin/env python
import sys
import os
import unittest
from straight.plugin import loaders
class ModuleLoaderTestCase(unittest.TestCase):
def setUp(self):
self.loader = loaders.ModuleLoader()
sys.path.append(os.path.join(os.path.dirname(__file__), 'test-packages', 'more-test-plugins'))
... | #!/usr/bin/env python
import sys
import os
import unittest
from straight.plugin import loaders
class ModuleLoaderTestCase(unittest.TestCase):
def setUp(self):
self.loader = loaders.ModuleLoader()
sys.path.append(os.path.join(os.path.dirname(__file__), 'test-packages', 'more-test-plugins'))
... | mit | Python |
a18e195734983849a90786a4631987466952a232 | Set vestion to 0.4.2 in __init__.py | vovanbo/trafaretrecord,vovanbo/trafaretrecord | lib/recordclass/__init__.py | lib/recordclass/__init__.py | # The MIT License (MIT)
#
# Copyright (c) <2011-2014> <Shibzukhov Zaur, szport at gmail dot com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including witho... | # The MIT License (MIT)
#
# Copyright (c) <2011-2014> <Shibzukhov Zaur, szport at gmail dot com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including witho... | mit | Python |
d537ea32462c7ef46634d1527702c4c4a6d37e1e | Fix UDF test, take two | caseyching/Impala,theyaa/Impala,lirui-intel/Impala,ibmsoe/ImpalaPPC,gistic/PublicSpatialImpala,mapr/impala,cgvarela/Impala,rampage644/impala-cut,cchanning/Impala,cloudera/recordservice,caseyching/Impala,grundprinzip/Impala,placrosse/ImpalaToGo,kapilrastogi/Impala,brightchen/Impala,brightchen/Impala,tempbottle/Impala,ra... | tests/query_test/test_udfs.py | tests/query_test/test_udfs.py | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestUdfs(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
... | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestUdfs(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
... | apache-2.0 | Python |
9c0a83da524831cf557e24ad0a61c160c856dec9 | move definitions to the bottom again | fungusakafungus/cloudformation-jsonschema | tools.py | tools.py | # coding: utf-8
from pyquery import PyQuery as q
import json
from collections import OrderedDict
this = None
BASE = 'http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/'
def load(filename='resource.json'):
schema = json.load(open(filename), object_pairs_hook=OrderedDict)
return schema
def get_pq... | # coding: utf-8
from pyquery import PyQuery as q
import json
from collections import OrderedDict
this = None
BASE = 'http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/'
def load(filename='resource.json'):
schema = json.load(open(filename), object_pairs_hook=OrderedDict)
return schema
def get_pq... | mit | Python |
586cd6c864fdbdb3ac20aa49bdc6c550fa93aa2f | fix a testdir stragler | pathawks/pygments,pathawks/pygments,pathawks/pygments,pathawks/pygments,pathawks/pygments,pathawks/pygments,pathawks/pygments,pathawks/pygments,pathawks/pygments,pathawks/pygments,pathawks/pygments,pathawks/pygments,pathawks/pygments,pathawks/pygments,pathawks/pygments,pathawks/pygments | tests/test_latex_formatter.py | tests/test_latex_formatter.py | # -*- coding: utf-8 -*-
"""
Pygments LaTeX formatter tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: 2006-2007 by Georg Brandl.
:license: BSD, see LICENSE for more details.
"""
import os
import unittest
import tempfile
from pygments.formatters import LatexFormatter
from pygments.lexers import Python... | # -*- coding: utf-8 -*-
"""
Pygments LaTeX formatter tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: 2006-2007 by Georg Brandl.
:license: BSD, see LICENSE for more details.
"""
import os
import unittest
import tempfile
from pygments.formatters import LatexFormatter
from pygments.lexers import Python... | bsd-2-clause | Python |
07cfc39e50251384ddb647ccc7f73c98ed8cf7b9 | Save model with an interval of 1000 steps | vanhuyz/CycleGAN-TensorFlow,vanhuyz/CycleGAN-TensorFlow | train.py | train.py | import tensorflow as tf
from model import CycleGAN
from reader import Reader
from datetime import datetime
import os
X_TRAIN_FILE = 'data/tfrecords/apple.tfrecords'
Y_TRAIN_FILE = 'data/tfrecords/orange.tfrecords'
BATCH_SIZE = 1
def train():
current_time = datetime.now().strftime("%Y%m%d-%H%M")
checkpoints_dir =... | import tensorflow as tf
from model import CycleGAN
from reader import Reader
from datetime import datetime
import os
X_TRAIN_FILE = 'data/tfrecords/apple.tfrecords'
Y_TRAIN_FILE = 'data/tfrecords/orange.tfrecords'
BATCH_SIZE = 1
def train():
current_time = datetime.now().strftime("%Y%m%d-%H%M")
checkpoints_dir =... | mit | Python |
1970bad9d9933432154de2042c4ed74a8696b7f0 | fix timeout when no options are specified | caibo2014/teuthology,ivotron/teuthology,michaelsevilla/teuthology,t-miyamae/teuthology,yghannam/teuthology,michaelsevilla/teuthology,ktdreyer/teuthology,ktdreyer/teuthology,tchaikov/teuthology,dmick/teuthology,robbat2/teuthology,ceph/teuthology,yghannam/teuthology,dmick/teuthology,caibo2014/teuthology,zhouyuan/teutholo... | teuthology/task/thrashosds.py | teuthology/task/thrashosds.py | import contextlib
import logging
import ceph_manager
from teuthology import misc as teuthology
log = logging.getLogger(__name__)
@contextlib.contextmanager
def task(ctx, config):
"""
"Thrash" the OSDs by randomly marking them out/down (and then back
in) until the task is ended. This loops, and every op_d... | import contextlib
import logging
import ceph_manager
from teuthology import misc as teuthology
log = logging.getLogger(__name__)
@contextlib.contextmanager
def task(ctx, config):
"""
"Thrash" the OSDs by randomly marking them out/down (and then back
in) until the task is ended. This loops, and every op_d... | mit | Python |
e7b7709784e105114d490eaab655a16e9842a1ed | optimize post processor shouldn't run 'call' with shell and pipe. | ui/django-thumbnails | thumbnails/post_processors.py | thumbnails/post_processors.py | import imghdr
import os
from subprocess import call
import tempfile
import uuid
from django.core.files import File
def get_or_create_temp_dir():
temp_dir = os.path.join(tempfile.gettempdir(), 'thumbnails')
if not os.path.exists(temp_dir):
os.mkdir(temp_dir)
return temp_dir
def process(thumbnail... | import imghdr
import os
from subprocess import call, PIPE
import tempfile
import uuid
from django.core.files import File
def get_or_create_temp_dir():
temp_dir = os.path.join(tempfile.gettempdir(), 'thumbnails')
if not os.path.exists(temp_dir):
os.mkdir(temp_dir)
return temp_dir
def process(thu... | mit | Python |
27e30c4172f2da79168640799188f0394b88c9ec | Fix circular import between querysets.workflow and models.domain | botify-labs/python-simple-workflow,botify-labs/python-simple-workflow | swf/models/domain.py | swf/models/domain.py | # -*- coding: utf-8 -*-
from boto.swf.exceptions import SWFResponseError, SWFDomainAlreadyExistsError
from swf.constants import REGISTERED
from swf.core import ConnectedSWFObject
from swf.exceptions import AlreadyExistsError, DoesNotExistError
class Domain(ConnectedSWFObject):
"""Simple Workflow Domain wrapper
... | # -*- coding: utf-8 -*-
from boto.swf.exceptions import SWFResponseError, SWFDomainAlreadyExistsError
from swf.constants import REGISTERED
from swf.core import ConnectedSWFObject
from swf.querysets.workflow import WorkflowTypeQuerySet
from swf.exceptions import AlreadyExistsError, DoesNotExistError
class Domain(Con... | mit | Python |
157a09187bccfbfae9b4698159f3a889cb619dd6 | Call resp.json() | molly/boston-snowbot | utils.py | utils.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2015–2020 Molly White
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights... | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2015–2020 Molly White
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights... | mit | Python |
e2dd97f16f4f8223c25dbaf661863b3e7323a302 | add more make errors. i now need to add context lines. | escapewindow/mozharness,kartikgupta0909/mozilla-mozharness,escapewindow/mozharness,kartikgupta0909/build-mozharness,mozilla/build-mozharness,kartikgupta0909/build-mozharness,simar7/build-mozharness,armenzg/build-mozharness,armenzg/build-mozharness,simar7/build-mozharness,lissyx/build-mozharness,mozilla/build-mozharness... | mozharness/base/errors.py | mozharness/base/errors.py | #!/usr/bin/env python
"""Generic error regexes.
We could also create classes that generate these, but with the appropriate
level (please don't die on any errors; please die on any warning; etc.)
"""
# ErrorLists {{{1
""" TODO: more of these.
We could have a generic shell command error list (e.g. File not found,
perm... | #!/usr/bin/env python
"""Generic error regexes.
We could also create classes that generate these, but with the appropriate
level (please don't die on any errors; please die on any warning; etc.)
"""
# ErrorLists {{{1
""" TODO: more of these.
We could have a generic shell command error list (e.g. File not found,
perm... | mpl-2.0 | Python |
c967f59da33dec46ccbe73d7e7878e01715da236 | Add docstrings and comments to video module | richgieg/RichEmu86 | video.py | video.py | import graphics
class VideoController():
"""Represents a computer system's video controller."""
def power_on(self):
"""Powers on this video controller."""
print("VideoController.power_on()")
self._create_terminal_window()
def _create_terminal_window(self):
# Creates t... | import graphics
class VideoController():
def power_on(self):
print("VideoController.power_on()")
self._create_terminal_window()
def _create_terminal_window(self):
win = graphics.GraphWin("RichEmu86", 890, 408)
win.setBackground("black")
s = "RichEmu86 " * 8
i ... | mit | Python |
c705ef83607e09b2ed6e2b8d14aa6a6a7f9f57ea | Update __init__.py | selvakarthik21/newspaper,selvakarthik21/newspaper | newspaperdemo/__init__.py | newspaperdemo/__init__.py | from flask import Flask, request, render_template, redirect, url_for
from newspaper import Article
from xml.etree import ElementTree
app = Flask(__name__)
# Debug logging
import logging
import sys
# Defaults to stdout
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
try:
log.info('Loggi... | from flask import Flask, request, render_template, redirect, url_for, json
from newspaper import Article
from xml.etree import ElementTree
app = Flask(__name__)
# Debug logging
import logging
import sys
# Defaults to stdout
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
try:
log.info(... | mit | Python |
844270b6eee2eabfaa1b43c73ed8ffcab833586f | Bump to version 0.19.4 | reubano/meza,reubano/tabutils,reubano/meza,reubano/meza,reubano/tabutils,reubano/tabutils | tabutils/__init__.py | tabutils/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
tabutils
~~~~~~~~
Provides methods for reading and processing data from tabular formatted files
Attributes:
CURRENCIES [tuple(unicode)]: Currency symbols to remove from decimal
strings.
ENCODING (str): Default file encoding.... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
tabutils
~~~~~~~~
Provides methods for reading and processing data from tabular formatted files
Attributes:
CURRENCIES [tuple(unicode)]: Currency symbols to remove from decimal
strings.
ENCODING (str): Default file encoding.... | mit | Python |
c7665ba1988215fd27f0eb7f547a34104d8b921f | add MA | harry0519/nsnqt | nsnqtlib/tkpi/momentum.py | nsnqtlib/tkpi/momentum.py |
import numpy as np
import pandas as pd
#Moving average
def MA(data=[], timeperiod=10):
ma = []
ma_a = pd.DataFrame(data,columns=['MA']).rolling(window=timeperiod).mean()
for i in ma_a['MA']:
ma.append(i)
return ma
#MACD related indicators
#Moving average: there will be unstable period i... |
import numpy as np
#MACD related indicators
#Moving average: there will be unstable period in the beginning
#input: list of close price
def EMA(close=[], timeperiod=10):
ema = []
current = close[0]
for i in close:
current = (current*(timeperiod-1)+ 2*i)/(timeperiod+1)
ema.append(current)
... | bsd-2-clause | Python |
1045f8a2cedf86a401a2868f4092f5d416e8f3e9 | Bump to 0.26 | Calysto/octave_kernel,Calysto/octave_kernel | octave_kernel/__init__.py | octave_kernel/__init__.py | """An Octave kernel for Jupyter"""
__version__ = '0.26.0'
| """An Octave kernel for Jupyter"""
__version__ = '0.25.1'
| bsd-3-clause | Python |
dcc89b0d4757a4d2e0a541172ce3ded1f7e92014 | Create CDAP's HDFS directory | cdapio/cdap-ambari-service,cdapio/cdap-ambari-service | package/scripts/master.py | package/scripts/master.py | import sys
import ambari_helpers as helpers
from resource_management import *
class Master(Script):
def install(self, env):
print 'Install the CDAP Master';
import params
self.configure(env)
# Add repository file
helpers.add_repo(params.files_dir + params.repo_file, params.os_repo_dir)
# Inst... | import sys
import ambari_helpers as helpers
from resource_management import *
class Master(Script):
def install(self, env):
print 'Install the CDAP Master';
import params
self.configure(env)
# Add repository file
helpers.add_repo(params.files_dir + params.repo_file, params.os_repo_dir)
# Inst... | apache-2.0 | Python |
00bfbae48af80fd12db31aecc663373dce3fa1a8 | Format code | megaprojectske/megaprojects.co.ke,megaprojectske/megaprojects.co.ke,megaprojectske/megaprojects.co.ke | megaprojects/core/models.py | megaprojects/core/models.py | import uuid
from django.conf import settings
from django.db import models
class TimeStampedModel(models.Model):
"""
An abstract base class model that provides self-updating ``created`` and
``modified`` fields.
"""
created = models.DateTimeField(
auto_now_add=True, help_text='The time wh... | import uuid
from django.conf import settings
from django.db import models
class TimeStampedModel(models.Model):
"""
An abstract base class model that provides self-updating ``created`` and
``modified`` fields.
"""
created = models.DateTimeField(
auto_now_add=True, help_text='The time wh... | apache-2.0 | Python |
cdcae64d095a7cbab99e439bc37ee7009fe5c482 | Mark version 0.3.1 | sebasmagri/mezzanine_polls | mezzanine_polls/__init__.py | mezzanine_polls/__init__.py | __version__ = 0.3.1
| __version__ = 0.3
| bsd-2-clause | Python |
afaa2dd700a7474b81b981b266ee5aaa977d28d5 | Update team_rank_request.py to use response.json() | prcutler/nflpool,prcutler/nflpool | team_rank_request.py | team_rank_request.py | import requests
from requests.auth import HTTPBasicAuth
import secret
import json
x = 0
y = 0
parameters = 'teamstats'
response = requests.get(
'https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/playoff_team_standings.json?teamstats',
auth=HTTPBasicAuth(secret.msf_username, secret.msf_pw))
d... | import requests
from requests.auth import HTTPBasicAuth
import secret
import json
x = 0
y = 0
parameters = 'teamstats'
response = requests.get(
'https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/playoff_team_standings.json?teamstats',
auth=HTTPBasicAuth(secret.msf_username, secret.msf_pw))
r... | mit | Python |
f326dd569e9240c2b883e9c5f436728f321a0c61 | Add TransactionMiddleware | allanlei/django-multitenant | tenant/middleware.py | tenant/middleware.py | from django.core.urlresolvers import resolve
from django.shortcuts import get_object_or_404
from django.db import transaction
from tenant.models import Tenant
from tenant.utils import connect_tenant_provider, disconnect_tenant_provider
class TenantMiddleware(object):
def process_request(self, request):
r... | from django.core.urlresolvers import resolve
from django.shortcuts import get_object_or_404
from tenant.models import Tenant
from tenant.utils import connect_tenant_provider, disconnect_tenant_provider
class TenantMiddleware(object):
def process_request(self, request):
request.tenant = None
name ... | bsd-3-clause | Python |
5168c98ea9b903a06cb52c79da81fe598abcb570 | use correct import | missionpinball/mpf,missionpinball/mpf | mpf/devices/shot_profile.py | mpf/devices/shot_profile.py | """Shot profiles."""
from mpf.core.mode import Mode
from mpf.core.system_wide_device import SystemWideDevice
from mpf.core.mode_device import ModeDevice
class ShotProfile(ModeDevice, SystemWideDevice):
"""A shot profile."""
config_section = 'shot_profiles'
collection = 'shot_profiles'
class_label ... | """Shot profiles."""
from mpfmc.core.mode import Mode
from mpf.core.system_wide_device import SystemWideDevice
from mpf.core.mode_device import ModeDevice
class ShotProfile(ModeDevice, SystemWideDevice):
"""A shot profile."""
config_section = 'shot_profiles'
collection = 'shot_profiles'
class_labe... | mit | Python |
6e6e2e03da2f4ef141b51843ca16fdb52f0770ca | Use tokenized no-reply address in send_test_email. | dhcrzf/zulip,timabbott/zulip,hackerkid/zulip,brainwane/zulip,showell/zulip,synicalsyntax/zulip,punchagan/zulip,timabbott/zulip,synicalsyntax/zulip,andersk/zulip,hackerkid/zulip,jackrzhang/zulip,shubhamdhama/zulip,jackrzhang/zulip,showell/zulip,synicalsyntax/zulip,eeshangarg/zulip,shubhamdhama/zulip,synicalsyntax/zulip,... | zerver/management/commands/send_test_email.py | zerver/management/commands/send_test_email.py |
from typing import Any
from django.conf import settings
from django.core.mail import mail_admins, mail_managers, send_mail
from django.core.management import CommandError
from django.core.management.commands import sendtestemail
from zerver.lib.send_email import FromAddress
class Command(sendtestemail.Command):
... |
from typing import Any
from django.conf import settings
from django.core.mail import mail_admins, mail_managers, send_mail
from django.core.management import CommandError
from django.core.management.commands import sendtestemail
from zerver.lib.send_email import FromAddress
class Command(sendtestemail.Command):
... | apache-2.0 | Python |
a971b84541b991bbc14be73e94b633c88edcd567 | Remove unused vars | PolyFloyd/ledcubesim,PolyFloyd/ledcubesim,PolyFloyd/ledcubesim | programs/ledcube/audio.py | programs/ledcube/audio.py | #
# Copyright (c) 2014 PolyFloyd
#
import numpy.fft
import os
class Source:
def get_spectrum(self, signal):
signal = numpy.array([(s + 1) / 2 for s in signal], dtype=float)
spectrum = numpy.abs(numpy.fft.rfft(signal))
freqs = numpy.fft.fftfreq(spectrum.size, 1 / self.get_sample_rate(... | #
# Copyright (c) 2014 PolyFloyd
#
import io
import numpy.fft
import os
import pyaudio
class Source:
def get_spectrum(self, signal):
n = len(signal)
signal = numpy.array([(s + 1) / 2 for s in signal], dtype=float)
spectrum = numpy.abs(numpy.fft.rfft(signal))
freqs = numpy.fft... | mit | Python |
50628685c310703fb24f266dfd4d72b666eecfa4 | Update version to 1.0.0 (not yet tagged) | desihub/desisurvey,desihub/desisurvey | py/desisurvey/_version.py | py/desisurvey/_version.py | __version__ = '1.0.0'
| __version__ = '0.8.2.dev415'
| bsd-3-clause | Python |
5934d94c9644eaea850a27773db5890b68078477 | Load all api items | alexandermendes/pybossa-analyst,alexandermendes/pybossa-analyst,alexandermendes/pybossa-analyst,LibCrowds/libcrowds-analyst | pybossa_analyst/client.py | pybossa_analyst/client.py | # -*- coding: utf8 -*-
"""API client module for pybossa-analyst."""
import enki
class PyBossaClient(object):
"""A class for interacting with PyBossa."""
def __init__(self, app=None):
"""Init method."""
self.app = app
if app is not None: # pragma: no cover
self.init_app(a... | # -*- coding: utf8 -*-
"""API client module for pybossa-analyst."""
import enki
class PyBossaClient(object):
"""A class for interacting with PyBossa."""
def __init__(self, app=None):
"""Init method."""
self.app = app
if app is not None: # pragma: no cover
self.init_app(a... | unknown | Python |
73b7d0670414ec65a152d239a5c5c60464ce8ff9 | Fix bad import. Fixes #2196 | davidwaroquiers/pymatgen,gVallverdu/pymatgen,fraricci/pymatgen,vorwerkc/pymatgen,davidwaroquiers/pymatgen,fraricci/pymatgen,gVallverdu/pymatgen,fraricci/pymatgen,gVallverdu/pymatgen,gVallverdu/pymatgen,gmatteo/pymatgen,davidwaroquiers/pymatgen,gmatteo/pymatgen,davidwaroquiers/pymatgen,vorwerkc/pymatgen,vorwerkc/pymatge... | pymatgen/core/__init__.py | pymatgen/core/__init__.py | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This package contains core modules and classes for representing structures and
operations on them.
"""
import os
try:
from ruamel import yaml
except ImportError:
try:
import ruamel_yaml as... | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This package contains core modules and classes for representing structures and
operations on them.
"""
import os
try:
from ruamal import yaml
except ImportError:
try:
import ruamel_yaml as... | mit | Python |
d55f2b98822faa7d71f5fce2bfa980f8265e0610 | Use take() instead of takeSample() in PySpark kmeans example. | rednaxelafx/apache-spark,maropu/spark,ron8hu/spark,ddna1021/spark,mzl9039/spark,sachintyagi22/spark,sureshthalamati/spark,map222/spark,nchammas/spark,mzl9039/spark,xflin/spark,yanboliang/spark,dotunolafunmiloye/spark,cin/spark,xuanyuanking/spark,andrewor14/iolap,koeninger/spark,joseph-torres/spark,esi-mineset/spark,mde... | python/examples/kmeans.py | python/examples/kmeans.py | """
This example requires numpy (http://www.numpy.org/)
"""
import sys
import numpy as np
from pyspark import SparkContext
def parseVector(line):
return np.array([float(x) for x in line.split(' ')])
def closestPoint(p, centers):
bestIndex = 0
closest = float("+inf")
for i in range(len(centers)):
... | """
This example requires numpy (http://www.numpy.org/)
"""
import sys
import numpy as np
from pyspark import SparkContext
def parseVector(line):
return np.array([float(x) for x in line.split(' ')])
def closestPoint(p, centers):
bestIndex = 0
closest = float("+inf")
for i in range(len(centers)):
... | apache-2.0 | Python |
d680fca8bef783bd6fad7c71989ca51fb4725bc8 | upgrade to latest chatexchange+fix | NickVolynkin/SmokeDetector,NickVolynkin/SmokeDetector,ArtOfCode-/SmokeDetector,Charcoal-SE/SmokeDetector,Charcoal-SE/SmokeDetector,ArtOfCode-/SmokeDetector | ws.py | ws.py | #requires https://pypi.python.org/pypi/websocket-client/
import websocket
import threading
import json,os,sys,getpass,time
from findspam import FindSpam
from ChatExchange.chatexchange.client import *
import HTMLParser
parser=HTMLParser.HTMLParser()
if("ChatExchangeU" in os.environ):
username=os.environ["ChatExchang... | #requires https://pypi.python.org/pypi/websocket-client/
import websocket
import threading
import json,os,sys,getpass,time
from findspam import FindSpam
from ChatExchange.chatexchange.client import *
import HTMLParser
parser=HTMLParser.HTMLParser()
if("ChatExchangeU" in os.environ):
username=os.environ["ChatExchang... | apache-2.0 | Python |
af5b574fb785e65fd1292bb28e90d005be1ecd03 | Fix pep8 errors | meomancer/field-campaigner,meomancer/field-campaigner,meomancer/field-campaigner | reporter/test/test_osm.py | reporter/test/test_osm.py | # coding=utf-8
"""Test cases for the OSM module.
:copyright: (c) 2013 by Tim Sutton
:license: GPLv3, see LICENSE for more details.
"""
import os
from reporter.utilities import LOGGER
from reporter.osm import load_osm_document, extract_buildings_shapefile
from reporter.test.helpers import FIXTURE_PATH
from reporter.te... | # coding=utf-8
"""Test cases for the OSM module.
:copyright: (c) 2013 by Tim Sutton
:license: GPLv3, see LICENSE for more details.
"""
import os
from reporter.utilities import LOGGER
from reporter.osm import load_osm_document, extract_buildings_shapefile
from reporter.test.helpers import FIXTURE_PATH
from reporter.te... | bsd-3-clause | Python |
acf2d57fa49a5ed25275a279d04946178f8cedde | Fix formatting and add doc strings | McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research | reporting_scripts/base.py | reporting_scripts/base.py | import csv
from pymongo import MongoClient
class BaseEdX(object):
def __init__(self, args):
self.url = args.url
client = MongoClient(self.url)
self.db = client[args.db_name]
self.collections = None
self.output_directory = args.output_directory
self.row_limit = args... | import csv
from pymongo import MongoClient
class BaseEdX(object):
def __init__(self, args):
self.url = args.url
client = MongoClient(self.url)
self.db = client[args.db_name]
self.collections = None
self.output_directory = args.output_directory
self.row_limit = args... | mit | Python |
0e58ef45f45df0192be6c52cd34df5f1b5c5a028 | correct if condition | sathishcodes/Webhookskeleton-py,sathishcodes/Webhookskeleton-py | app.py | app.py | #!/usr/bin/env python
import urllib
import json
import os
from flask import Flask
from flask import request
from flask import make_response
# Flask app should start in global layout
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def webhook():
req = request.get_json(silent=True, force=True)
... | #!/usr/bin/env python
import urllib
import json
import os
from flask import Flask
from flask import request
from flask import make_response
# Flask app should start in global layout
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def webhook():
req = request.get_json(silent=True, force=True)
... | apache-2.0 | Python |
e33a06ad4d4a7494f925a96e9d272e32e4dc18ba | Return json when error occurs | philipbl/SpeakerCast,philipbl/talk_feed | app.py | app.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, request, json
from flask.ext.cors import CORS
import database
import rsser
import logging
import threading
logging.basicConfig(level=logging.INFO)
logging.getLogger("gospellibrary").setLevel(logging.WARNING)
logging.getLogger("requests").setLevel... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, request, json
from flask.ext.cors import CORS
import database
import rsser
import logging
import threading
logging.basicConfig(level=logging.INFO)
logging.getLogger("gospellibrary").setLevel(logging.WARNING)
logging.getLogger("requests").setLevel... | bsd-3-clause | Python |
d177d63ebc87208fdba4227377b2e1aebda8f077 | Add port code for Heroku | smizell/maze_server | app.py | app.py | import os
from flask import Flask, Response, request
from hypermedia_resource import HypermediaResource
from hypermedia_resource.wrappers import HypermediaResponse, ResponseBuilder
import maze
app = Flask(__name__)
# Helper functions for the views
def maze_resource(type_of):
"""
Sets up a HypermediaResource ... | from flask import Flask, Response, request
from hypermedia_resource import HypermediaResource
from hypermedia_resource.wrappers import HypermediaResponse, ResponseBuilder
import maze
app = Flask(__name__)
# Helper functions for the views
def maze_resource(type_of):
"""
Sets up a HypermediaResource for the re... | mit | Python |
096cd81f318e8446855fb806772c674328adc6b2 | Create app.py | rajeshrao04/news-api | app.py | app.py | #!/usr/bin/env python
from __future__ import print_function
from future.standard_library import install_aliases
install_aliases()
from urllib.parse import urlparse, urlencode
from urllib.request import urlopen, Request
from urllib.error import HTTPError
import json
import os
from flask import Flask
from flask impor... | #!/usr/bin/env python
from __future__ import print_function
from future.standard_library import install_aliases
install_aliases()
from urllib.parse import urlparse, urlencode
from urllib.request import urlopen, Request
from urllib.error import HTTPError
import json
import os
from flask import Flask
from flask impor... | apache-2.0 | Python |
8fc38abecd4a9cba6579c7a422b957748115f450 | disable CSRF token | Mouleshwar/Flask-S3-Uploader,themouli/Flask-S3-Uploader,Mouleshwar/Flask-S3-Uploader,themouli/Flask-S3-Uploader | app.py | app.py | from flask import Flask, render_template, flash
from flask_wtf import Form
from flask_wtf.file import FileField
from tools import s3_upload
import json
app = Flask(__name__)
app.config.from_object('config')
class UploadForm(Form):
example = FileField('Example File')
@app.route('/', methods=['POS... | from flask import Flask, render_template, flash
from flask_wtf import Form
from flask_wtf.file import FileField
from tools import s3_upload
import json
app = Flask(__name__)
app.config.from_object('config')
class UploadForm(Form):
example = FileField('Example File')
@app.route('/', methods=['POS... | mit | Python |
e33174b6fcf8110478ec84016781ed65df7eb055 | Add web-interface to utility | tildecross/tildex-notify | app.py | app.py | #!notify/bin/python3
import hug
import os
from pushbullet import Pushbullet
@hug.get()
@hug.cli()
def create_note(title: hug.types.text, content: hug.types.text):
api_key = os.environ["PB_API_KEY"]
pb = Pushbullet(api_key)
pb.push_note(title, content)
if __name__ == '__main__':
create_note.interfac... | #!notify/bin/python3
import hug
import os
from pushbullet import Pushbullet
@hug.cli()
def create_note(title: hug.types.text, content: hug.types.text):
api_key = os.environ["PB_API_KEY"]
pb = Pushbullet(api_key)
pb.push_note(title, content)
if __name__ == '__main__':
create_note.interface.cli()
| isc | Python |
ed3ee7caae9ce754e2ec098e8889bfbed2198aa6 | Print log msg before trying to write to log file | jiko/lovecraft_ebooks | bot.py | bot.py | #!/usr/bin/python
import init_twit as tw
import markovgen, time, re, random, codecs
# make a separate file for these reusable functions: bot.py
# main bot-specific app logic in app.py
corpus_file = 'corpus.txt'
with open(corpus_file) as text:
markov = markovgen.Markov(text)
def log(msg):
print msg
with codecs.ope... | #!/usr/bin/python
import init_twit as tw
import markovgen, time, re, random, codecs
# make a separate file for these reusable functions: bot.py
# main bot-specific app logic in app.py
corpus_file = 'corpus.txt'
with open(corpus_file) as text:
markov = markovgen.Markov(text)
def log(msg):
with codecs.open('log','a'... | mit | Python |
132b422e81c8a3f3de4d1600acdc6a71327bfc1e | Update bro .py | jacobdshimer/Bro-Log-Utility-Script | bro.py | bro.py | def bro(verbose, files=[]):
import subprocess
import os
import time
files = files.split("\n")
files.pop(-1)
if verbose == False:
epoch = time.time()
path = os.getcwd()
os.mkdir(path + "/" + str(epoch))
os.chdir(path + "/" + str(epoch))
for file in files:
subprocess.check_output(["bro","-r",file])
... | def combiner(verbose, files=[]):
import subprocess
import os
import time
files = files.split("\n")
files.pop(-1)
if verbose == False:
epoch = time.time()
path = os.getcwd()
os.mkdir(path + "/" + str(epoch))
os.chdir(path + "/" + str(epoch))
for file in files:
subprocess.check_output(["bro","-r",fil... | mit | Python |
4aad9aeb5acf0c8aba609a53f20107ec48cdfa2b | Initialise gpio | thomas-vl/car | car.py | car.py | import time, os, sys
import wiringpi as io
class light(object):
def __init__(self, pin):
#make pins into output
io.pinMode(pin,1)
#set output low
io.digitalWrite(pin,0)
#set variables
self.status = 0
self.pin = pin
def on(self):
#turn light on
... | import time, os, sys
import wiringpi as io
class light(object):
def __init__(self, pin):
#make pins into output
io.pinMode(pin,1)
#set output low
io.digitalWrite(pin,0)
#set variables
self.status = 0
self.pin = pin
def on(self):
#turn light on
... | mit | Python |
43a26a77d84fb8547564518a8469be69ed852cf1 | add discourse to csp | HTTPArchive/beta.httparchive.org,rviscomi/beta.httparchive.org,rviscomi/beta.httparchive.org,HTTPArchive/beta.httparchive.org,HTTPArchive/beta.httparchive.org,rviscomi/beta.httparchive.org | csp.py | csp.py | csp = {
'default-src': '\'self\'',
'style-src': [
'\'self\'',
'\'unsafe-inline\'',
'fonts.googleapis.com'
],
'script-src': [
'\'self\'',
'cdn.httparchive.org',
'www.google-analytics.com',
'use.fontawesome.com',
'cdn.speedcurve.com',
'spdcrv.global.ssl.fastly.net'
],
'font-src': [
'\'self\'',
... | csp = {
'default-src': '\'self\'',
'style-src': [
'\'self\'',
'\'unsafe-inline\'',
'fonts.googleapis.com'
],
'script-src': [
'\'self\'',
'cdn.httparchive.org',
'www.google-analytics.com',
'use.fontawesome.com',
'cdn.speedcurve.com',
'spdcrv.global.ssl.fastly.net'
],
'font-src': [
'\'self\'',
... | apache-2.0 | Python |
5000dc1045d2771b85528b60991e9ac2aad7d69d | fix bug to merge dict | mfuentesg/SyncSettings,adnedelcu/SyncSettings | sync_settings/libs/exceptions.py | sync_settings/libs/exceptions.py | # -*- coding: utf-8 -*-
import json
import sys
import traceback
class GistException(Exception):
def to_json(self):
json_error = json.loads(json.dumps(self.args[0]))
trace = traceback.extract_tb(sys.exc_info()[2])[-1]
return dict({
'filename': str(trace[0]),
'line': str(trace[1])
}, **js... | # -*- coding: utf-8 -*-
import json
import sys
import traceback
class GistException(Exception):
def to_json(self):
json_error = json.loads(json.dumps(self.args[0]))
trace = traceback.extract_tb(sys.exc_info()[2])[-1]
return json_error.update({
'filename': str(trace[0]),
'line': str(trace[1]... | mit | Python |
94c30a0efe0c3597678c64f46735ca7cd9990ccd | Revert Settings.py, only added admin schema | miguelcleon/ODM2-Admin,ocefpaf/ODM2-Admin,miguelcleon/ODM2-Admin,ocefpaf/ODM2-Admin,ocefpaf/ODM2-Admin,ocefpaf/ODM2-Admin,miguelcleon/ODM2-Admin,miguelcleon/ODM2-Admin | templatesAndSettings/settings.py | templatesAndSettings/settings.py | """
Keep this file untracked
"""
# SECURITY WARNING: keep the secret key used in production secret!
secret_key = 'random_secret_key_like_so_7472873649836'
media_root = 'C:/Users/leonmi/Google Drive/ODM2Djangoadmin/ODM2CZOData/upfiles/'
media_url = '/odm2testapp/upfiles/'
# Application definition
custom_template_path... | """
Keep this file untracked
"""
# SECURITY WARNING: keep the secret key used in production secret!
secret_key = 'random_secret_key_like_so_7472873649836'
media_root = '/Users/lsetiawan/Desktop/shared_ubuntu/APL/ODM2/ODM2-Admin/ODM2CZOData/upfiles/'
media_url = '/odm2testapp/upfiles/'
# Application definition
custom... | mit | Python |
2536526a383d1b2a921277970584ef5d3ba6073d | revert LIF base model | mwalton/artificial-olfaction,mwalton/artificial-olfaction,mwalton/artificial-olfaction | lif.py | lif.py | from numpy import *
from pylab import *
## setup parameters and state variables
T = 200 # total time to simulate (msec)
dt = 0.125 # simulation time step (msec)
time = arange(0, T+dt, dt) # time array
t_rest = 0 # initial refractory time
## LIF propertie... | from numpy import *
from pylab import *
## setup parameters and state variables
T = 1000 # total time to simulate (msec)
dt = 0.125 # simulation time step (msec)
time = arange(0, T+dt, dt) # time array
t_rest = 0 # initial refractory time
## LIF properti... | mit | Python |
3228b640d74dd1b06e9d96fb8265cc8c952074f6 | solve Flatten layer issue | AlexandruBurlacu/keras_squeezenet,AlexandruBurlacu/keras_squeezenet | run.py | run.py | from keras.models import Model, Sequential
from keras.layers import (Activation, Dropout, AveragePooling2D, Input,
Flatten, MaxPooling2D, Convolution2D)
from firemodule import FireModule
from keras.datasets import cifar10, mnist
from keras.optimizers import SGD
from keras.utils import np_utils
... | from keras.models import Model
from keras.layers import (Activation, Dropout, AveragePooling2D, Input,
Flatten, MaxPooling2D, Convolution2D)
from firemodule import FireModule
from keras.datasets import cifar10, mnist
from keras.optimizers import SGD
from keras.utils import np_utils
import nump... | mit | Python |
454740f2657efa88efa16abdba93dc427bcf4d70 | Add try catch to capture all the exceptions that might generate anywhere todo: need to capture exceptions in specific places and raise them to log from the main catch | manishgs/pdf-processor,anjesh/pdf-processor,manishgs/pdf-processor,anjesh/pdf-processor | run.py | run.py | from PdfProcessor import *
import argparse
from datetime import datetime
import ConfigParser
import ProcessLogger
import traceback
parser = argparse.ArgumentParser(description='Processes the pdf and extracts the text')
parser.add_argument('-i','--infile', help='File path of the input pdf file.', required=True)
parser.... | from PdfProcessor import *
import argparse
from datetime import datetime
import ConfigParser
import ProcessLogger
parser = argparse.ArgumentParser(description='Processes the pdf and extracts the text')
parser.add_argument('-i','--infile', help='File path of the input pdf file.', required=True)
parser.add_argument('-o'... | mit | Python |
ec09e3b35d431232feb0df1577b3fe6578b68704 | Remove old SSL code from run.py | virtool/virtool,virtool/virtool,igboyes/virtool,igboyes/virtool | run.py | run.py | import logging
import os
import sys
import json
import uvloop
import asyncio
from aiohttp import web
from setproctitle import setproctitle
from virtool.app import create_app
from virtool.app_init import get_args, configure
sys.dont_write_bytecode = True
logger = logging.getLogger("aiohttp.server")
setproctitle("vir... | import logging
import os
import sys
import ssl
import json
import uvloop
import asyncio
from aiohttp import web
from setproctitle import setproctitle
from virtool.app import create_app
from virtool.app_init import get_args, configure
sys.dont_write_bytecode = True
logger = logging.getLogger("aiohttp.server")
setpro... | mit | Python |
c15de13fa8dae840349463f6853f3edd3784ba6d | Update connect_db.py | zelongc/cloud-project,zelongc/cloud-project,zelongc/cloud-project | connect_db.py | connect_db.py | #!/usr/bin/python
from couchdb import Server
# server = Server() # connects to the local_server
# >>> remote_server = Server('http://example.com:5984/')
# >>> secure_remote_server = Server('https://username:password@example.com:5984/')
class db_server(object):
def __init__(self,username,login):
self.se... |
from couchdb import Server
# server = Server() # connects to the local_server
# >>> remote_server = Server('http://example.com:5984/')
# >>> secure_remote_server = Server('https://username:password@example.com:5984/')
class db_server(object):
def __init__(self,username,login):
self.secure_server=Serve... | mit | Python |
76a7b89cd8c935dec87ac89ec36b174c9a0636c4 | change lambda with broken typing to def | willmcgugan/rich | rich/pager.py | rich/pager.py | from abc import ABC, abstractmethod
from typing import Any, Callable
class Pager(ABC):
"""Base class for a pager."""
@abstractmethod
def show(self, content: str) -> None:
"""Show content in pager.
Args:
content (str): Content to be displayed.
"""
class SystemPager(P... | from abc import ABC, abstractmethod
from typing import Any, Callable
class Pager(ABC):
"""Base class for a pager."""
@abstractmethod
def show(self, content: str) -> None:
"""Show content in pager.
Args:
content (str): Content to be displayed.
"""
class SystemPager(P... | mit | Python |
9bd5662194007d995c924d2d57f6af5c75075472 | fix dashboard json output | mutantmonkey/ctfengine,mutantmonkey/ctfengine | ctfengine/views.py | ctfengine/views.py | import hashlib
from flask import abort, flash, jsonify, render_template, request, redirect, \
url_for
from ctfengine import app
from ctfengine import database
from ctfengine import lib
from ctfengine import models
@app.route('/')
def index():
scores = models.Handle.topscores()
total_points = database.... | import hashlib
from flask import abort, flash, jsonify, render_template, request, redirect, \
url_for
from ctfengine import app
from ctfengine import database
from ctfengine import lib
from ctfengine import models
@app.route('/')
def index():
scores = models.Handle.topscores()
total_points = database.... | isc | Python |
65e8aba17517247770ba27d796016c49fa41e0ab | correct handling of measure.ref() and aggregation selection in statutils' calculated aggregations | ubreddy/cubes,pombredanne/cubes,zejn/cubes,cesarmarinhorj/cubes,cesarmarinhorj/cubes,she11c0de/cubes,zejn/cubes,jell0720/cubes,zejn/cubes,pombredanne/cubes,noyeitan/cubes,noyeitan/cubes,jell0720/cubes,pombredanne/cubes,jell0720/cubes,ubreddy/cubes,ubreddy/cubes,she11c0de/cubes,cesarmarinhorj/cubes,noyeitan/cubes,she11c... | cubes/statutils.py | cubes/statutils.py | from collections import deque
from cubes.model import Attribute
def _wma(values):
n = len(values)
denom = n * (n + 1) / 2
total = 0.0
idx = 1
for val in values:
total += float(idx) * float(val)
idx += 1
return round(total / denom, 4)
def _sma(values):
# use all the values
... | from collections import deque
from cubes.model import Attribute
def _wma(values):
n = len(values)
denom = n * (n + 1) / 2
total = 0.0
idx = 1
for val in values:
total += float(idx) * float(val)
idx += 1
return round(total / denom, 4)
def _sma(values):
# use all the values
... | mit | Python |
582cacac1411312ad5e5dc132562883693f3877a | bump version | brentp/cyvcf2,brentp/cyvcf2,brentp/cyvcf2 | cyvcf2/__init__.py | cyvcf2/__init__.py | from .cyvcf2 import (VCF, Variant, Writer, r_ as r_unphased, par_relatedness,
par_het)
Reader = VCFReader = VCF
__version__ = "0.8.7"
| from .cyvcf2 import (VCF, Variant, Writer, r_ as r_unphased, par_relatedness,
par_het)
Reader = VCFReader = VCF
__version__ = "0.8.6"
| mit | Python |
e53ae572ac6c232a6afc01ae9ad2988ea1ef456a | Bump version. | Crandy/robobrowser,palaniyappanBala/robobrowser,jmcarp/robobrowser,emijrp/robobrowser,rcutmore/robobrowser | robobrowser/__init__.py | robobrowser/__init__.py | __version__ = '0.4.1'
from .browser import RoboBrowser
| __version__ = '0.4.0'
from .browser import RoboBrowser
| bsd-3-clause | Python |
70b4be757d671bc86876b4568632bb6fe6064001 | Fix a Django deprecation warning | fabiocaccamo/django-admin-interface,fabiocaccamo/django-admin-interface,fabiocaccamo/django-admin-interface | admin_interface/templatetags/admin_interface_tags.py | admin_interface/templatetags/admin_interface_tags.py | # -*- coding: utf-8 -*-
from django import template
from admin_interface.models import Theme
register = template.Library()
@register.simple_tag(takes_context = True)
def get_admin_interface_theme(context):
theme = None
request = context.get('request', None)
if request:
theme = getattr(reques... | # -*- coding: utf-8 -*-
from django import template
from admin_interface.models import Theme
register = template.Library()
@register.assignment_tag(takes_context = True)
def get_admin_interface_theme(context):
theme = None
request = context.get('request', None)
if request:
theme = getattr(re... | mit | Python |
2f3b5a6e0600f92ae0803ad3df44948dd5408444 | comment out stdout log handler | bweck/cssbot | cssbot/log.py | cssbot/log.py |
#
# Copyright (C) 2011 by Brian Weck
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
#
import logging
from datetime import date
import utils
def __configure_logging():
# configure the base logger for the pkg
l = logging.getLogger("cssbot")
l.setLevel(logging.DEBUG)
#... |
#
# Copyright (C) 2011 by Brian Weck
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
#
import logging
from datetime import date
import utils
def __configure_logging():
# configure the base logger for the pkg
l = logging.getLogger("cssbot")
l.setLevel(logging.DEBUG)
#... | mit | Python |
057110e3aa4007ad7221873029bed383ee1e0e3b | Remove platform check | Mortal/aiotkinter | aiotkinter.py | aiotkinter.py | import asyncio
import tkinter
class _TkinterSelector(asyncio.selectors._BaseSelectorImpl):
def __init__(self):
super().__init__()
self._tk = tkinter.Tk(useTk=0)
self._ready = []
def register(self, fileobj, events, data=None):
key = super().register(fileobj, events, data)
... | import asyncio
import tkinter
import sys
if sys.platform == 'win32':
raise ImportError('%s is not available on your platform'.format(__name__))
class _TkinterSelector(asyncio.selectors._BaseSelectorImpl):
def __init__(self):
super().__init__()
self._tk = tkinter.Tk(useTk=0)
self._read... | mit | Python |
7ab744fe8464ce85a27431adf94039c45551010f | Remove Google analytics code. | gustavofoa/dicasdejava.com.br,gustavofoa/dicasdejava.com.br,gustavofoa/dicasdejava.com.br,gustavofoa/dicasdejava.com.br,gustavofoa/dicasdejava.com.br | publishconf.py | publishconf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
# This file is only used if you use `make publish` or
# explicitly specify it as your config file.
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = 'https://dicasdejava.com.br'
RELATIVE_URLS = F... | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
# This file is only used if you use `make publish` or
# explicitly specify it as your config file.
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = 'https://dicasdejava.com.br'
RELATIVE_URLS = F... | mit | Python |
07a4cb667e702a1cbb758a3761ec41b89fa98313 | Add options to python script | colloquium/rhevm-api,markmc/rhevm-api,markmc/rhevm-api,colloquium/rhevm-api,markmc/rhevm-api | python/test.py | python/test.py | #!/usr/bin/env python
# Copyright (C) 2010 Red Hat, Inc.
#
# This is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of
# the License, or (at your option) any later version.
#
# This so... | #!/usr/bin/env python
# Copyright (C) 2010 Red Hat, Inc.
#
# This is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of
# the License, or (at your option) any later version.
#
# This so... | lgpl-2.1 | Python |
4656f7834f2c56f9dffcb775a5c9833304a3a55f | Fix doctests with Python 2 | jtauber/pyuca | pyuca/utils.py | pyuca/utils.py | """
utilities for formatting the datastructures used in pyuca.
Useful mostly for debugging output.
"""
from __future__ import unicode_literals
def hexstrings2int(hexstrings):
"""
list of hex strings to list of integers
>>> hexstrings2int(["0000", "0001", "FFFF"])
[0, 1, 65535]
"""
return [in... | """
utilities for formatting the datastructures used in pyuca.
Useful mostly for debugging output.
"""
from __future__ import unicode_literals
def hexstrings2int(hexstrings):
"""
list of hex strings to list of integers
>>> hexstrings2int(["0000", "0001", "FFFF"])
[0, 1, 65535]
"""
return [in... | mit | Python |
a23374939583b3954baa1418f12ce309442d31ff | Mark certain resources as uncompressible | heiths/allura,apache/incubator-allura,apache/allura,Bitergia/allura,lym/allura-git,apache/allura,apache/allura,leotrubach/sourceforge-allura,apache/incubator-allura,heiths/allura,heiths/allura,apache/incubator-allura,apache/incubator-allura,heiths/allura,lym/allura-git,leotrubach/sourceforge-allura,Bitergia/allura,Bite... | pyforge/pyforge/lib/widgets/form_fields.py | pyforge/pyforge/lib/widgets/form_fields.py | from pylons import c
from pyforge.model import User
from formencode import validators as fev
import ew
class MarkdownEdit(ew.InputField):
template='genshi:pyforge.lib.widgets.templates.markdown_edit'
validator = fev.UnicodeString()
params=['name','value','show_label']
show_label=True
name=None
... | from pylons import c
from pyforge.model import User
from formencode import validators as fev
import ew
class MarkdownEdit(ew.InputField):
template='genshi:pyforge.lib.widgets.templates.markdown_edit'
validator = fev.UnicodeString()
params=['name','value','show_label']
show_label=True
name=None
... | apache-2.0 | Python |
2b5e94f6c301932eb9387bba9a80414a714e2b38 | Tidy up the references | studiawan/pygraphc | pygraphc/abstraction/ClusterAbstraction.py | pygraphc/abstraction/ClusterAbstraction.py |
class ClusterAbstraction(object):
"""Get cluster abstraction based on longest common substring [jtjacques2010]_.
References
----------
.. [jtjacques2010] jtjacques, Longest common substring from more than two strings - Python.
http://stackoverflow.com/questions/2892931/longest-common-substring-... |
class ClusterAbstraction(object):
"""Get cluster abstraction based on longest common substring [jtjacques2010]_.
References
----------
.. [jtjacques2010] jtjacques, Longest common substring from more than two strings - Python.
http://stackoverflow.com/questions/2892931/longest-common-substr... | mit | Python |
ac61b2f99f91a274572e96be8f0136871288f1bb | update timer to be able to measure time more times | adaptive-learning/proso-apps,adaptive-learning/proso-apps,adaptive-learning/proso-apps | proso/util.py | proso/util.py | import re
import importlib
import time
_timers = {}
def timer(name):
now = time.time()
diff = None
if name in _timers:
diff = now - _timers[name]
_timers[name] = now
return diff
def instantiate(classname, *args, **kwargs):
matched = re.match('(.*)\.(\w+)', classname)
if matched ... | import re
import importlib
import time
_timers = {}
def timer(name):
now = time.clock()
if name in _timers:
diff = now - _timers[name]
return diff
_timers[name] = now
def instantiate(classname, *args, **kwargs):
matched = re.match('(.*)\.(\w+)', classname)
if matched is None:
... | mit | Python |
ce1350bb42028ad29356af275ab5b90257ccf0cb | fix import | Abbe98/yr-py | yr/__init__.py | yr/__init__.py | from .yr import YR | from yr import YR | mit | Python |
1cfc885597f14282245c68179922e27e3974a26f | use environment var for file location | SouthAfricaDigitalScience/gmp-deploy,SouthAfricaDigitalScience/gmp-deploy | publish-ci.py | publish-ci.py | import requests
import json
import os
# import tarfile
# def make_tarfile(output_filename, source_dir):
# with tarfile.open(output_filename, "w:gz") as tar:
# tar.add(source_dir, arcname=os.path.basename(source_dir))
uri = 'https://zenodo.org/api/deposit/depositions'
access_token = os.environ['ZENODO_API_... | import requests
import json
import os
# import tarfile
# def make_tarfile(output_filename, source_dir):
# with tarfile.open(output_filename, "w:gz") as tar:
# tar.add(source_dir, arcname=os.path.basename(source_dir))
uri = 'https://zenodo.org/api/deposit/depositions'
access_token = os.environ['ZENODO_API_... | apache-2.0 | Python |
99b65f7308a4b5719f5cf2e15200767af6780775 | deploy keynote images | pytexas/PyTexasBackend,pytexas/PyTexasBackend,pytexas/PyTexasBackend,pytexas/PyTexasBackend | pytx/files.py | pytx/files.py | import os
from django.conf import settings
JS_HEAD = []
JS = [
# 'raven.min.js',
# 'plugins/vue.min.js',
# 'showdown.min.js',
'pytexas.js',
]
CSS = [
'vuetify.min.css',
'global.css',
'pytexas.css',
]
IMAGES = [
'img/atx.svg',
'img/banner80.png',
'img/icon.svg',
'img/icon... | import os
from django.conf import settings
JS_HEAD = []
JS = [
# 'raven.min.js',
# 'plugins/vue.min.js',
# 'showdown.min.js',
'pytexas.js',
]
CSS = [
'vuetify.min.css',
'global.css',
'pytexas.css',
]
IMAGES = [
'img/atx.svg',
'img/banner80.png',
'img/icon.svg',
'img/icon... | mit | Python |
e9314b02c482314efeb7e36ecf3f6613f9a99adb | fix fetch loop block server | hainesc/daochain,DaoCloud/daochain,hainesc/daochain,DaoCloud/dao-chain,DaoCloud/dao-chain,Revolution1/daochain,Revolution1/daochain,DaoCloud/daochain,DaoCloud/daochain,DaoCloud/daochain,hainesc/daochain,DaoCloud/dao-chain,Revolution1/daochain,DaoCloud/dao-chain,hainesc/daochain,Revolution1/daochain | app/server.py | app/server.py | import logging
import os
import sys
import requests
from flask import Flask
from flask import send_file, send_from_directory
from api import load_api
from blockchain import web3_client
from settings import SOURCE_ROOT
from storage import Cache
log = logging.getLogger(__name__)
console_handler = logging.StreamHandle... | import logging
import os
import sys
import requests
from flask import Flask
from flask import send_file, send_from_directory
from gevent import sleep, spawn
from api import load_api
from blockchain import web3_client
from settings import SOURCE_ROOT
from storage import Cache
log = logging.getLogger(__name__)
consol... | apache-2.0 | Python |
69f24cd7a1936fb7dc4cfb03e3e97997332f633e | add portforward_get method | dreamhost/akanda-horizon,dreamhost/akanda-horizon | akanda/horizon/client.py | akanda/horizon/client.py | import requests
def portforward_get(request):
headers = {
"User-Agent" : "python-quantumclient",
"Content-Type" : "application/json",
"Accept" : "application/json",
"X-Auth-Token" : request.user.token.id
}
r = requests.get('http://0.0.0.0/v2.0/dhportforward.json', headers=he... | apache-2.0 | Python | |
b37814280dc06dbf8aefec4490f6b73a47f05c1a | Simplify python3 unicode fixer and make it replace all occurrences of __unicode__ with __str__. | live-clones/pybtex | custom_fixers/fix_alt_unicode.py | custom_fixers/fix_alt_unicode.py | # Taken from jinja2. Thanks, Armin Ronacher.
# See also http://lucumr.pocoo.org/2010/2/11/porting-to-python-3-a-guide
from lib2to3 import fixer_base
class FixAltUnicode(fixer_base.BaseFix):
PATTERN = "'__unicode__'"
def transform(self, node, results):
new = node.clone()
new.value = '__str__... | # Taken from jinja2. Thanks, Armin Ronacher.
# See also http://lucumr.pocoo.org/2010/2/11/porting-to-python-3-a-guide
from lib2to3 import fixer_base
from lib2to3.fixer_util import Name, BlankLine
class FixAltUnicode(fixer_base.BaseFix):
PATTERN = """
func=funcdef< 'def' name='__unicode__'
... | mit | Python |
8f4918a63e312309e835c3a9fc0513ddd6b4bbc1 | test restore resnet | MohammadChavosh/VQA | restore_resnet.py | restore_resnet.py | __author__ = 'Mohammad'
import tensorflow as tf
sess = tf.Session()
#First let's load meta graph and restore weights
saver = tf.train.import_meta_graph('data/tensorflow-resnet-pretrained-20160509/ResNet-L152.meta')
saver.restore(sess, 'data/tensorflow-resnet-pretrained-20160509/ResNet-L152.ckpt')
for i in tf.get_col... | __author__ = 'Mohammad'
import tensorflow as tf
sess = tf.Session()
#First let's load meta graph and restore weights
saver = tf.train.import_meta_graph('data/tensorflow-resnet-pretrained-20160509/ResNet-L152.meta')
saver.restore(sess, 'data/tensorflow-resnet-pretrained-20160509/ResNet-L152.ckpt')
for i in tf.get_col... | apache-2.0 | Python |
5632447a202ef3a83e5b96d11cbbc653fafac99b | Use os.getlogin to get login user name. | j717273419/ibus,Keruspe/ibus,ibus/ibus,luoxsbupt/ibus,ueno/ibus,luoxsbupt/ibus,fujiwarat/ibus,j717273419/ibus,ueno/ibus,ibus/ibus-cros,ibus/ibus,fujiwarat/ibus,phuang/ibus,j717273419/ibus,ueno/ibus,Keruspe/ibus,ueno/ibus,j717273419/ibus,ueno/ibus,luoxsbupt/ibus,ibus/ibus-cros,ibus/ibus,luoxsbupt/ibus,phuang/ibus,luoxsb... | ibus/common.py | ibus/common.py | # vim:set et sts=4 sw=4:
#
# ibus - The Input Bus
#
# Copyright (c) 2007-2008 Huang Peng <shawn.p.huang@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of ... | # vim:set et sts=4 sw=4:
#
# ibus - The Input Bus
#
# Copyright (c) 2007-2008 Huang Peng <shawn.p.huang@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of ... | lgpl-2.1 | Python |
eb4cda636a0b0ceb5312b161e97ae5f8376c9f8e | Change biolookup test to work around service bug | johnbachman/indra,bgyori/indra,johnbachman/indra,bgyori/indra,bgyori/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/indra,sorgerlab/indra | indra/tests/test_biolookup_client.py | indra/tests/test_biolookup_client.py | from indra.databases import biolookup_client
def test_lookup_curie():
curie = 'pubchem.compound:40976'
res = biolookup_client.lookup_curie(curie)
assert res['name'] == '(17R)-13-ethyl-17-ethynyl-17-hydroxy-11-' \
'methylidene-2,6,7,8,9,10,12,14,15,16-decahydro-1H-' \
'cyclopenta[a]phenanth... | from indra.databases import biolookup_client
def test_lookup_curie():
curie = 'pubchem.compound:40976'
res = biolookup_client.lookup_curie(curie)
assert res['name'] == '(17R)-13-ethyl-17-ethynyl-17-hydroxy-11-' \
'methylidene-2,6,7,8,9,10,12,14,15,16-decahydro-1H-' \
'cyclopenta[a]phenanth... | bsd-2-clause | Python |
7fd2060f2241bcff6849d570406dc057b9c7f8d1 | Fix the message string | taedori81/satchless,fusionbox/satchless,fusionbox/satchless,fusionbox/satchless | satchless/cart/views.py | satchless/cart/views.py | # -*- coding: utf-8 -*-
from django.contrib import messages
from django.shortcuts import get_object_or_404, redirect
from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _
from django.views.decorators.http import require_POST
from . import models
from . import forms
d... | # -*- coding: utf-8 -*-
from django.contrib import messages
from django.shortcuts import get_object_or_404, redirect
from django.template.response import TemplateResponse
from django.utils.translation import ugettext
from django.views.decorators.http import require_POST
from . import models
from . import forms
def ca... | bsd-3-clause | Python |
80691fa6d517b39a6656a2afc0635f485fd49974 | add dependencies (#18406) | LLNL/spack,LLNL/spack,iulian787/spack,LLNL/spack,iulian787/spack,iulian787/spack,LLNL/spack,LLNL/spack,iulian787/spack,iulian787/spack | var/spack/repos/builtin/packages/gconf/package.py | var/spack/repos/builtin/packages/gconf/package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Gconf(AutotoolsPackage):
"""GConf is a system for storing application preferences."""
... | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Gconf(AutotoolsPackage):
"""GConf is a system for storing application preferences."""
... | lgpl-2.1 | Python |
bd0960cda8a66b843035935c7caa9f20b38b4d0d | Add 0.16.0 and address test suite issues (#27604) | LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack | var/spack/repos/builtin/packages/gpgme/package.py | var/spack/repos/builtin/packages/gpgme/package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Gpgme(AutotoolsPackage):
"""GPGME is the standard library to access GnuPG
functions... | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Gpgme(AutotoolsPackage):
"""GPGME is the standard library to access GnuPG
functions... | lgpl-2.1 | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.