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 |
|---|---|---|---|---|---|---|---|---|
9e4fbcab21ffb1ec79330ef25c7a3de98cb20e37 | Fix up python syntax | openaustralia/morph,openaustralia/morph,openaustralia/morph,openaustralia/morph,openaustralia/morph,openaustralia/morph,openaustralia/morph | docker_images/morph-mitmdump/mitmproxy/log_to_morph.py | docker_images/morph-mitmdump/mitmproxy/log_to_morph.py | # Run this with dotenv mitmdump -q -a -s mitmproxy/log_to_morph.py --confdir mitmproxy
import urllib
import os
# Doing this to be able to handle running this under mitmproxy 0.12 and 0.17.1
try:
from mitmproxy.script import concurrent
except ImportError:
pass
try:
from libmproxy.script import concurrent
... | # Run this with dotenv mitmdump -q -a -s mitmproxy/log_to_morph.py --confdir mitmproxy
import urllib
import os
# Doing this to be able to handle running this under mitmproxy 0.12 and 0.17.1
try:
from mitmproxy.script import concurrent
except ImportError:
pass
try:
from libmproxy.script import concurrent
... | agpl-3.0 | Python |
5d188a71ae43ec8858f985dddbb0ff970cd18e73 | Fix DomainsConfig.name to fix rtfd build | watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder | feder/domains/apps.py | feder/domains/apps.py | from django.apps import AppConfig
class DomainsConfig(AppConfig):
name = "feder.domains"
| from django.apps import AppConfig
class DomainsConfig(AppConfig):
name = "domains"
| mit | Python |
7b3525c227b3867cd68683bcebc4100c83712909 | Make Device.public_key a BinaryField for easier querying | keybar/keybar | src/keybar/models/device.py | src/keybar/models/device.py | # -*- coding: utf-8 -*-
import hashlib
from Crypto.PublicKey import RSA
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import force_bytes
from keybar.utils.crypto import prettify_fingerprint
from keybar.utils.db import KeybarModel
class Device(Keybar... | # -*- coding: utf-8 -*-
import hashlib
from Crypto.PublicKey import RSA
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import force_bytes
from keybar.utils.crypto import prettify_fingerprint
from keybar.utils.db import KeybarModel
class Device(Keybar... | bsd-3-clause | Python |
32e67631500df93c41cbd56dbdd5f638476e29d3 | fix bugs in fulltests | avlach/univbris-ocf,avlach/univbris-ocf,avlach/univbris-ocf,avlach/univbris-ocf | src/python/openflow/tests/full/prepare_ch.py | src/python/openflow/tests/full/prepare_ch.py | '''
Created on May 19, 2010
@author: jnaous
'''
import sys
from os.path import join, dirname
import traceback
PYTHON_DIR = join(dirname(__file__), "../../../")
sys.path.append(PYTHON_DIR)
def main(argv):
try:
from expedient.common.tests.commands import call_env_command, Env
proj_dir, ch_host,... | '''
Created on May 19, 2010
@author: jnaous
'''
import sys
from os.path import join, dirname
PYTHON_DIR = join(dirname(__file__), "../../../")
sys.path.append(PYTHON_DIR)
def main(argv):
from expedient.common.tests.commands import call_env_command, Env
proj_dir, ch_host, ch_username, ch_passwd, om_host, om_p... | bsd-3-clause | Python |
b6b4c09fbee80eedcd1945f17fb0f04211afa974 | Package up README and LICENSE. Closes #11. | JASchilz/AnkiSyncDuolingo | build.py | build.py | import os
from zipfile import ZipFile
def project_files(path):
result = []
for root, dirs, files in os.walk(path):
result += [os.path.join(root, f) for f in files if '.pyc' not in f]
return result
if __name__ == '__main__':
with ZipFile('duolingo_sync.zip', 'w') as myzip:
myzip... | import os
from zipfile import ZipFile
def project_files(path):
result = []
for root, dirs, files in os.walk(path):
result += [os.path.join(root, f) for f in files if '.pyc' not in f]
return result
if __name__ == '__main__':
with ZipFile('duolingo_sync.zip', 'w') as myzip:
myzip... | mit | Python |
1e68ea979e345a687fcc5a744716a0d29d86e861 | Add newrelic stuff to wsgi file. | turtleloveshoes/kitsune,YOTOV-LIMITED/kitsune,MziRintu/kitsune,turtleloveshoes/kitsune,iDTLabssl/kitsune,safwanrahman/linuxdesh,safwanrahman/kitsune,safwanrahman/kitsune,NewPresident1/kitsune,safwanrahman/linuxdesh,feer56/Kitsune2,orvi2014/kitsune,orvi2014/kitsune,feer56/Kitsune2,YOTOV-LIMITED/kitsune,asdofindia/kitsun... | wsgi/kitsune.wsgi | wsgi/kitsune.wsgi | import os
import site
from datetime import datetime
try:
import newrelic.agent
except ImportError:
newrelic = False
if newrelic:
newrelic_ini = os.getenv('NEWRELIC_PYTHON_INI_FILE', False)
if newrelic_ini:
newrelic.agent.initialize(newrelic_ini)
else:
newrelic = False
# Remember... | import os
import site
from datetime import datetime
# Remember when mod_wsgi loaded this file so we can track it in nagios.
wsgi_loaded = datetime.now()
# Add the zamboni dir to the python path so we can import manage.
wsgidir = os.path.dirname(__file__)
site.addsitedir(os.path.abspath(os.path.join(wsgidir, '../')))
... | bsd-3-clause | Python |
0833587b1e0627c79b38c83865efba991cfcc871 | update wordcount example | danmichaelo/mwtemplates | scripts/wordcount.py | scripts/wordcount.py | #!/usr/bin/env python
#encoding=utf-8
from __future__ import unicode_literals
import argparse
import logging
import mwclient
from danmicholoparser import MainText, DanmicholoParseError
logger = logging.getLogger()
logger.setLevel(logging.INFO)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging... | #!/usr/bin/env python
#encoding=utf-8
from __future__ import unicode_literals
import argparse
import mwclient
from danmicholoparser import DanmicholoParser, DanmicholoParseError
parser = argparse.ArgumentParser( description = 'Prints wordcount for all revisions of a page. ' \
+ 'May take a long time to run, with... | mit | Python |
c078f6dd4e7aebbe02ca9c96533042f3b758f0cb | Tweak to __init__.py to give other import options | EoRImaging/katalogss | katalogss/__init__.py | katalogss/__init__.py | from . import fhd_pype
from . import katalogss
from . import kg_utils
from . import utils
# use the below style of import if you want the things inside the various files
# to be in the katalogss namespace rather than the katalogss.file namespace
# e.g: katalogss.clip_comps vs katalogss.katalogss.clip_comps
# from .fhd_... | from .fhd_pype import *
from .katalogss import *
from .kg_utils import *
from .utils import *
| bsd-2-clause | Python |
dce237e1161a5e6bd796d8ff07a442546f3dac8b | Add stubs for tests which are to be written. | peak6/st2,punalpatel/st2,Plexxi/st2,punalpatel/st2,Plexxi/st2,emedvedev/st2,lakshmi-kannan/st2,lakshmi-kannan/st2,tonybaloney/st2,peak6/st2,emedvedev/st2,StackStorm/st2,tonybaloney/st2,punalpatel/st2,peak6/st2,StackStorm/st2,nzlosh/st2,pixelrebel/st2,Plexxi/st2,tonybaloney/st2,lakshmi-kannan/st2,emedvedev/st2,nzlosh/st... | st2api/tests/unit/controllers/v1/test_pack_configs.py | st2api/tests/unit/controllers/v1/test_pack_configs.py | # Licensed to the StackStorm, Inc ('StackStorm') 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 "License"); you may not use th... | # Licensed to the StackStorm, Inc ('StackStorm') 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 "License"); you may not use th... | apache-2.0 | Python |
486b25f9df25bac954eaae6ebb269b9e6c784d05 | Fix variable spelling | gunthercox/chatterbot-corpus | tests/test_data.py | tests/test_data.py | from __future__ import unicode_literals
from unittest import TestCase
from chatterbot_corpus.corpus import Corpus
class CorpusUtilsTestCase(TestCase):
"""
This test case is designed to make sure that all
corpus data adheres to a few general rules.
"""
def setUp(self):
self.corpus = Corpus... | from __future__ import unicode_literals
from unittest import TestCase
from chatterbot_corpus.corpus import Corpus
class CorpusUtilsTestCase(TestCase):
"""
This test case is designed to make sure that all
corpus data adheres to a few general rules.
"""
def setUp(self):
self.corpus = Corpus... | bsd-3-clause | Python |
8220e8974523837d25adb28c4d7f945e43c1cd63 | fix typo | ImmobilienScout24/aws-monocyte-alarming-lambda | build.py | build.py | from pybuilder.core import use_plugin, init, Author
import os
use_plugin("python.core")
use_plugin("python.unittest")
use_plugin("python.install_dependencies")
use_plugin("python.flake8")
use_plugin("python.coverage")
use_plugin("python.distutils")
use_plugin("pypi:pybuilder_aws_plugin")
name = "aws-monocyte-alarming... | from pybuilder.core import use_plugin, init, Author
import os
use_plugin("python.core")
use_plugin("python.unittest")
use_plugin("python.install_dependencies")
use_plugin("python.flake8")
use_plugin("python.coverage")
use_plugin("python.distutils")
use_plugin("pypi:pybuilder_aws_plugin")
name = "aws-monocyte-alarming... | apache-2.0 | Python |
3c134dcae2569bd97cd009389055b721cca8a81c | add test_env | brennv/namedtupled,brennv/namedtupled | tests/test_docs.py | tests/test_docs.py | import namedtupled
import pytest
def test_getting_started():
data = {'binks': {'says': 'meow'}}
cat = namedtupled.map(data)
assert cat.binks.says == 'meow'
# cat = namedtupled.map(data, name='Cat')
# cat # Cat(binks=NT(says='meow'))
def test_map():
data = {'binks': {'says': 'meow'}}
cat... | import namedtupled
import pytest
def test_getting_started():
data = {'binks': {'says': 'meow'}}
cat = namedtupled.map(data)
assert cat.binks.says == 'meow'
# cat = namedtupled.map(data, name='Cat')
# cat # Cat(binks=NT(says='meow'))
def test_map():
data = {'binks': {'says': 'meow'}}
cat... | mit | Python |
959b58ee3520678b9c955ebed1ea46bcfb115597 | Fix test misc cases | lepture/mistune | tests/test_misc.py | tests/test_misc.py | import mistune3 as mistune
from unittest import TestCase
class TestMiscCases(TestCase):
def test_none(self):
self.assertEqual(mistune.html(None), '')
def test_before_parse_hooks(self):
def _add_name(md, state):
state.env['name'] = 'test'
md = mistune.create_markdown()
... | import mistune
from unittest import TestCase
class TestMiscCases(TestCase):
def test_none(self):
self.assertEqual(mistune.html(None), '')
def test_before_parse_hooks(self):
def _add_name(md, s, state):
state['name'] = 'test'
return s, state
md = mistune.create... | bsd-3-clause | Python |
d98f34668a108ca7410a4cb9c659b65766c99427 | Test send_keys literal / non-literal | tony/libtmux | tests/test_pane.py | tests/test_pane.py | # -*- coding: utf-8 -*-
"""Test for tmuxp Pane object."""
from __future__ import absolute_import, unicode_literals, with_statement
import logging
logger = logging.getLogger(__name__)
def test_resize_pane(session):
""" Test Pane.resize_pane(). """
window = session.attached_window
window.rename_window('t... | # -*- coding: utf-8 -*-
"""Test for tmuxp Pane object."""
from __future__ import absolute_import, unicode_literals, with_statement
import logging
logger = logging.getLogger(__name__)
def test_resize_pane(session):
""" Test Pane.resize_pane(). """
window = session.attached_window
window.rename_window('t... | bsd-3-clause | Python |
60413d7dac72b0d6993731139d7ea4d1f4b78100 | Check stats reults is numbers.Number vs int | silas/ops | tests/test_stat.py | tests/test_stat.py | import helper
import datetime
import grp
import pwd
import numbers
import os
import unittest
import uuid
import ops
class StatTestCase(unittest.TestCase):
def setUp(self):
self.workspace = helper.Workspace()
self.uid = os.geteuid()
self.user = pwd.getpwuid(self.uid)[0]
self.gid = ... | import helper
import datetime
import grp
import pwd
import os
import unittest
import uuid
import ops
class StatTestCase(unittest.TestCase):
def setUp(self):
self.workspace = helper.Workspace()
self.uid = os.geteuid()
self.user = pwd.getpwuid(self.uid)[0]
self.gid = os.getgid()
... | mit | Python |
7741968b9d48afc7ac135742774ae911e2611c83 | Cover case when seq is oneven | CodersOfTheNight/verata | tests/test_util.py | tests/test_util.py | from grazer.util import time_convert, grouper
class TestTimeConvert(object):
def test_seconds(self):
assert time_convert("10s") == 10
def test_minutes(self):
assert time_convert("2m") == 120
def test_hours(self):
assert time_convert("3h") == 3 * 60 * 60
class TestGrouper(objec... | from grazer.util import time_convert, grouper
class TestTimeConvert(object):
def test_seconds(self):
assert time_convert("10s") == 10
def test_minutes(self):
assert time_convert("2m") == 120
def test_hours(self):
assert time_convert("3h") == 3 * 60 * 60
class TestGrouper(objec... | mit | Python |
ef060a18216d652df6efa866b6433102262831d8 | Remove close_called test (no longer supported in python 3) | justinsalamon/scaper | tests/test_util.py | tests/test_util.py | # CREATED: 10/15/16 7:52 PM by Justin Salamon <justin.salamon@nyu.edu>
'''
Tests for functions in util.py
'''
from scaper.util import _close_temp_files
from scaper.util import _set_temp_logging_level
import tempfile
import os
import logging
def test_close_temp_files():
'''
Create a bunch of temp files and t... | # CREATED: 10/15/16 7:52 PM by Justin Salamon <justin.salamon@nyu.edu>
'''
Tests for functions in util.py
'''
from scaper.util import _close_temp_files
from scaper.util import _set_temp_logging_level
import tempfile
import os
import logging
def test_close_temp_files():
'''
Create a bunch of temp files and t... | bsd-3-clause | Python |
33868d5c5a4c305f0a1f067810839c8e4ade36e0 | test level>1 cases for pywt.downcoef and pywt.upcoef | kwohlfahrt/pywt,rgommers/pywt,kwohlfahrt/pywt,aaren/pywt,rgommers/pywt,eriol/pywt,aaren/pywt,eriol/pywt,aaren/pywt,ThomasA/pywt,ThomasA/pywt,rgommers/pywt,michelp/pywt,grlee77/pywt,eriol/pywt,PyWavelets/pywt,PyWavelets/pywt,kwohlfahrt/pywt,michelp/pywt,ThomasA/pywt,rgommers/pywt,michelp/pywt,grlee77/pywt | pywt/tests/test__pywt.py | pywt/tests/test__pywt.py | #!/usr/bin/env python
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.testing import run_module_suite, assert_allclose
import pywt
def test_upcoef_docstring():
data = [1, 2, 3, 4, 5, 6]
(cA, cD) = pywt.dwt(data, 'db2', 'sp1')
rec = pywt.upcoef('a', cA, 'db... | #!/usr/bin/env python
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.testing import run_module_suite, assert_allclose
import pywt
def test_upcoef_docstring():
data = [1, 2, 3, 4, 5, 6]
(cA, cD) = pywt.dwt(data, 'db2', 'sp1')
rec = pywt.upcoef('a', cA, 'db... | mit | Python |
aa6df5b1ca4801cdaa85f7546c292be4f34e0107 | Rename tests so that they run. | gtagency/pyrostest,gtagency/pyrostest | test/pyrostest/test_system.py | test/pyrostest/test_system.py | import pytest
import pyrostest
class TestSpinUp(pyrostest.RosTest):
def test_noop(self):
pass
@pyrostest.launch_node('pyrostest', 'add_one.py')
def test_launches_node(self):
pass
class TestFailureCases(pyrostest.RosTest):
@pytest.mark.xfail(strict=True)
@pyrostest.launch_node('th... | import pytest
import pyrostest
class TestSpinUp(pyrostest.RosTest):
def noop(self):
pass
@pyrostest.launch_node('pyrostest', 'add_one.py')
def launches_node(self):
pass
class FailureCases(pyrostest.RosTest):
@pytest.mark.xfail(strict=True)
@pyrostest.launch_node('this_isnt_a_proj... | mit | Python |
9c1d460f791272094a677ae3681306f0e0c60886 | Bump to version 0.1.0. | pbs/agora-proc | agora/__init__.py | agora/__init__.py | __version__ = '0.1.0'
| __version__ = '0.0.1'
| apache-2.0 | Python |
ace813e11baa73d73e63255e21ebe89f242a4855 | Bump version | slash-testing/backslash-python,vmalloc/backslash-python | backslash/__version__.py | backslash/__version__.py | __version__ = '2.28.4'
| __version__ = '2.28.2'
| bsd-3-clause | Python |
6c96b3d4f797a172bbb6a10a46bed52af61fa3aa | Bump version | slash-testing/backslash-python,vmalloc/backslash-python | backslash/__version__.py | backslash/__version__.py | __version__ = '2.28.6'
| __version__ = '2.28.4'
| bsd-3-clause | Python |
77a1b12d9cb4c93186e8406a80327ee6368772c7 | Bump version | christang/django-registration-1.5,christang/django-registration-1.5 | registration/__init__.py | registration/__init__.py | VERSION = (1, 1, 0, 'beta', 1)
def get_version():
"Returns a PEP 386-compliant version number from VERSION."
assert len(VERSION) == 5
assert VERSION[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
... | VERSION = (1, 0, 0, 'final', 0)
def get_version():
"Returns a PEP 386-compliant version number from VERSION."
assert len(VERSION) == 5
assert VERSION[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases... | bsd-3-clause | Python |
16c659bb822963224047bc7b7393a484cca6a8f0 | fix lastminute | sbauza/badger | badger/cmd/lastminute.py | badger/cmd/lastminute.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
# d... | # 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
# d... | apache-2.0 | Python |
162700c488275b057964f16659f3846c930a0c4f | Add utility function for retrieving the active registration backend. | aptivate/django-registration,rafaduran/django-pluggable-registration,QPmedia/django-registration,QPmedia/django-registration,siddharthsarda/django-registration,maraujop/django-registration,CoatedMoose/django-registration,CoatedMoose/django-registration,newvem/django-registration,christang/django-registration-1.5,thedod... | registration/__init__.py | registration/__init__.py | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
def get_backend():
"""
Return an instance of the registration backend for use on this
site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise
``django.cor... | bsd-3-clause | Python | |
370001ad384445053edb34c484f53ec33cea738c | Use 'verbose' flag in main.py to gate printing | samjabrahams/anchorhub | anchorhub/main.py | anchorhub/main.py | """
Command-line entry to AnchorHub, main method is here.
"""
import anchorhub.cmdparse as cmdparse
import anchorhub.messages as messages
import anchorhub.normalization.normalize_opts as normalize_opts
import anchorhub.validation.validate_opts as validate_opts
import anchorhub.validation.validate_files as validate_fil... | """
Command-line entry to AnchorHub, main method is here.
"""
import anchorhub.cmdparse as cmdparse
import anchorhub.messages as messages
import anchorhub.normalization.normalize_opts as normalize_opts
import anchorhub.validation.validate_opts as validate_opts
import anchorhub.validation.validate_files as validate_fil... | apache-2.0 | Python |
c44a019cfbfccf166ff6850178991816b2ef7874 | Refactor Imports | smoqadam/PyFladesk,smoqadam/PyFladesk | gui.py | gui.py | import sys
import webbrowser
from PyQt5 import QtCore, QtWidgets, QtWebKitWidgets, QtGui
def init_gui(application, port=5000, width=300, height=400,
window_title="PyFladesk", icon="appicon.png"):
ROOT_URL = 'http://localhost:{}'.format(port)
# open links in browser from http://stackoverflow.co... | import sys
import webbrowser
from PyQt5.QtCore import QThread, QUrl
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtWebKitWidgets import QWebView, QWebPage
def init_gui(application, port=5000, width=300, height=400,
window_title="PyFladesk", icon="appico... | mit | Python |
2012717cb08527d0ca5ce5e6189357457825cc6b | add CTCP VERSION listener | sammdot/circa | circa.py | circa.py | import logging
import client
import importlib
import modules
import sys
import time
from util.nick import nicklower
from util.mask import match
class Circa(client.Client):
version = "circa 0.9 http://github.com/sammdot/circa"
def __init__(self, conf):
conf["autoconn"] = False
for setting in "server nick usern... | import logging
import client
import importlib
import modules
import sys
import time
from util.nick import nicklower
from util.mask import match
class Circa(client.Client):
modules = {}
def __init__(self, conf):
conf["autoconn"] = False
for setting in "server nick username realname admins".split():
if setti... | bsd-3-clause | Python |
cc498485834579b828c460f40c1965e240d48ecb | fix clean.py to be platform independent | svn2github/libtorrent-rasterbar-trunk,svn2github/libtorrent-rasterbar-trunk,svn2github/libtorrent-rasterbar-trunk,svn2github/libtorrent-rasterbar-trunk | clean.py | clean.py | import os
import shutil
to_delete = [
'session_stats',
'libtorrent_logs*',
'round_trip_ms.log',
'dht.log',
'upnp.log',
'natpmp.log',
'bin',
'test_tmp_*'
]
directories = [
'examples',
'test',
'.',
'tools'
]
for d in directories:
for f in to_delete:
path = os.path.join(d, f)
print path
try:
shuti... | import os
to_delete = [
'session_stats',
'libtorrent_logs*',
'round_trip_ms.log',
'dht.log',
'upnp.log',
'natpmp.log',
'bin',
'test_tmp_*'
]
directories = [
'examples',
'test',
'.',
'tools'
]
for d in directories:
for f in to_delete:
path = os.path.join(d, f)
print path
os.system('rm -rf %s' % pat... | bsd-3-clause | Python |
cddbd0f37dab341a2e06153bae693744f87233d7 | Remove -profile-mode=stopwatch | oinume/dmm-eikaiwa-fft,oinume/dmm-eikaiwa-fft,oinume/lekcije,oinume/lekcije,oinume/lekcije,oinume/lekcije,oinume/dmm-eikaiwa-fft,oinume/dmm-eikaiwa-fft,oinume/lekcije,oinume/lekcije | clock.py | clock.py | from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
scheduler = BlockingScheduler()
@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
print("Run notifier (interval=1)")
subprocess.check_... | from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
scheduler = BlockingScheduler()
@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
print("Run notifier (interval=1)")
subprocess.check_... | mit | Python |
6fd3e1948486cdb63a5144d5dedc8eba096c3dff | Remove redundant comment | Yubico/yubikey-manager,Yubico/yubikey-manager | ykman/piv/util.py | ykman/piv/util.py | # Copyright (c) 2018 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditi... | # Copyright (c) 2018 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditi... | bsd-2-clause | Python |
0f2baa83e2669ade20591f60939dcb44940b5af4 | Add chunk() | The-Compiler/dotfiles,The-Compiler/dotfiles,The-Compiler/dotfiles | startup.py | startup.py | import sys
from pprint import pprint as pp # convenience
try:
from rich import pretty
except ImportError:
pass
else:
pretty.install()
del pretty
def chunk(elems, n):
for i in range(0, len(elems), n):
yield elems[i:i+n]
sys.ps1 = '\001\033[96m\002>>> \001\033[0m\002'
sys.ps2 = '\001\033[9... | import sys
from pprint import pprint as pp # convenience
try:
from rich import pretty
except ImportError:
pass
else:
pretty.install()
del pretty
sys.ps1 = '\001\033[96m\002>>> \001\033[0m\002'
sys.ps2 = '\001\033[96m\002... \001\033[0m\002'
| mit | Python |
b0b37ab794dcf3cb5291155d01d4888dc922f85c | Fix tests | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | bluebottle/deeds/periodic_tasks.py | bluebottle/deeds/periodic_tasks.py | from datetime import date
from django.utils.translation import ugettext_lazy as _
from bluebottle.fsm.effects import TransitionEffect
from bluebottle.fsm.periodic_tasks import ModelPeriodicTask
from bluebottle.deeds.models import (
Deed
)
from bluebottle.deeds.states import (
DeedStateMachine
)
from bluebottle... | from datetime import date
from django.utils.translation import ugettext_lazy as _
from bluebottle.fsm.effects import TransitionEffect
from bluebottle.fsm.periodic_tasks import ModelPeriodicTask
from bluebottle.deeds.models import (
Deed
)
from bluebottle.deeds.states import (
DeedStateMachine
)
from bluebottle... | bsd-3-clause | Python |
b36672d56935a5fd6e368e9f836e05b75fe581da | bump to beta v1.0.0 | whitews/FlowIO | flowio/_version.py | flowio/_version.py | """
FlowIO version
"""
__version__ = "1.0.0b"
| """
FlowIO version
"""
__version__ = "0.9.15b"
| bsd-3-clause | Python |
01c9b8b64616118ee3a370daca25efa46a3443ae | Fix tab | martinkou/bson | bson/tests/test_unknown_handler.py | bson/tests/test_unknown_handler.py | #!/usr/bin/env python
from bson import dumps, loads
from decimal import Decimal
from unittest import TestCase
class TestUnknownHandler(TestCase):
def test_unknown_handler(self):
d = Decimal("123.45")
obj = {"decimal": d}
serialized = dumps(obj, on_unknown=float)
unserialized = loa... | #!/usr/bin/env python
from bson import dumps, loads
from decimal import Decimal
from unittest import TestCase
class TestUnknownHandler(TestCase):
def test_unknown_handler(self):
d = Decimal("123.45")
obj = {"decimal": d}
serialized = dumps(obj, on_unknown=float)
unserialized = loads(seri... | bsd-3-clause | Python |
a1cd5a8b67de78c64db1589f5934d3e68e37c495 | Add minor changes in models.py | agarwalt/WikiNearby,tushar-agarwal/map_annotate,tushar-agarwal/map_annotate,tushar-agarwal/map_annotate,agarwalt/WikiNearby,tushar-agarwal/WikiNearby,tushar-agarwal/WikiNearby,tushar-agarwal/WikiNearby,agarwalt/WikiNearby | map_annotate_app/models.py | map_annotate_app/models.py | from __future__ import unicode_literals
from django.db import models
class CrimeType(models.Model):
crime_type = models.CharField(max_length=45, unique=True)
def __unicode__(self):
return self.crime_type
class Location(models.Model):
name = models.CharField(max_length=255, unique=True)
lat... | from __future__ import unicode_literals
from django.db import models
class CrimeType(models.Model):
crime_type = models.CharField(max_length=15)
def __unicode__(self):
return self.crime_type
class Location(models.Model):
name = models.CharField(max_length=45)
latitude = models.FloatField()... | mit | Python |
5ebe4bb70dbda678f0ff3b99ef5a9abc2577c187 | Bump version to 0.9.4 | rvause/django-tiamat | tiamat/__init__.py | tiamat/__init__.py | """
A collection of utilities to help ...Farm
"""
__version__ = '0.9.4'
__author__ = 'Rick Vause'
__email__ = 'rvause@gmail.com'
| """
A collection of utilities to help ...Farm
"""
__version__ = '0.9.3'
__author__ = 'Rick Vause'
__email__ = 'rvause@gmail.com'
| bsd-2-clause | Python |
31fe928eec181de67eea62a6bd7da95df63ffb2b | Add some debug statements. | fedora-infra/fmn.rules,jeremycline/fmn,jeremycline/fmn,jeremycline/fmn | fmn/rules/utils.py | fmn/rules/utils.py | """ Fedora Notifications pkgdb client """
import json
import logging
import requests
log = logging.getLogger(__name__)
## TODO: Move this variable into a configuration file
PKGDB_API_URL = 'http://209.132.184.188/api/'
## TODO: cache the results of this method
# This might mean removing the acl and branch argument
... | """ Fedora Notifications pkgdb client """
import json
import logging
import requests
log = logging.getLogger(__name__)
## TODO: Move this variable into a configuration file
PKGDB_API_URL = 'http://209.132.184.188/api/'
## TODO: cache the results of this method
# This might mean removing the acl and branch argument
... | lgpl-2.1 | Python |
ba9a955a4ccb0a2d083dc309babe3eada1294a88 | Add docstring for extract_pandas_matrix method. Change: 125057894 | Mazecreator/tensorflow,mavenlin/tensorflow,seanli9jan/tensorflow,benoitsteiner/tensorflow,manipopopo/tensorflow,chenjun0210/tensorflow,apark263/tensorflow,lakshayg/tensorflow,raymondxyang/tensorflow,mengxn/tensorflow,tntnatbry/tensorflow,benoitsteiner/tensorflow,lukeiwanski/tensorflow,benoitsteiner/tensorflow-opencl,a-... | tensorflow/contrib/learn/python/learn/io/pandas_io.py | tensorflow/contrib/learn/python/learn/io/pandas_io.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | apache-2.0 | Python |
b814f8861be74f2a3b0ae4c9e59a973fa95179e7 | bump version to 1.2.0 | ScottDuckworth/python-anyvcs,ScottDuckworth/python-anyvcs | anyvcs/__init__.py | anyvcs/__init__.py | # Copyright 2013 Clemson University
#
# This file is part of python-anyvcs.
#
# python-anyvcs 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 3 of the License, or
# (at your option) any l... | # Copyright 2013 Clemson University
#
# This file is part of python-anyvcs.
#
# python-anyvcs 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 3 of the License, or
# (at your option) any l... | bsd-3-clause | Python |
f78c476050e5772e0f6b9df5462673b619e4ef40 | Add filtering by name to Offering entity. | opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind | src/waldur_mastermind/marketplace/filters.py | src/waldur_mastermind/marketplace/filters.py | import json
import django_filters
from django.utils.translation import ugettext_lazy as _
from rest_framework import exceptions as rf_exceptions
from waldur_core.core import filters as core_filters
from . import models
class ServiceProviderFilter(django_filters.FilterSet):
customer = core_filters.URLFilter(vie... | import json
import django_filters
from django.utils.translation import ugettext_lazy as _
from rest_framework import exceptions as rf_exceptions
from waldur_core.core import filters as core_filters
from . import models
class ServiceProviderFilter(django_filters.FilterSet):
customer = core_filters.URLFilter(vie... | mit | Python |
648b274c04be9fc7532a8ae185cf9e12e801a34a | Add some reprs to autojit metaclasses | stonebig/numba,stuartarchibald/numba,ssarangi/numba,seibert/numba,ssarangi/numba,numba/numba,shiquanwang/numba,numba/numba,pombredanne/numba,shiquanwang/numba,cpcloud/numba,jriehl/numba,GaZ3ll3/numba,gdementen/numba,sklam/numba,gmarkall/numba,seibert/numba,stefanseefeld/numba,IntelLabs/numba,jriehl/numba,numba/numba,jr... | numba/exttypes/autojitmeta.py | numba/exttypes/autojitmeta.py | # -*- coding: utf-8 -*-
"""
Autojit meta class.
"""
from __future__ import print_function, division, absolute_import
class _AutojitMeta(type):
"""
Metaclass base for autojit classes.
"""
def create_unspecialized_cls(py_class, class_specializer):
"""
Create an unspecialized class.
class_spec... | # -*- coding: utf-8 -*-
"""
Autojit meta class.
"""
from __future__ import print_function, division, absolute_import
class _AutojitMeta(type):
"""
Metaclass base for autojit classes.
"""
def create_unspecialized_cls(py_class, class_specializer):
"""
Create an unspecialized class.
class_spec... | bsd-2-clause | Python |
11ad94cb40726c02794020a0fb8537bcbac1a960 | include pyramid_openid in setup.py requires | FOSSRIT/charsheet,FOSSRIT/charsheet,FOSSRIT/charsheet | metrics/charsheet/setup.py | metrics/charsheet/setup.py | import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
requires = [
'coderwall',
'elementtree',
'pyramid',
'py-stackexchange',
'SQLAlche... | import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
requires = [
'coderwall',
'elementtree',
'pyramid',
'py-stackexchange',
'SQLAlche... | agpl-3.0 | Python |
09e8bd268bb394dbf45dc6b2f4de73ba2b97fc79 | Update __init__.py | Alan-Jairo/topgeo | topgeo/__init__.py | topgeo/__init__.py | from coordenada import calcoor
from distancia import caldist
| from coordenada import calcoor
from distancia import caldist
def topgeo(a):
"""
Esta libreria funciona para realizar calculos topograficos.
"""
| mit | Python |
3c3cda58e3aa795020ca82ca4e0a5fd5af2f8913 | Fix KeyError , get_profile_media function | marcopompili/django-instagram,marcopompili/django-instagram,marcopompili/django-instagram | django_instagram/templatetags/instagram_client.py | django_instagram/templatetags/instagram_client.py | """
Created on 12/dic/2013
@author: Marco Pompili
"""
from django import template
from sorl.thumbnail import get_thumbnail, delete
from django_instagram import settings
from django_instagram.scraper import instagram_profile_json, instagram_profile_obj
register = template.Library()
def get_profile_media(profile, p... | """
Created on 12/dic/2013
@author: Marco Pompili
"""
from django import template
from sorl.thumbnail import get_thumbnail, delete
from django_instagram import settings
from django_instagram.scraper import instagram_profile_json, instagram_profile_obj
register = template.Library()
def get_profile_media(profile, p... | bsd-3-clause | Python |
ac7477803739d303df8374f916748173da32cb07 | Allow test client to be created with kwargs | brunobell/elasticsearch-py,elastic/elasticsearch-py,brunobell/elasticsearch-py,elastic/elasticsearch-py | test_elasticsearch/test_server/__init__.py | test_elasticsearch/test_server/__init__.py | from elasticsearch.helpers.test import get_test_client, ElasticsearchTestCase as BaseTestCase
client = None
def get_client(**kwargs):
global client
if client is not None and not kwargs:
return client
# try and locate manual override in the local environment
try:
from test_elasticsearc... | from elasticsearch.helpers.test import get_test_client, ElasticsearchTestCase as BaseTestCase
client = None
def get_client():
global client
if client is not None:
return client
# try and locate manual override in the local environment
try:
from test_elasticsearch.local import get_clie... | apache-2.0 | Python |
6bc7afc0af3424c2e1c9f5982248bf68b2eb62a5 | Add `github` command to `!cactus` | CactusDev/CactusBot | cactusbot/commands/magic/cactus.py | cactusbot/commands/magic/cactus.py | """Cactus command."""
from . import Command
from ...packets import MessagePacket
@Command.command()
class Cactus(Command):
"""Ouch! That's pokey!"""
COMMAND = "cactus"
@Command.command(name="cactus")
async def default(self):
return MessagePacket(
("text", "Ohai! I'm CactusBot! ... | """Cactus command."""
from . import Command
from ...packets import MessagePacket
@Command.command()
class Cactus(Command):
"""Ouch! That's pokey!"""
COMMAND = "cactus"
@Command.command(name="cactus")
async def default(self):
return MessagePacket(
("text", "Ohai! I'm CactusBot! ... | mit | Python |
2f9f2024e49c4594226168d60b0217c9af559291 | Simplify logic for speed | timvandermeij/lbp.py | lbp.py | lbp.py | import sys
import os.path
import numpy as np
from PIL import Image
class LBP:
def __init__(self, filename):
# Convert the image to grayscale
self.image = Image.open(filename).convert("L")
self.width = self.image.size[0]
self.height = self.image.size[1]
self.patterns = []
... | import sys
import os.path
import numpy as np
from PIL import Image
class LBP:
def __init__(self, filename):
self.image = Image.open(filename)
self.width = self.image.size[0]
self.height = self.image.size[1]
self.pixels = list(self.image.getdata())
self.patterns = []
def... | mit | Python |
b51aaaf0adce17e44928bcc858b72181afbee8ea | Add space line between import & func def | bowen0701/algorithms_data_structures | alg_bfs.py | alg_bfs.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import numpy as np
def bfs(graph_adj_d, start_vertex):
"""Breadth First Search (BFS) algorithm with single source
by queue.
Time complexity for graph G(V, E): O(|V|+|E|).
"""
distance_d ... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import numpy as np
def bfs(graph_adj_d, start_vertex):
"""Breadth First Search (BFS) algorithm with single source
by queue.
Time complexity for graph G(V, E): O(|V|+|E|).
"""
distance_d =... | bsd-2-clause | Python |
6a961a855a1ee22abd2ee2b8c29f965a26f5baa4 | Stop allowing submissions only AFTER deadline A missing keyword caused the new deadline calculation to only allow submissions if it was PAST the deadline. Whoops! | magfest/mivs,magfest/mivs | mivs/config.py | mivs/config.py | from mivs import *
mivs_config = parse_config(__file__)
c.include_plugin_config(mivs_config)
c.CODES_REQUIRING_INSTRUCTIONS = [getattr(c, code_type.upper()) for code_type in c.CODES_REQUIRING_INSTRUCTIONS]
# Add the access levels we defined to c.ACCESS* (this will go away if/when we implement enum merging)
c.ACCESS.... | from mivs import *
mivs_config = parse_config(__file__)
c.include_plugin_config(mivs_config)
c.CODES_REQUIRING_INSTRUCTIONS = [getattr(c, code_type.upper()) for code_type in c.CODES_REQUIRING_INSTRUCTIONS]
# Add the access levels we defined to c.ACCESS* (this will go away if/when we implement enum merging)
c.ACCESS.... | agpl-3.0 | Python |
e7b4a3618efd248b9a7f00d326cfa72bace166ff | Update drivers.py | ariegg/webiopi-drivers,ariegg/webiopi-drivers | chips/sensor/simulation/drivers.py | chips/sensor/simulation/drivers.py | # This code has to be added to the corresponding __init__.py
DRIVERS["simulatedsensors"] = ["PRESSURE", "TEMPERATURE", "LUMINOSITY", "DISTANCE", "HUMIDITY",
"COLOR", "CURRENT", "VOLTAGE", "POWER",
"LINEARVELOCITY", "ANGULARVELOCITY", "VELOCITY",
... | # This code has to be added to the corresponding __init__.py
DRIVERS["simulatedsensors"] = ["PRESSURE", "TEMPERATURE", "LUMINOSITY", "DISTANCE", "HUMIDITY",
"COLOR", "CURRENT", "VOLTAGE", "POWER",
"LINEARACCELERATION", "ANGULARACCELERATION", "ACCELERATION", "LINEARVE... | apache-2.0 | Python |
c7daf3136c8ae024187cd50530d3ee90b1385b13 | Use observable deferreds because they are sane | matrix-org/synapse,matrix-org/synapse,TribeMedia/synapse,TribeMedia/synapse,TribeMedia/synapse,matrix-org/synapse,matrix-org/synapse,TribeMedia/synapse,TribeMedia/synapse,matrix-org/synapse,matrix-org/synapse | synapse/rest/client/v2_alpha/sendtodevice.py | synapse/rest/client/v2_alpha/sendtodevice.py | # -*- coding: utf-8 -*-
# Copyright 2016 OpenMarket Ltd
#
# 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... | # -*- coding: utf-8 -*-
# Copyright 2016 OpenMarket Ltd
#
# 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 |
6c8863153a83742d76d3a4e1baab5ebc68d6096f | Remove beautifulsoup, not needed (#520) | hhursev/recipe-scraper | recipe_scrapers/bbcgoodfood.py | recipe_scrapers/bbcgoodfood.py | from ._abstract import AbstractScraper
class BBCGoodFood(AbstractScraper):
@classmethod
def host(cls):
return "bbcgoodfood.com"
def title(self):
return self.schema.title()
def total_time(self):
return self.schema.total_time()
def yields(self):
return self.schema.... | from bs4 import BeautifulSoup
from ._abstract import AbstractScraper
class BBCGoodFood(AbstractScraper):
@classmethod
def host(cls):
return "bbcgoodfood.com"
def title(self):
return self.schema.title()
def total_time(self):
return self.schema.total_time()
def yields(sel... | mit | Python |
f98502b1fb2542f9c2fcaa16772a5fb8a484b277 | Use ElementTree to parse Inkscape dependencies | morevnaproject/RenderChan,morevnaproject/RenderChan,scribblemaniac/RenderChan,scribblemaniac/RenderChan | renderchan/contrib/inkscape.py | renderchan/contrib/inkscape.py |
__author__ = 'scribblemaniac'
from renderchan.module import RenderChanModule
import subprocess
import gzip
import os
import os.path
from xml.etree import ElementTree
class RenderChanInkscapeModule(RenderChanModule):
def __init__(self):
RenderChanModule.__init__(self)
if os.name == 'nt':
... |
__author__ = 'scribblemaniac'
from renderchan.module import RenderChanModule
import subprocess
import gzip
import os
import re
class RenderChanInkscapeModule(RenderChanModule):
def __init__(self):
RenderChanModule.__init__(self)
if os.name == 'nt':
self.conf['binary']=os.path.join(os... | bsd-3-clause | Python |
d5558926b5208f816f5fd698c110c9a389471cb1 | Remove one "undefined-variable" | Synss/python-mbedtls,Synss/python-mbedtls | src/mbedtls/cipher/__init__.py | src/mbedtls/cipher/__init__.py | # SPDX-License-Identifier: MIT
# Copyright (c) 2016, Elaborated Networks GmbH
# Copyright (c) 2019, Mathias Laurin
"""The cipher package provide symmetric encryption and decryption.
The API follows the recommendations from PEP 272 "API for Block
Encryption Algorithms"
"""
from . import AES, ARC4, ARIA, CHACHA20, DE... | # SPDX-License-Identifier: MIT
# Copyright (c) 2016, Elaborated Networks GmbH
# Copyright (c) 2019, Mathias Laurin
"""The cipher package provide symmetric encryption and decryption.
The API follows the recommendations from PEP 272 "API for Block
Encryption Algorithms"
"""
from . import AES, ARC4, ARIA, CHACHA20, DE... | mit | Python |
2266dc2a22cc342d41b3c29a2341082a635a53ab | Make sql in model more clear | UngaForskareStockholm/medlem2 | model/model.py | model/model.py | #! /usr/bin/env python2.7
import lib.database
class Model(object):
@classmethod
def init_model(cls, table, primary_key):
cls._table = table
cls._primary_key = primary_key
cls._db = lib.database.db
cls._db.cursor.execute("SELECT * FROM %s WHERE FALSE"%cls._table)
cls.COLUMNS = set([desc[0] for desc in cls.... | #! /usr/bin/env python2.7
import lib.database
class Model(object):
@classmethod
def init_model(cls, table, primary_key):
cls._table = table
cls._primary_key = primary_key
cls._db = lib.database.db
cls._db.cursor.execute("SELECT * FROM %s WHERE FALSE"%cls._table)
cls.COLUMNS = set([desc[0] for desc in cls.... | bsd-3-clause | Python |
af1e22746131c65121f25faab1c760faebfbf93c | fix migration for oauthclient | inveniosoftware/invenio-accounts,inveniosoftware/invenio-accounts,inveniosoftware/invenio-accounts | invenio_accounts/alembic/62efc52773d4_create_useridentity_table.py | invenio_accounts/alembic/62efc52773d4_create_useridentity_table.py | #
# This file is part of Invenio.
# Copyright (C) 2022 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Create UserIdentity table."""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by ... | #
# This file is part of Invenio.
# Copyright (C) 2022 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Create UserIdentity table."""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by ... | mit | Python |
a10a9a401dc130ce07ebe47ee415d62e26506ff9 | Update comments | chaosmail/python-midi,pdorrell/python-midi,ListFranz/python-midi,eli-b/python-midi,ListFranz/python-midi,rlkelly/python-midi,ListFranz/python-midi,vishnubob/python-midi,chaosmail/python-midi,rlkelly/python-midi,shimpe/python-midi,rlkelly/python-midi,chaosmail/python-midi,vishnubob/python-midi,pdorrell/python-midi,james... | src/containers.py | src/containers.py | from pprint import pformat, pprint
class Pattern(list):
def __init__(self, tracks=[], resolution=220, format=1):
self.format = format
self.resolution = resolution
super(Pattern, self).__init__(tracks)
def __repr__(self):
return "midi.Pattern(format=%r, resolution=%r, tracks=\\\... | from pprint import pformat, pprint
class Pattern(list):
def __init__(self, tracks=[], resolution=220, format=1):
self.format = format
self.resolution = resolution
super(Pattern, self).__init__(tracks)
def __repr__(self):
return "midi.Pattern(format=%r, resolution=%r, tracks=\\\... | mit | Python |
f034c6121dabfb20cb1cf6b6ae6985b236bfef11 | Update storage to 1.3.1. (#3741) | jonparrott/google-cloud-python,dhermes/google-cloud-python,dhermes/google-cloud-python,tseaver/google-cloud-python,tseaver/gcloud-python,tartavull/google-cloud-python,tseaver/google-cloud-python,jonparrott/gcloud-python,dhermes/google-cloud-python,googleapis/google-cloud-python,tswast/google-cloud-python,tseaver/gcloud... | storage/setup.py | storage/setup.py | # Copyright 2016 Google 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 writing, ... | # Copyright 2016 Google 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 writing, ... | apache-2.0 | Python |
c7441f030aa1758959197358fcddf428f4987287 | Remove translation logging prefixes from i18n | openstack/barbican,openstack/barbican | barbican/i18n.py | barbican/i18n.py | # Copyright 2010-2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | # Copyright 2010-2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | apache-2.0 | Python |
d5402147f07d614c8c1b2f3541640cba467a1904 | replace version and change the download url (#11837) | LLNL/spack,LLNL/spack,LLNL/spack,iulian787/spack,iulian787/spack,iulian787/spack,iulian787/spack,LLNL/spack,iulian787/spack,LLNL/spack | var/spack/repos/builtin/packages/bib2xhtml/package.py | var/spack/repos/builtin/packages/bib2xhtml/package.py | # Copyright 2013-2019 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 *
from glob import glob
class Bib2xhtml(Package):
"""bib2xhtml is a program that converts BibTeX f... | # Copyright 2013-2019 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 *
from glob import glob
class Bib2xhtml(Package):
"""bib2xhtml is a program that converts BibTeX f... | lgpl-2.1 | Python |
6d5edb8a5eacfb2dc83a2eef5732562024995942 | Fix bug with registering non-school teams | stefantsov/blackbox3,stefantsov/blackbox3,stefantsov/blackbox3 | api/serializers.py | api/serializers.py | from django.utils.translation import ugettext as _
from rest_framework.serializers import ModelSerializer, ValidationError
from reg.models import Team
class TeamSerializer(ModelSerializer):
def validate(self, data):
error_dict = {}
if 'is_school' in data and data['is_school']:
if 's... | from django.utils.translation import ugettext as _
from rest_framework.serializers import ModelSerializer, ValidationError
from reg.models import Team
class TeamSerializer(ModelSerializer):
def validate(self, data):
if 'is_school' in data and data['is_school']:
error_dict = {}
i... | bsd-3-clause | Python |
863bdd5115bea68fd773735732a18bdd3d841c94 | add build dependency on texinfo (#20930) | LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack | var/spack/repos/builtin/packages/libconfig/package.py | var/spack/repos/builtin/packages/libconfig/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 Libconfig(AutotoolsPackage):
"""C/C++ Configuration File Library"""
homepage = "http:... | # 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 Libconfig(AutotoolsPackage):
"""C/C++ Configuration File Library"""
homepage = "http:... | lgpl-2.1 | Python |
8333c56ab8f81ddae0f9af0f9a8e5cc42f3416c3 | add versions to package py-pandas (#3338) | skosukhin/spack,EmreAtes/spack,skosukhin/spack,iulian787/spack,lgarren/spack,krafczyk/spack,matthiasdiener/spack,EmreAtes/spack,tmerrick1/spack,LLNL/spack,TheTimmy/spack,matthiasdiener/spack,mfherbst/spack,skosukhin/spack,matthiasdiener/spack,LLNL/spack,matthiasdiener/spack,LLNL/spack,TheTimmy/spack,iulian787/spack,The... | var/spack/repos/builtin/packages/py-pandas/package.py | var/spack/repos/builtin/packages/py-pandas/package.py | ##############################################################################
# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | ##############################################################################
# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | lgpl-2.1 | Python |
1782a3c0a2c284d692e6c06ab274b8eb0e4bd199 | Make 'home' and 'booking' urls more specific to avoid future conflicts. | muhummadPatel/raspied,muhummadPatel/raspied,muhummadPatel/raspied | students/urls.py | students/urls.py | from django.conf.urls import include, url
from . import views
app_name = "students"
urlpatterns = [
url(r'^home/$', views.home, name='home'),
url(r'^booking/$', views.booking, name='booking'),
# TODO: overidden registration urls come before the include below
url(r'^accounts/register/$', views.Exclusiv... | from django.conf.urls import include, url
from . import views
app_name = "students"
urlpatterns = [
url(r'^home/', views.home, name='home'),
url(r'^booking/', views.booking, name='booking'),
# TODO: overidden registration urls come before the include below
url(r'^accounts/register/$', views.ExclusiveR... | mit | Python |
13a93a740ce263e2ac83548633608e1b9680079d | decrease vocab size to make model file smaller | kbrose/article-tagging,kbrose/article-tagging,chicago-justice-project/article-tagging,chicago-justice-project/article-tagging | lib/tagnews/crimetype/models/binary_stemmed_logistic/save_model.py | lib/tagnews/crimetype/models/binary_stemmed_logistic/save_model.py | import os
import time
import sys
from ....utils import load_data as ld
from ....utils.model_helpers import LemmaTokenizer
import numpy as np
import pandas as pd
import sklearn
import sklearn.feature_extraction.text
import sklearn.multiclass
import sklearn.linear_model
from nltk import word_tokenize
from nltk.stem impo... | import os
import time
import sys
from ....utils import load_data as ld
from ....utils.model_helpers import LemmaTokenizer
import numpy as np
import pandas as pd
import sklearn
import sklearn.feature_extraction.text
import sklearn.multiclass
import sklearn.linear_model
from nltk import word_tokenize
from nltk.stem impo... | mit | Python |
ae711d520611871ca9dfcdac1d393c199a39f1fd | Update backprop.py | ParallelDots/WordEmbeddingAutoencoder | tyrion/backprop.py | tyrion/backprop.py | '''
Re-implementation of Word Embedding in theano
'''
import numpy as np
import theano
from theano import tensor as T
from compatibility import range, pickle
rng = np.random
class TrainModel(object):
def __init__(self, maxnum, reduced_dims, learnrate=0.4):
self.threshold = 1e-2
# Input variable ... | '''
Re-implementation of Word Embedding in theano
'''
import numpy as np
import theano
from theano import tensor as T
rng = np.random
class TrainModel(object):
def __init__(self, maxnum, reduced_dims, learnrate=0.4):
self.threshold = 1e-2
# Input variable (equivalent to dummyword in original imp... | mit | Python |
91049834c3f30dcb838ac45167e93aa1bc92a913 | Prepare Django 1.7 compatibility, use new fluent_pages.adminui module | edoburu/django-fluent-faq,edoburu/django-fluent-faq | fluent_faq/pagetypes/faqpage/page_type_plugins.py | fluent_faq/pagetypes/faqpage/page_type_plugins.py | from fluent_pages.adminui import HtmlPageAdmin
from fluent_pages.extensions import page_type_pool, PageTypePlugin
from .models import FaqPage
@page_type_pool.register
class FaqPagePlugin(PageTypePlugin):
"""
Plugin binding the FaqPage model as pagetype.
"""
model = FaqPage
model_admin = HtmlPageAd... | from fluent_pages.admin import HtmlPageAdmin
from fluent_pages.extensions import page_type_pool, PageTypePlugin
from .models import FaqPage
@page_type_pool.register
class FaqPagePlugin(PageTypePlugin):
"""
Plugin binding the FaqPage model as pagetype.
"""
model = FaqPage
model_admin = HtmlPageAdmi... | apache-2.0 | Python |
fbd984abff692410fa23b302d59a9468dd59e1ae | use selftext not description | ScorpionResponse/freelancefinder,ScorpionResponse/freelancefinder,ScorpionResponse/freelancefinder | freelancefinder/remotes/sources/reddit/harvest.py | freelancefinder/remotes/sources/reddit/harvest.py | """Harvest process for the Reddit Source."""
import praw
from django.conf import settings
from jobs.models import Post
class Harvester(object):
"""Simple Harvester to gather reddit posts."""
def __init__(self, source):
"""Init the harvester with basic info."""
self.source = source
... | """Harvest process for the Reddit Source."""
import praw
from django.conf import settings
from jobs.models import Post
class Harvester(object):
"""Simple Harvester to gather reddit posts."""
def __init__(self, source):
"""Init the harvester with basic info."""
self.source = source
... | bsd-3-clause | Python |
30b7f8f6fb432f19cc52b904427e84185abb346a | Update documentation | patchew-project/patchew,famz/patchew,patchew-project/patchew,patchew-project/patchew,famz/patchew,patchew-project/patchew,famz/patchew,famz/patchew | mods/footer.py | mods/footer.py | from mod import PatchewModule
_default_config = """
<!-- your HTML here -->
"""
class FooterModule(PatchewModule):
"""
Documentation
-------------
This is a simple module to inject any HTML code into the page bottom. Can be
useful to add statistic code, etc..
The config is the raw HTML code to inject.
"""
... | from mod import PatchewModule
_default_config = """
<!-- your HTML here -->
"""
class FooterModule(PatchewModule):
name = "footer"
default_config = _default_config
def render_page_hook(self, context_data):
context_data.setdefault("footer", "")
context_data["footer"] += self.get_config_ra... | mit | Python |
e4b66b0365d696422c6e892593bf314666a006b4 | add on_close method to avoid error on session expiration | ilredeitopi/uniluganobot | uniluganobot/interfaces/telegram/usibot.py | uniluganobot/interfaces/telegram/usibot.py | import asyncio
import telepot
from telepot.aio.loop import MessageLoop
from telepot.aio.delegate import per_chat_id, create_open, pave_event_space
import os
# from . import botconfig
from .commands import Command
class UsiBot(telepot.aio.helper.ChatHandler):
timeout = 10
# def __init__(self, *args, **kwarg... | import asyncio
import telepot
from telepot.aio.loop import MessageLoop
from telepot.aio.delegate import per_chat_id, create_open, pave_event_space
import os
# from . import botconfig
from .commands import Command
class UsiBot(telepot.aio.helper.ChatHandler):
timeout = 10
# def __init__(self, *args, **kwarg... | mit | Python |
9d3676100ff0799a238f009a09cacd3be51da2b0 | Switch to in-memory SQLite database as the default for local tests (@justinvdm, @jerith). | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | go/testsettings.py | go/testsettings.py | import os
from settings import *
SECRET_KEY = "test_secret"
# This needs to point at the test riak buckets.
VUMI_API_CONFIG['riak_manager'] = {'bucket_prefix': 'test.'}
VUMI_API_CONFIG['redis_manager'] = {
'key_prefix': 'test',
'FAKE_REDIS': 'sure',
}
# Setup test database
VUMIGO_TEST_DB = os.environ.get('V... | import os
from settings import *
SECRET_KEY = "test_secret"
# This needs to point at the test riak buckets.
VUMI_API_CONFIG['riak_manager'] = {'bucket_prefix': 'test.'}
VUMI_API_CONFIG['redis_manager'] = {
'key_prefix': 'test',
'FAKE_REDIS': 'sure',
}
# Setup test database
VUMIGO_TEST_DB = os.environ.get('V... | bsd-3-clause | Python |
2815374373857605e338afe551db921d178fa7ba | add implementation of stable matching algorithm | topliceanu/learn,topliceanu/learn,topliceanu/learn,topliceanu/learn,topliceanu/learn,topliceanu/learn,topliceanu/learn,topliceanu/learn,topliceanu/learn | algo/src/stable_matching.py | algo/src/stable_matching.py | # -*- coding: utf-8 -*-
import random
def stable_matching(u, v):
""" Solves the stable matching problem using the Gale-Shapley Proposal
algorithm.
Given two sets of items u and v, each item in u has preferences to items in
v, and every item in v has preferences to items in u. Compute a stable
ma... | # -*- coding: utf-8 -*-
import random
def stable_matching(u, v):
""" Solves the stable matching problem using the Gale-Shapley Proposal
algorithm.
We assume that the cardinalities of u and v are equal.
Created by Lloyd Shapley and David Gale
Complexity: O(n^2)
Params:
u: dict, forma... | mit | Python |
cf76af82ac3c0829f8a812abc37463f6d48fe3f1 | Strengthen the MUC JOIN test to forbid duplicate NewChannels | freedesktop-unofficial-mirror/telepathy__telepathy-idle,freedesktop-unofficial-mirror/telepathy__telepathy-idle,freedesktop-unofficial-mirror/telepathy__telepathy-idle | tests/twisted/channels/join-muc-channel.py | tests/twisted/channels/join-muc-channel.py |
"""
Test connecting to a IRC channel
"""
from idletest import exec_test
from servicetest import EventPattern, call_async
from constants import *
import dbus
def test(q, bus, conn, stream):
conn.Connect()
q.expect_many(
EventPattern('dbus-signal', signal='StatusChanged', args=[1, 1]),
... |
"""
Test connecting to a IRC channel
"""
from idletest import exec_test
from servicetest import EventPattern, call_async
from constants import *
import dbus
def test(q, bus, conn, stream):
conn.Connect()
q.expect_many(
EventPattern('dbus-signal', signal='StatusChanged', args=[1, 1]),
... | lgpl-2.1 | Python |
dd2adad3c588e38594c63467b2b0343d5629caf8 | fix tests | universalcore/unicore-mc,universalcore/unicore-mc,universalcore/unicore-mc,praekelt/mc2,praekelt/mc2,praekelt/mc2,universalcore/unicore-mc,praekelt/mc2,praekelt/mc2 | unicoremc/views.py | unicoremc/views.py | import json
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.views.decorators.csrf import csrf_exempt
from unicoremc.models import Project, Localisation
from unicoremc import const... | import json
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.views.decorators.csrf import csrf_exempt
from unicoremc.models import Project, Localisation
from unicoremc import const... | bsd-2-clause | Python |
a6289b867947855016ae87ee4bcaffc6488d1a9a | bump version number | creimers/cmsplugin_simpleslider,creimers/cmsplugin_simpleslider,AdrianRibao/cmsplugin_simpleslider,AdrianRibao/cmsplugin_simpleslider | cmsplugin_simpleslider/__init__.py | cmsplugin_simpleslider/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Chirstoph Reimers'
__email__ = 'christoph@superservice-international.com'
__version__ = '0.1.0.b4'
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Chirstoph Reimers'
__email__ = 'christoph@superservice-international.com'
__version__ = '0.1.0.b3'
| bsd-2-clause | Python |
85cdf38b7060ed1cc51657e9ed0780106e020ac5 | set up rester | materialsproject/MPContribs,materialsproject/MPContribs,materialsproject/MPContribs,materialsproject/MPContribs | als_beamline/rest/rester.py | als_beamline/rest/rester.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from mpcontribs.io.archieml.mpfile import MPFile
from mpcontribs.rest.rester import MPContribsRester
from mpcontribs.io.core.recdict import RecursiveDict
from mpcontribs.io.core.components import Table
class AlsBeamlineRester(MPContribsRester):
"""ALS... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from mpcontribs.rest.rester import MPContribsRester
class AlsBeamlineRester(MPContribsRester):
"""ALS Beamline-specific convenience functions to interact with MPContribs REST interface"""
query = {'content.measurement_location': 'ALS Beamline 6.3.... | mit | Python |
b3d0f710de7982877fb2c30c46c75de86262caf4 | Allow render to take a template different from the default one. | swayf/grako,swayf/grako | grako/rendering.py | grako/rendering.py | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**f... | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**f... | bsd-2-clause | Python |
f191ab586d652fc02004a35b26477c01faf833b3 | Disable another FACE_DETECTION test (#1253) | GoogleCloudPlatform/python-docs-samples,GoogleCloudPlatform/python-docs-samples,GoogleCloudPlatform/python-docs-samples,GoogleCloudPlatform/python-docs-samples | video/cloud-client/analyze/analyze_test.py | video/cloud-client/analyze/analyze_test.py | #!/usr/bin/env python
# Copyright 2017 Google, 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... | #!/usr/bin/env python
# Copyright 2017 Google, 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... | apache-2.0 | Python |
a8254bf2d4626a46b007d809be0b69ce59760cfb | address comments | biocore/American-Gut,biocore/American-Gut | americangut/per_category.py | americangut/per_category.py | from os.path import join
from copy import copy
from biom import load_table
import americangut.notebook_environment as agenv
from .util import collapse_full, collapse_taxonomy, get_existing_path
def cat_taxa_summaries(debug=False):
"""Creates taxa summary files for each available summary category per site
""... | from os.path import join
from copy import copy
from biom import load_table
import americangut.notebook_environment as agenv
from .util import collapse_full, collapse_taxonomy, get_existing_path
def cat_taxa_summaries():
"""Creates taxa summary files for each available summary category per site
"""
paths... | bsd-3-clause | Python |
f7f76feaed259dbef6807ccce81cbb978e6306b5 | make intent clearer | eugene-eeo/graphlite | graphlite/graph.py | graphlite/graph.py | from contextlib import closing
from sqlite3 import Connection
from threading import Lock
from graphlite.query import Query
from graphlite.transaction import Transaction
import graphlite.sql as SQL
class Graph(object):
"""
Initializes a new Graph object.
:param uri: The URI of the SQLite db.
:param g... | from contextlib import closing
from sqlite3 import Connection
from threading import Lock
from graphlite.query import Query
from graphlite.transaction import Transaction
import graphlite.sql as SQL
class Graph(object):
"""
Initializes a new Graph object.
:param uri: The URI of the SQLite db.
:param g... | mit | Python |
7f8f6a7fee84282619632580dbf831fff3bc6870 | Resolve bug #154764364 (GUI saved "£" sign in units as "\xA3") | willu47/smif,nismod/smif,tomalrussell/smif,willu47/smif,willu47/smif,tomalrussell/smif,nismod/smif,nismod/smif,tomalrussell/smif,nismod/smif,willu47/smif,tomalrussell/smif | src/smif/data_layer/load.py | src/smif/data_layer/load.py | # -*- coding: utf-8 -*-
"""Parse yaml config files, to construct sector models
"""
import yaml
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
def load(file_path):
"""Parse yaml config file into plain data (lists, dicts and simple values)
... | # -*- coding: utf-8 -*-
"""Parse yaml config files, to construct sector models
"""
import yaml
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
def load(file_path):
"""Parse yaml config file into plain data (lists, dicts and simple values)
... | mit | Python |
f95f57516e934693f5455b22ee3e005c5617a45e | Handle Stripe dispute objects | Flamacue/pretix,Flamacue/pretix,Flamacue/pretix,Flamacue/pretix | src/pretix/plugins/stripe/views.py | src/pretix/plugins/stripe/views.py | import json
import logging
import stripe
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from pretix.base.models import Event, Order
from pretix.base.services.orders import mark_order_refunded
from pretix.plugins.stripe.pa... | import json
import logging
import stripe
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from pretix.base.models import Event, Order
from pretix.base.services.orders import mark_order_refunded
from pretix.plugins.stripe.pa... | apache-2.0 | Python |
a1353cac57dc1f122c0f251a5b60023b63414f83 | Add serialize method to help json parsing | openedoo/module_employee,openedoo/module_employee,openedoo/module_employee | database.py | database.py | from openedoo import db
from openedoo import config
from sqlalchemy.orm import relationship
database_prefix = config.database_prefix
def dump_datetime(val):
"""Deserialize datetime object into string form for JSON processing."""
if val is None:
raise ValueError("Your datetime is wrong!.")
return [... | from openedoo import db
from openedoo import config
from sqlalchemy.orm import relationship
from sqlalchemy_utils import PasswordType
database_prefix = config.database_prefix
class User(db.Model):
__tablename__ = '{db_prefix}_em_user'.format(db_prefix=database_prefix)
id = db.Column(db.Integer, primary_key=T... | mit | Python |
c62507c218aef2f4a834499bcf37d212b4fc8ce2 | Read from configuration in database.by | colorado-code-for-communities/denver_streets,colorado-code-for-communities/denver_streets | database.py | database.py | from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
from geoalchemy import *
import os
import yaml
config = yaml.load(open('config.yaml', 'r'))
try:
if os.environ['FLASK_ENV'] == 'test':
databse_name = config['database']['test']['db']
datab... | from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
from geoalchemy import *
import os
import yaml
config = yaml.load(open('config.yaml', 'r'))
try:
if os.environ['FLASK_ENV'] == 'test':
databse_name = config['database']['test']['db']
datab... | apache-2.0 | Python |
f2b6ade7310f4970f4d780910294390f294b9825 | Fix api | qateam123/secure-messaging-api | app/api.py | app/api.py | from flask import Flask
from flask_restful import Resource, Api
from app.resources.message import Message
app = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
def get(self):
return {'hello': 'world'}
api.add_resource(HelloWorld, '/')
api.add_resource(Message, '/message/<int:id>')
if __name_... | from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
def get(self):
return {'hello': 'world'}
api.add_resource(HelloWorld, '/')
if __name__ == '__main__':
app.run(debug=True)
| mit | Python |
7f14735dbcfca317340e65ef83fd1a3f6df4f3b7 | Complete lc119_pascal_triangle_ii.py | bowen0701/algorithms_data_structures | lc119_pascal_triangle_ii.py | lc119_pascal_triangle_ii.py | """Leetcode 119. Pascal's Triangle II
Easy
URL: https://leetcode.com/problems/pascals-triangle-ii/
Given a non-negative index k where k <= 33, return the kth index row of the
Pascal's triangle.
Note that the row index starts from 0.
In Pascal's triangle, each number is the sum of the two numbers directly
above it... | """Leetcode 119. Pascal's Triangle II
Easy
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.
Note that the row index starts from 0.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 3
Output: [1,3,3,1]
Follow up:
Could y... | bsd-2-clause | Python |
1690959502e2951920e52a0832e6571144bab6a8 | Change faq processor to bulk index | kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh | _lib/wordpress_faq_processor.py | _lib/wordpress_faq_processor.py | import sys
import json
import os.path
import requests
def posts_at_url(url):
current_page = 1
max_page = sys.maxint
while current_page <= max_page:
url = os.path.expandvars(url)
resp = requests.get(url, params={'page': current_page, 'count': '-1'})
results = json.loads(resp.conte... | import sys
import json
import os.path
import requests
def posts_at_url(url):
current_page = 1
max_page = sys.maxint
while current_page <= max_page:
url = os.path.expandvars(url)
resp = requests.get(url, params={'page': current_page, 'count': '-1'})
results = json.loads(resp.conte... | cc0-1.0 | Python |
3b4141907248bbced4fac84ddc155a6c6fced83e | Update __init__.py | hhj0325/pystock | com/hhj/pystock/master/__init__.py | com/hhj/pystock/master/__init__.py | class boy:
gender = 'male'
interest = 'girl'
def say(self):
return 'i am a boy'
hhj = boy()
print(hhj.say())
print(hhj.say())
| class boy:
gender = 'male'
interest = 'girl'
def say(self):
return 'i am a boy'
hhj = boy()
print(hhj.say())
| apache-2.0 | Python |
2e3ecb908031b538fbe6fa54ca6a6e862e021b83 | fix under-indentation | cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy | tests/cupy_tests/logic_tests/test_content.py | tests/cupy_tests/logic_tests/test_content.py | import unittest
import numpy
from cupy import testing
@testing.gpu
class TestContent(unittest.TestCase):
@testing.for_dtypes('efFdD')
@testing.numpy_cupy_array_equal()
def check_unary_inf(self, name, xp, dtype):
a = xp.array([-3, numpy.inf, -1, -numpy.inf, 0, 1, 2],
dtype=d... | import unittest
import numpy
from cupy import testing
@testing.gpu
class TestContent(unittest.TestCase):
@testing.for_dtypes('efFdD')
@testing.numpy_cupy_array_equal()
def check_unary_inf(self, name, xp, dtype):
a = xp.array([-3, numpy.inf, -1, -numpy.inf, 0, 1, 2],
dtype=d... | mit | Python |
42340e3d73fcb8a197d3329cabd254b1045a26fd | Sort account usage by name | MeerkatLabs/gnucash-reporting | gnu_reporting/reports/account_usage_categories.py | gnu_reporting/reports/account_usage_categories.py | """
Iterate through all of the accounts provided and give a categorized record of the expenses that have been charged to
that account.
"""
from gnu_reporting.configuration.expense_categories import get_category_for_account
from gnu_reporting.wrapper import get_decimal, account_walker, get_splits
from gnu_reporting.repo... | """
Iterate through all of the accounts provided and give a categorized record of the expenses that have been charged to
that account.
"""
from gnu_reporting.configuration.expense_categories import get_category_for_account
from gnu_reporting.wrapper import get_decimal, account_walker, get_splits
from gnu_reporting.repo... | mit | Python |
992f19e525290b41aff535f77a7cc26fa6a26cd2 | Fix unittest for random.rand | jnishi/chainer,ktnyt/chainer,cemoody/chainer,kikusu/chainer,jnishi/chainer,anaruse/chainer,hvy/chainer,niboshi/chainer,cupy/cupy,minhpqn/chainer,kikusu/chainer,keisuke-umezawa/chainer,niboshi/chainer,chainer/chainer,sinhrks/chainer,t-abe/chainer,truongdq/chainer,wkentaro/chainer,benob/chainer,truongdq/chainer,kashif/ch... | tests/cupy_tests/random_tests/test_sample.py | tests/cupy_tests/random_tests/test_sample.py | import mock
import unittest
import numpy
from cupy import random
from cupy import testing
@testing.gpu
class TestSample(unittest.TestCase):
_multiprocess_can_split_ = True
def test_rand(self):
random.sample_.random_sample = mock.Mock()
random.rand(1, 2, 3, dtype=numpy.float32)
rand... | import mock
import unittest
import numpy
from cupy import random
from cupy import testing
@testing.gpu
class TestSample(unittest.TestCase):
_multiprocess_can_split_ = True
def setUp(self):
random.random_sample = mock.Mock()
def test_rand(self):
random.rand(1, 2, 3, dtype=numpy.float32... | mit | Python |
0d5dd945966ea2b358e79a9ef970ca119a537979 | Change release json path | nuimk/nmk,nuimk/nmk,nuimk/nmk,nuimk/nmk | bin/nmk-update.py | bin/nmk-update.py | #!/usr/bin/env python
import json
import logging
import os
from os import path
import subprocess
from tempfile import NamedTemporaryFile
from six.moves.urllib import request
logging.basicConfig(format='{0}: %(message)s'.format(__file__), level=logging.INFO)
NMK_DIR = os.path.dirname(os.path.dirname(os.path.abspath(_... | #!/usr/bin/env python
import json
import logging
import os
from os import path
import subprocess
from tempfile import NamedTemporaryFile
from six.moves.urllib import request
logging.basicConfig(level=logging.INFO)
NMK_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
RELEASE_INFO_PATH = path.join(NMK... | mit | Python |
6e3c3862cc64e25e34b94e91d11aba82cf812074 | make the listener more useful | ryepup/arduino-experiments,ryepup/arduino-experiments | arduino.py | arduino.py | import serial
def listen():
global ser
ser = serial.Serial('/dev/ttyUSB0', 9600)
def watch():
global ser
while 1:
print ser.readline(),
if __name__ == '__main__':
global ser
listen()
try:
watch()
finally:
ser.close()
| import serial
def listen():
global ser
ser = serial.Serial('/dev/ttyUSB0', 9600)
def watch():
global ser
while 1:
print(ser.readline())
| bsd-2-clause | Python |
60bf4d338ce13208b8afd1a4df4df57d72cc9485 | Reduce compiled template's memory usage | mhallin/django-compiling-loader,mhallin/django-compiling-loader,jnovinger/django-compiling-loader,jnovinger/django-compiling-loader | compiling_loader/compiler_state.py | compiling_loader/compiler_state.py | import ast
import collections.abc
EMIT_ARG_NAME = '$emit$'
CONTEXT_ARG_NAME = '$context$'
class CompilerState:
def __init__(self):
self._ivar_counter = 0
self.ivars = {}
self._ivar_values = {}
self._local_var_counter = 0
self._global_var_counter = 0
self.imports ... | import ast
EMIT_ARG_NAME = '$emit$'
CONTEXT_ARG_NAME = '$context$'
class CompilerState:
def __init__(self):
self._ivar_counter = 0
self.ivars = {}
self._local_var_counter = 0
self._global_var_counter = 0
self.imports = []
self._imported_names = {}
def add_iv... | bsd-3-clause | Python |
efd128339bac1156db8e0c02b41bfdcf33504aeb | Set all addons to uninstallable | ddico/account-financial-tools,ddico/account-financial-tools | account_renumber/__openerp__.py | account_renumber/__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP - Account renumber wizard
# Copyright (C) 2009 Pexego Sistemas Informáticos. All Rights Reserved
# Copyright (c) 2013 Servicios Tecnológicos Avanzados (http://www.serviciosbaeza.com)
# ... | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP - Account renumber wizard
# Copyright (C) 2009 Pexego Sistemas Informáticos. All Rights Reserved
# Copyright (c) 2013 Servicios Tecnológicos Avanzados (http://www.serviciosbaeza.com)
# ... | agpl-3.0 | Python |
b2948a5f8809b3dfcc7a271666dc65c30b8ce36e | Add tests for mutually exclusive options. | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | tests/integration/cli_test.py | tests/integration/cli_test.py | # Import salt libs
try:
import integration
except ImportError:
if __name__ == '__main__':
import os
import sys
sys.path.insert(
0, os.path.abspath(
os.path.join(
os.path.dirname(__file__), '../'
)
)
)
... | # Import salt libs
try:
import integration
except ImportError:
if __name__ == '__main__':
import os
import sys
sys.path.insert(
0, os.path.abspath(
os.path.join(
os.path.dirname(__file__), '../'
)
)
)
... | apache-2.0 | Python |
d2965229b0cec08e6b497ce511dbad3c8f5e6801 | Create a method for getting Script's ClassName | VoxelDavid/elixir | elixir/processors.py | elixir/processors.py | import os.path
from elixir import rbxmx
class BaseProcessor:
"""The primary processor class.
A processor is what compilers use to determine what happens when they
encounter a file or folder. All of the `process` methods return a new
instance from `elixir.rbx`.
For example, when processing a file... | import os.path
from elixir import rbxmx
class BaseProcessor:
"""The primary processor class.
A processor is what compilers use to determine what happens when they
encounter a file or folder. All of the `process` methods return a new
instance from `elixir.rbx`.
For example, when processing a file... | mit | Python |
03e924a032eff571da11d98e62c966d0b86dc5a9 | Handle case of no description | RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline | bin/json2fasta.py | bin/json2fasta.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright [2009-2018] EMBL-European Bioinformatics Institute
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... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright [2009-2018] EMBL-European Bioinformatics Institute
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... | apache-2.0 | Python |
0f4a62bfb966c105c9b9cddf96ad3c3b891b2188 | Clean up | cherokee/pyscgi,cherokee/pyscgi | CTK/Refreshable.py | CTK/Refreshable.py | # CTK: Cherokee Toolkit
#
# Authors:
# Alvaro Lopez Ortega <alvaro@alobbs.com>
#
# Copyright (C) 2009 Alvaro Lopez Ortega
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License as published by the Free Software Foundation.
#
# ... | # CTK: Cherokee Toolkit
#
# Authors:
# Alvaro Lopez Ortega <alvaro@alobbs.com>
#
# Copyright (C) 2009 Alvaro Lopez Ortega
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License as published by the Free Software Foundation.
#
# ... | bsd-3-clause | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.