commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
d0ce6af2bb893904e8a3e36dd725707bd6d9f201 | indico/modules/attachments/tasks.py | indico/modules/attachments/tasks.py | # This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.core.celery import celery
from indico.core.db import db
from indico.modules.attachments.models... | # This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
import os
from indico.core.celery import celery
from indico.core.db import db
from indico.modules.attachm... | Delete material package temp file after creation | Delete material package temp file after creation
| Python | mit | ThiefMaster/indico,ThiefMaster/indico,DirkHoffmann/indico,pferreir/indico,indico/indico,pferreir/indico,indico/indico,indico/indico,pferreir/indico,pferreir/indico,DirkHoffmann/indico,DirkHoffmann/indico,ThiefMaster/indico,DirkHoffmann/indico,indico/indico,ThiefMaster/indico |
b0e3e93c3af70e42edf110e09039815575195c00 | packages/dependencies/spirv_tools.py | packages/dependencies/spirv_tools.py | {
'repo_type' : 'git',
'rename_folder' : 'spirv-tools',
'url' : 'https://github.com/KhronosGroup/SPIRV-Tools.git',
'branch' : 'aa270e568a3fd637f4a329611107b384a8023195',
'needs_make' : False,
'needs_make_install' : False,
'needs_configure' : False,
'recursive_git' : True,
'_info' : { 'version' : None, 'fancy_n... | {
'repo_type' : 'git',
'rename_folder' : 'spirv-tools',
'url' : 'https://github.com/KhronosGroup/SPIRV-Tools.git',
'needs_make' : False,
'needs_make_install' : False,
'needs_configure' : False,
'recursive_git' : True,
'_info' : { 'version' : None, 'fancy_name' : 'SPIRV Tools' },
} | Revert "packages/spirvtools: stick to last working commit" | Revert "packages/spirvtools: stick to last working commit"
This reverts commit cbaac43c95226b4ca5c9c1478467069966e9ef35.
| Python | mpl-2.0 | DeadSix27/python_cross_compile_script |
12914961c0c2851dd720e84ff811389b1cd936dd | wsgi.py | wsgi.py | """
WSGI script run on Heroku using gunicorn.
Exposes the app and configures it to use Heroku environment vars.
"""
import os
from suddendev import create_app, socketio
app = create_app()
if __name__ == '__main__':
app.run()
| """
WSGI script run on Heroku using gunicorn.
Exposes the app and configures it to use Heroku environment vars.
"""
import os
from suddendev import create_app, socketio
app = create_app()
if __name__ == '__main__':
socketio.run(app)
| Change to socketio.run() so WebSockets work on local runs. | [NG] Change to socketio.run() so WebSockets work on local runs.
| Python | mit | SuddenDevs/SuddenDev,SuddenDevs/SuddenDev,SuddenDevs/SuddenDev,SuddenDevs/SuddenDev |
e050864d333e4b332a21671cb5f08f2ffd9172fe | pipeline/archivebot/shared_config.py | pipeline/archivebot/shared_config.py | import os
import yaml
def config():
my_dir = os.path.dirname(__file__)
config_file = os.path.join(my_dir, '../../lib/shared_config.yml')
with open(config_file, 'r') as f:
return yaml.load(f.read())
def log_channel():
c = config()
return c['channels']['log']
def pipeline_channel():
c... | import os
import yaml
try:
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
def config():
my_dir = os.path.dirname(__file__)
config_file = os.path.join(my_dir, '../../lib/shared_config.yml')
with open(config_file, 'r') as f:
return yaml.load(f.read(), Loader = Loade... | Fix compatibility with PyYAML 6.0 (mandatory `Loader`) | Fix compatibility with PyYAML 6.0 (mandatory `Loader`)
| Python | mit | ArchiveTeam/ArchiveBot,ArchiveTeam/ArchiveBot,ArchiveTeam/ArchiveBot,ArchiveTeam/ArchiveBot,ArchiveTeam/ArchiveBot |
bb3d2927437a51d8144ec398085876bc3dedb5f6 | project_generator/commands/clean.py | project_generator/commands/clean.py | # Copyright 2014-2015 0xc0170
#
# 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 2014-2015 0xc0170
#
# 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,... | Clean command - tool help fix | Clean command - tool help fix
| Python | apache-2.0 | sarahmarshy/project_generator,ohagendorf/project_generator,0xc0170/project_generator,project-generator/project_generator |
d198b8d92ec42f8e5fc995f59c8776044b8950e8 | analysis/data_process/uk_2017/config.py | analysis/data_process/uk_2017/config.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Config file for the cleaning - plotting and notebook process"""
class CleaningConfig:
# Unprocessed dataset
raw_data = './dataset/raw_results-survey245554.csv'
# load the different answers to questions to classify questions based on that
question_fil... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Config file for the cleaning - plotting and notebook process"""
class CleaningConfig:
# Unprocessed dataset
raw_data = './dataset/raw_results-survey245554.csv'
# load the different answers to questions to classify questions based on that
question_fil... | Add the option for showing percent rather than count in plots | Add the option for showing percent rather than count in plots
| Python | bsd-3-clause | softwaresaved/international-survey |
da22196a8167a57c5edf39578ceece4efd8cfd63 | app/views.py | app/views.py | from app import app
from flask import make_response
@app.route('/')
@app.route('/index')
def index():
return make_response(open(app.root_path + '/templates/index.html').read()) | from flask import render_template
from app import app
@app.route('/')
@app.route('/index')
def index():
user = { 'nickname': 'Marvolo' } # fake user
posts = [ # fake array of posts
{
'author': { 'nickname': 'John' },
'body': 'Beautiful day in Portland!'
},
{
... | Set up mock data for index | Set up mock data for index
| Python | apache-2.0 | happyraul/tv |
158a2ffd17cf59a87092581dc0ce40cf0b82aa85 | bigbuild/management/commands/publish.py | bigbuild/management/commands/publish.py | from django.conf import settings
from bakery.management.commands.publish import Command as BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
# When in BIGBUILD_BRANCH_BUILD don't delete because we'll be syncing
# a different subdirectory for each one of our git branches
... | from django.conf import settings
from bakery.management.commands.publish import Command as BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
# When in BIGBUILD_BRANCH_BUILD don't delete because we'll be syncing
# a different subdirectory for each one of our git branches
... | Make an attribute call a little smarter | Make an attribute call a little smarter
| Python | mit | datadesk/django-bigbuild,datadesk/django-bigbuild,datadesk/django-bigbuild |
939c5fd069fafbe353fc9a209d2bd376e8d9bbd6 | gridded/gridded.py | gridded/gridded.py | class Gridded:
_grid_obj_classes = []
_grids_loaded = False
@classmethod
def _load_grid_objs(cls):
from pkg_resources import working_set
for ep in working_set.iter_entry_points('gridded.grid_objects'):
cls._grid_obj_classes.append(ep.load())
@classmethod
def load(c... | class Gridded:
_grid_obj_classes = []
_grids_loaded = False
@classmethod
def _load_grid_objs(cls):
from pkg_resources import working_set
for ep in working_set.iter_entry_points('gridded.grid_objects'):
cls._grid_obj_classes.append(ep.load())
@classmethod
def load(c... | Fix self- > cls, make super generic (no `nc`) | Fix self- > cls, make super generic (no `nc`)
| Python | mit | pyoceans/gridded |
d2adf86767857e9b57527c3db1d720b1f8f086a2 | openedx/stanford/djangoapps/register_cme/admin.py | openedx/stanford/djangoapps/register_cme/admin.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import ExtraInfo
admin.site.register(ExtraInfo)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import ExtraInfo
class ExtraInfoAdmin(admin.ModelAdmin):
"""
Admin interface for ExtraInfo model.
"""
readonly_fields = (
'user',
)
class Meta(object):
model = Extr... | Make `user` field read-only in `ExtraInfo` detail | Make `user` field read-only in `ExtraInfo` detail
Previously, server would hang trying to load an `ExtraInfo` detail page,
because the `user` field was rendering as a dropdown select menu loading
all users in the system. We fix this by making the field read-only.
| Python | agpl-3.0 | caesar2164/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform,caesar2164/edx-platform,caesar2164/edx-platform,Stanford-Online/edx-platform,caesar2164/edx-platform |
cf8621affe1e654bf5ec391d80f260cbce83445b | cli/cli.py | cli/cli.py | import argparse
parser = argparse.ArgumentParser(prog='moocx', description='EdX MOOC Data Anaylysis')
parser.add_argument('-v', '--version', action='version', version='0.1.0')
subparsers = parser.add_subparsers(help='commands')
# A list command
list_parser = subparsers.add_parser('list', help='List commands')
list_p... | import argparse
import os
parser = argparse.ArgumentParser(prog='moocx', description='EdX MOOC Data Anaylysis')
parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.1.0')
subparsers = parser.add_subparsers(help='commands')
# A list command
list_parser = subparsers.add_parser('list', help='Lis... | Define more arguments for command line parser | Define more arguments for command line parser
| Python | mit | McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research |
adfbd9b192316bc527259a1c0a01db0a8dbd5f3e | examples/rmg/liquid_phase/input.py | examples/rmg/liquid_phase/input.py | # Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# List of species
species(
label='oc... | # Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# List of species
species(
label='oc... | Change termination criteria for liquid phase examples to attainable value. | Change termination criteria for liquid phase examples to attainable value.
Conversion of octane was stuck at 8e-3 for quite some time...
| Python | mit | nyee/RMG-Py,faribas/RMG-Py,enochd/RMG-Py,faribas/RMG-Py,comocheng/RMG-Py,chatelak/RMG-Py,pierrelb/RMG-Py,pierrelb/RMG-Py,nickvandewiele/RMG-Py,chatelak/RMG-Py,enochd/RMG-Py,nyee/RMG-Py,KEHANG/RMG-Py,KEHANG/RMG-Py,nickvandewiele/RMG-Py,comocheng/RMG-Py |
e4e38ecd09b4c96e5b801b1bc9f7a943934c6485 | cobertura_clover_transform/converter.py | cobertura_clover_transform/converter.py | import lxml.etree as ET
import argparse
import pkg_resources
def convert(inxml):
dom = ET.parse(inxml)
xslt = ET.parse(pkg_resources.resource_stream('cobertura_clover_transform',
'transform.xslt'))
transform = ET.XSLT(xslt)
newdom = transform(dom)
... | import lxml.etree as ET
import argparse
import pkg_resources
def convert(inxml):
dom = ET.parse(inxml)
xslt = ET.parse(pkg_resources.resource_stream('cobertura_clover_transform',
'transform.xslt'))
transform = ET.XSLT(xslt)
newdom = transform(dom)
... | Add support for output to a file | Add support for output to a file
| Python | mit | cwacek/cobertura-clover-transform |
270e222301cf8c61e7632b366fba349552356928 | services/__init__.py | services/__init__.py | #!/usr/bin/env python
import os
import glob
__all__ = [ os.path.basename(f)[:-3] for f in glob.glob(os.path.dirname(__file__)+"/*.py")]
class InvalidConfigException(Exception):
pass
class PluginMount(type):
def __init__(cls, name, bases, attrs):
if not hasattr(cls, 'plugins'):
# This br... | #!/usr/bin/env python
import os
import glob
__all__ = [ os.path.basename(f)[:-3] for f in glob.glob(os.path.dirname(__file__)+"/*.py")]
class InvalidConfigException(Exception):
pass
class PluginMount(type):
def __init__(cls, name, bases, attrs):
if not hasattr(cls, 'plugins'):
# This br... | Add get_plugin method to the plugin base. | Add get_plugin method to the plugin base.
| Python | bsd-3-clause | vtcsec/wargame-scorer |
3a3997b19966560b828efb1699ee29a58cacbfc8 | spriteworld/configs/cobra/common.py | spriteworld/configs/cobra/common.py | # Copyright 2019 DeepMind Technologies Limited.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2019 DeepMind Technologies Limited.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | Remove noise from default COBRA configs. | Remove noise from default COBRA configs.
PiperOrigin-RevId: 265733849
Change-Id: Ie0e7c0385497852fd85c769ee85c951542c14463
| Python | apache-2.0 | deepmind/spriteworld |
752dca349d9f93c2a756e0b1b891006159eecbad | impactstoryanalytics/highcharts.py | impactstoryanalytics/highcharts.py | boilerplate = {
'chart': {
'renderTo': 'container',
'plotBackgroundColor': 'none',
'backgroundColor': 'none',
},
'title': {'text': 'null'},
'subtitle': {'text': 'null'},
'credits': {
'enabled': False
},
'plotOptions': {
'series': {
'marker'... | boilerplate = {
'chart': {
'renderTo': 'container',
'plotBackgroundColor': 'none',
'backgroundColor': 'none',
},
'title': {'text': None},
'subtitle': {'text': None},
'credits': {
'enabled': False
},
'plotOptions': {
'series': {
'marker': {
... | Use None instead of "null" in Highcharts boilerplate | Use None instead of "null" in Highcharts boilerplate
| Python | mit | Impactstory/impactstory-analytics,Impactstory/impactstory-analytics,Impactstory/impactstory-analytics,total-impact/impactstory-analytics,total-impact/impactstory-analytics,total-impact/impactstory-analytics,Impactstory/impactstory-analytics,total-impact/impactstory-analytics |
aee8d2911c3f19a9b748f21ae82592d823e0c57e | update.py | update.py | #! /usr/bin/python
import os, subprocess
os.chdir(os.path.dirname(os.path.abspath(__file__)))
subprocess.call([ 'python',
os.path.join('..', 'venus', 'planet.py'),
'planet.ini' ])
subprocess.call([ 'python',
'aws', 's3', 'sync',
'--region', 'us-e... | #! /usr/bin/python
import os, subprocess
os.chdir(os.path.dirname(os.path.abspath(__file__)))
subprocess.call([ 'python',
os.path.join('..', 'venus', 'planet.py'),
'planet.ini' ])
subprocess.call([ 'python',
'aws', 's3', 'sync',
'--region', 'us-e... | Set ACL explicitly to make files readable | Set ACL explicitly to make files readable
| Python | mit | kzys/planet-tempura |
9656b9fb1590513398bfca20f53483c6397b8095 | morepath/generic.py | morepath/generic.py | import reg
@reg.generic
def consumer(obj):
"""A consumer consumes steps in a stack to find an object.
"""
@reg.generic
def app(obj):
"""Get the application that this object is associated with.
"""
@reg.generic
def base(model):
"""Get the base that this model is associated with.
"""
@reg.... | import reg
@reg.generic
def consumer(obj):
"""A consumer consumes steps in a stack to find an object.
"""
raise NotImplementedError
@reg.generic
def app(obj):
"""Get the application that this object is associated with.
"""
raise NotImplementedError
@reg.generic
def base(model):
"""Get ... | Raise NotImplementedError for basic stuff. | Raise NotImplementedError for basic stuff.
| Python | bsd-3-clause | morepath/morepath,faassen/morepath,taschini/morepath |
8723611817a982907f3f0a98ed4678d587597002 | src/appleseed.python/test/runtests.py | src/appleseed.python/test/runtests.py |
#
# This source file is part of appleseed.
# Visit http://appleseedhq.net/ for additional information and resources.
#
# This software is released under the MIT license.
#
# Copyright (c) 2015-2016 Esteban Tovagliari, The appleseedhq Organization
#
# Permission is hereby granted, free of charge, to any person obtainin... |
#
# This source file is part of appleseed.
# Visit http://appleseedhq.net/ for additional information and resources.
#
# This software is released under the MIT license.
#
# Copyright (c) 2015-2016 Esteban Tovagliari, The appleseedhq Organization
#
# Permission is hereby granted, free of charge, to any person obtainin... | Add new unit tests to collection | Add new unit tests to collection
| Python | mit | pjessesco/appleseed,dictoon/appleseed,gospodnetic/appleseed,Aakash1312/appleseed,Vertexwahn/appleseed,aiivashchenko/appleseed,luisbarrancos/appleseed,appleseedhq/appleseed,Vertexwahn/appleseed,aytekaman/appleseed,glebmish/appleseed,aytekaman/appleseed,pjessesco/appleseed,est77/appleseed,dictoon/appleseed,luisbarrancos/... |
e85883389dd14377d63fc8c0b4decf486b3b7c2c | conveyor/exceptions.py | conveyor/exceptions.py | class HashMismatch(ValueError):
"""
Raised when the incoming hash of a file does not match the expected.
"""
| from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
class HashMismatch(ValueError):
"""
Raised when the incoming hash of a file does not match the expected.
"""
| Bring the standard imports over | Bring the standard imports over
| Python | bsd-2-clause | crateio/carrier |
d5acdacbbe4e4a5464b789a92a31b56cb94aa6a0 | GTT/test/example_usage.py | GTT/test/example_usage.py | """
This module is a general example using test data showing usage of sparks, excel
and the studbook structure.
"""
import os
from GTT import SPARKS
from GTT import excel as ew
from GTT import studBookStruct
TEST_DIR = os.path.dirname(__file__)
TEST_DATA_DIR = os.path.join(TEST_DIR, 'testData')
# my_sparks_reader = ... | """
This module is a general example using test data showing usage of sparks, excel
and the studbook structure.
"""
import os
from GTT import SPARKS
from GTT import excel as ew
from GTT import studBookStruct
TEST_DIR = os.path.dirname(__file__)
TEST_DATA_DIR = os.path.join(TEST_DIR, 'testData')
# my_sparks_reader = ... | Use the correct excel path. | Use the correct excel path.
| Python | mit | 314ish/StudbookToolkit |
faac7b98d3270267b731c97aa0318d532f75610c | dash_table/__init__.py | dash_table/__init__.py | from dash.dash_table import * # noqa: F401, F403, E402
import warnings
warnings.warn(
"""
The dash_table package is deprecated. Please replace
`import dash_table` with `from dash import dash_table`""",
stacklevel=2,
)
| from dash.dash_table import * # noqa: F401, F403, E402
import warnings
warnings.warn(
"""
The dash_table package is deprecated. Please replace
`import dash_table` with `from dash import dash_table`
Also, if you're using any of the table format helpers (e.g. Group), replace
`from dash_table.Format import Group` ... | Add info on table format helpers to warning message | Add info on table format helpers to warning message
| Python | mit | plotly/dash-table,plotly/dash-table,plotly/dash-table |
34a2b3a93bd96643d74fcb3c8d2f8db52d18253f | desubot.py | desubot.py | from motobot.irc_bot import IRCBot, IRCLevel
import desubot
import threading
def worker():
desubot.bot.run()
def main():
desubot.bot.load_plugins('plugins')
desubot.bot.join('#Moto-chan')
thread = threading.Thread(target=worker)
thread.start()
while True:
msg = input()
if... | from motobot.irc_bot import IRCBot, IRCLevel
import desubot
import threading
import traceback
def worker():
desubot.bot.run()
def main():
desubot.bot.load_plugins('plugins')
desubot.bot.join('#Moto-chan')
desubot.bot.join('#animu')
desubot.bot.join('#anime-planet.com')
thread = threading.... | Make exception on reload not crash input | Make exception on reload not crash input
| Python | mit | Motoko11/MotoBot |
fbd7c3b5627ba288ac400944ee242f3369143291 | calico_containers/tests/st/test_container_to_host.py | calico_containers/tests/st/test_container_to_host.py | from subprocess import CalledProcessError
from test_base import TestBase
from tests.st.utils.docker_host import DockerHost
class TestContainerToHost(TestBase):
def test_container_to_host(self):
"""
Test that a container can ping the host. (Without using the docker
network driver, since i... | from subprocess import CalledProcessError
from test_base import TestBase
from tests.st.utils.docker_host import DockerHost
class TestContainerToHost(TestBase):
def test_container_to_host(self):
"""
Test that a container can ping the host.
This function is important for Mesos, since the c... | Clarify test_containers_to_host not using libnetwork | Clarify test_containers_to_host not using libnetwork
| Python | apache-2.0 | fasaxc/calicoctl,fasaxc/calicoctl,projectcalico/calico-containers,insequent/calico-docker,tomdee/calico-docker,robbrockbank/calico-containers,robbrockbank/calicoctl,Metaswitch/calico-docker,TrimBiggs/calico-containers,tomdee/calico-docker,dalanlan/calico-docker,CiscoCloud/calico-docker,TeaBough/calico-docker,webwurst/c... |
a5585f7e437a402b10e4fa9094172a10a8955eac | __init__.py | __init__.py | import sys
import importlib
sys.modules[__package__] = importlib.import_module('.dataset', __package__)
| import os
__path__.append(os.path.dirname(__file__) + '/dataset')
from .dataset import *
| Replace importlib hack with __path__ | Replace importlib hack with __path__
| Python | apache-2.0 | analysiscenter/dataset |
e230f3af592ffce613fa7c2bcf05e2993df9e1a6 | __init__.py | __init__.py | #!/usr/bin/env python
# encoding: utf-8
"""
__init__.py
Created by Gabriel Brammer on 2011-05-18.
$URL$
$Author$
$Date$
"""
__version__ = "$Rev$"
from socket import gethostname as hostname
if hostname().startswith('uni'):
GRISM_HOME = '/3DHST/Spectra/Work/'
else:
GRISM_HOME = '/research/HST/GRISM/3DHST/'
... | #!/usr/bin/env python
# encoding: utf-8
"""
__init__.py
Created by Gabriel Brammer on 2011-05-18.
$URL$
$Author$
$Date$
"""
__version__ = "$Rev$"
from socket import gethostname as hostname
if hostname().startswith('uni'):
GRISM_HOME = '/3DHST/Spectra/Work/'
else:
GRISM_HOME = '/research/HST/GRISM/3DHST/'
... | Add separate "plotting" script for general plot setup. | Add separate "plotting" script for general plot setup.
git-svn-id: b93d21f79df1f7407664ec6e512ac344bf52ef2a@711 f9184c78-529c-4a83-b317-4cf1064cc5e0
| Python | mit | gbrammer/pygrism,gbrammer/unicorn,gbrammer/unicorn,gbrammer/pygrism |
57f5d8c1f02aa5d3a1be5fdc7302a15d416071dc | utils/decorators.py | utils/decorators.py | from functools import wraps
def bot_only(func):
@wraps(func)
def inner(self, *args, **kwargs):
if not self.user.bot:
return
return func(self, *args, **kwargs)
return inner
| from functools import wraps
def bot_only(coro):
@wraps(coro)
async def inner(self, *args, **kwargs):
if not self.user.bot:
return
return await coro(self, *args, **kwargs)
return inner
| Make bot_only async, because duh | Make bot_only async, because duh
| Python | mit | BeatButton/beattie-bot,BeatButton/beattie |
1e775fbc8e11f44b8a680e17ac35e735e52d5739 | fabfile.py | fabfile.py | from fabric.api import run, env
from fabric.context_managers import cd
import os
env.hosts = ['root@0.0.0.0:1337']
def update_podcasts():
with cd('"{}"'.format(os.path.dirname(__file__))):
run('python3 manage.py updatepodcasts')
def setup_dev():
with cd('"{}"'.format(os.path.dirname(__file__))):
... | from fabric.api import run, env
from fabric.context_managers import cd
import os
env.hosts = ['root@0.0.0.0:1337']
def update_podcasts():
with cd('"{}"'.format(os.path.dirname(__file__))):
run('python3 manage.py updatepodcasts')
def fetch_episodes():
with cd('"{}"'.format(os.path.dirname(__file__))... | Add fab command for fetching episodes | Add fab command for fetching episodes
| Python | mit | matachi/sputnik,matachi/sputnik,matachi/sputnik,matachi/sputnik |
e41d46fe0539aa102a8af92236add5ba876db7a0 | elections/mixins.py | elections/mixins.py | from django.conf import settings
from django.http import Http404
from django.utils.translation import ugettext as _
class ElectionMixin(object):
'''A mixin to add election data from the URL to the context'''
def dispatch(self, request, *args, **kwargs):
self.election = election = self.kwargs['electio... | from django.utils.translation import ugettext as _
from django.shortcuts import get_object_or_404
from models import Election
class ElectionMixin(object):
'''A mixin to add election data from the URL to the context'''
def dispatch(self, request, *args, **kwargs):
self.election = election = self.kwarg... | Use the Election model in the elections Mixin | Use the Election model in the elections Mixin
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,neavouli/yournextrepresentative,dat... |
d9e7816da08a3d66e63356ea6f4474cc5f7d6b26 | bush/main.py | bush/main.py | from bush import option
from bush.spinner import Spinner
from bush.aws.ec2 import EC2
from bush.aws.iam import IAM
def run():
(options, args) = option.parse_args("bush")
output = ''
spinner = Spinner()
spinner.start()
if args[0] == 'ec2':
ec2 = EC2(options)
if args[1] == 'ls':
... | import sys
import traceback
from bush import option
from bush.spinner import Spinner
from bush.aws.ec2 import EC2
from bush.aws.iam import IAM
def run():
(options, args) = option.parse_args("bush")
output = ''
spinner = Spinner()
spinner.start()
try:
output = run_aws(options, args)
... | Fix keep turning spinner when error occurred | Fix keep turning spinner when error occurred
| Python | mit | okamos/bush |
18c99ee2b96564913cbd406bb540af10b078b2f3 | example.py | example.py | from datetime import datetime
from timetabler.schedule import Schedule
from timetabler.ssc.course import Lecture, Discussion
def main():
s = Schedule(["EECE 353", "CPSC 304", "EECE 381", "GEOG 122"],
session="2014W", terms=[2])
# STTs are for Vantage College students
s.courses["GEOG 122"... | import json
from datetime import datetime
from timetabler.schedule import Schedule
from timetabler.ssc.course import Lecture, Discussion
def main():
s = Schedule(["EECE 353", "CPSC 304", "EECE 381", "GEOG 122"],
session="2014W", terms=[2])
# STTs are for Vantage College students
s.course... | Add latest starting time sorting | Add latest starting time sorting
| Python | mit | hfaran/ubc-timetabler |
d5e3a4f76121b4c1c38787156c50e0602c4de43f | fabfile.py | fabfile.py | # Simple Tasks
def hello():
print 'Hello ThaiPy!'
def hi(name='Kan'):
print 'Hi ' + name
# Local Commands
from fabric.api import local, lcd
def deploy_fizzbuzz():
with lcd('fizzbuzz'):
local('python fizzbuzz_test.py')
local('git add fizzbuzz.py fizzbuzz_test.py')
local('git c... | # Simple Tasks
def hello():
print 'Hello ThaiPy!'
def hi(name='Kan'):
print 'Hi ' + name
# Local Commands
from fabric.api import local, lcd
def deploy_fizzbuzz():
with lcd('fizzbuzz'):
local('python fizzbuzz_test.py')
local('git add fizzbuzz.py fizzbuzz_test.py')
local('git c... | Add deploy task to deploy a new Nginx index page | Add deploy task to deploy a new Nginx index page
| Python | mit | zkan/fabric-workshop,zkan/fabric-workshop |
35308ba3dbfc25e86fab720e67d6a9576d6937c9 | fabfile.py | fabfile.py | from fabric.api import lcd, local
from fabric.decorators import runs_once
import os
fabfile_dir = os.path.dirname(__file__)
def update_theme():
theme_dir = os.path.join(fabfile_dir, 'readthedocs', 'templates', 'sphinx')
if not os.path.exists('/tmp/sphinx_rtd_theme'):
local('git clone https://github.... | from fabric.api import lcd, local
from fabric.decorators import runs_once
import os
fabfile_dir = os.path.dirname(__file__)
def i18n():
with lcd('readthedocs'):
local('rm -rf rtd_tests/tests/builds/')
local('tx pull')
local('./manage.py makemessages --all')
#local('tx push -s')
... | Drop fab file task for updating theme as well | Drop fab file task for updating theme as well
| Python | mit | espdev/readthedocs.org,pombredanne/readthedocs.org,davidfischer/readthedocs.org,rtfd/readthedocs.org,davidfischer/readthedocs.org,davidfischer/readthedocs.org,safwanrahman/readthedocs.org,tddv/readthedocs.org,techtonik/readthedocs.org,wijerasa/readthedocs.org,techtonik/readthedocs.org,espdev/readthedocs.org,stevepiercy... |
97990ea039228eb3311b148c047fae015a4f4d7e | examples/boilerplates/base_test_case.py | examples/boilerplates/base_test_case.py | '''
You can use this as a boilerplate for your test framework.
Define your customized library methods in a master class like this.
Then have all your test classes inherit it.
BaseTestCase will inherit SeleniumBase methods from BaseCase.
With Python 3, simplify "super(...)" to super().setUp() and super().tearDown()
'''
... | '''
You can use this as a boilerplate for your test framework.
Define your customized library methods in a master class like this.
Then have all your test classes inherit it.
BaseTestCase will inherit SeleniumBase methods from BaseCase.
With Python 3, simplify "super(...)" to super().setUp() and super().tearDown()
'''
... | Update the boilerplate example by adding "has_exception()" | Update the boilerplate example by adding "has_exception()"
| Python | mit | seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase |
88964dc79be1c88f1a197c5a59f342c9b7749ed2 | fantasyStocks/stocks/views.py | fantasyStocks/stocks/views.py | from django.shortcuts import render
from django.http import HttpResponse
from stocks import forms
# Create your views here.
def index(request):
regForm = forms.RegistrationForm()
logForm = forms.LoginForm()
return render(request, "index.html", {"loginForm" : logForm, "registrationForm" : regForm})
def ins... | from django.shortcuts import render
from django.http import HttpResponse
from stocks import forms
from django.contrib.auth.models import User
# Create your views here.
def index(request):
# If we got here through a submission...
if request.method == "POST":
if request.POST.get("password1", None):
... | Make some progress on the view. | Make some progress on the view.
I need to make it return a HttpResponse though. oops.
| Python | apache-2.0 | ddsnowboard/FantasyStocks,ddsnowboard/FantasyStocks,ddsnowboard/FantasyStocks |
93af551b8f0ce03b16dd7aad1a2963cc4e5b6d6a | fabfile.py | fabfile.py | from fabric.api import cd, run, sudo, env, roles, execute
from datetime import datetime
env.roledefs = {
'webuser': ['bloge@andrewlorente.com'],
'sudoer': ['alorente@andrewlorente.com'],
}
env.hosts = ['andrewlorente.com']
def deploy():
release_id = datetime.now().strftime("%Y%m%d%H%M%S")
execute(buil... | from fabric.api import cd, run, sudo, env, roles, execute
from datetime import datetime
env.roledefs = {
'webuser': ['bloge@andrewlorente.com'],
'sudoer': ['alorente@andrewlorente.com'],
}
env.hosts = ['andrewlorente.com']
def deploy():
release_id = datetime.now().strftime("%Y%m%d%H%M%S")
execute(buil... | Fix the `release` step of deploy | Fix the `release` step of deploy
lol
| Python | mit | ErinCall/bloge |
cf026dbabffd92cb51baeb63c1e1e88045e946b9 | netfields/forms.py | netfields/forms.py | import re
from IPy import IP
from django import forms
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
class NetInput(forms.Widget):
input_type = 'text'
def render(self, name, value, attrs=None):
# Default forms.Widget compares value != '' which breaks IP... | import re
from IPy import IP
from django import forms
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
class NetInput(forms.Widget):
input_type = 'text'
def render(self, name, value, attrs=None):
# Default forms.Widget compares value != '' which breaks IP... | Fix casting in form to_python() method | Fix casting in form to_python() method
NetAddressFormField.to_python() was calling "self.python_type()" to
cast the form value to an IP() object. Unfortunately, for is no such
method defined here, or in the Django forms.Field() class, at least
in 1.4 and up | Python | bsd-3-clause | jmacul2/django-postgresql-netfields |
87bd987ebb802200540c23cfccaba2c56a672ed5 | openmc/__init__.py | openmc/__init__.py | from openmc.arithmetic import *
from openmc.cell import *
from openmc.checkvalue import *
from openmc.mesh import *
from openmc.element import *
from openmc.geometry import *
from openmc.nuclide import *
from openmc.macroscopic import *
from openmc.material import *
from openmc.plots import *
from openmc.region import ... | from openmc.arithmetic import *
from openmc.cell import *
from openmc.checkvalue import *
from openmc.mesh import *
from openmc.element import *
from openmc.geometry import *
from openmc.nuclide import *
from openmc.macroscopic import *
from openmc.material import *
from openmc.plots import *
from openmc.region import ... | Make Model available in main openmc namespace | Make Model available in main openmc namespace
| Python | mit | amandalund/openmc,walshjon/openmc,amandalund/openmc,walshjon/openmc,amandalund/openmc,walshjon/openmc,walshjon/openmc,amandalund/openmc |
3d58796f9bedb607cd2c23aa7dcb6ce86b8af075 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jon LaBelle
# Copyright (c) 2017 Jon LaBelle
#
# License: MIT
#
"""This module exports the Markdownlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Markdownlint(NodeLinter):
"""Provi... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jon LaBelle
# Copyright (c) 2017 Jon LaBelle
#
# License: MIT
#
"""This module exports the Markdownlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Markdownlint(NodeLinter):
"""Provi... | Add more markdown syntax detection's | Add more markdown syntax detection's
Detect 'markdown gfm', 'multimarkdown' and 'markdown extended'.
Closes #2 | Python | mit | jonlabelle/SublimeLinter-contrib-markdownlint,jonlabelle/SublimeLinter-contrib-markdownlint |
8b4b5705907e1ec5f9dd3148560dc1bf4cd5b9b7 | bin/detail/get_nmake_environment.py | bin/detail/get_nmake_environment.py | # Copyright (c) 2014, Ruslan Baratov
# All rights reserved.
import detail.util
import os
import sys
def get(arch, vs_version):
vs_path_env = 'VS{}0COMNTOOLS'.format(vs_version)
vs_path = os.getenv(vs_path_env)
if not vs_path:
sys.exit(
'Environment variable {} is empty, '
'looks like Visual ... | # Copyright (c) 2014, Ruslan Baratov
# All rights reserved.
import detail.util
import os
import sys
def get(arch, vs_version):
vs_path_env = 'VS{}0COMNTOOLS'.format(vs_version)
vs_path = os.getenv(vs_path_env)
if not vs_path:
sys.exit(
'Environment variable {} is empty, '
'looks like Visual ... | Fix vcvarsall_dir for Visual Studio 2017 | polly.py: Fix vcvarsall_dir for Visual Studio 2017
[skip ci]
| Python | bsd-2-clause | idscan/polly,idscan/polly,ruslo/polly,ruslo/polly |
07e300e393701d8bddf6646a76542555b92c9f4d | pmxbot/__init__.py | pmxbot/__init__.py | # -*- coding: utf-8 -*-
# vim:ts=4:sw=4:noexpandtab
import importlib
from .dictlib import ConfigDict
config = ConfigDict(
bot_nickname = 'pmxbot',
database = 'sqlite:pmxbot.sqlite',
server_host = 'irc.freenode.net',
server_port = 6667,
use_ssl = False,
password = None,
silent_bot = False,
log_channels = [],
... | # -*- coding: utf-8 -*-
# vim:ts=4:sw=4:noexpandtab
import importlib
from .dictlib import ConfigDict
config = ConfigDict(
bot_nickname = 'pmxbot',
database = 'sqlite:pmxbot.sqlite',
server_host = 'localhost',
server_port = 6667,
use_ssl = False,
password = None,
silent_bot = False,
log_channels = [],
other_... | Use IRC server on localhost by default | Use IRC server on localhost by default
| Python | mit | yougov/pmxbot,yougov/pmxbot,yougov/pmxbot |
b3807e5ddb50ca34af3f4f187bc01fcc284afb20 | bin/jenkins.py | bin/jenkins.py | #!/usr/bin/env python3
# Copyright (c) 2014, Ruslan Baratov
# All rights reserved.
import os
import subprocess
import sys
def run():
toolchain = os.getenv('TOOLCHAIN')
if not toolchain:
sys.exit('Environment variable TOOLCHAIN is empty')
build_type = os.getenv('BUILD_TYPE')
if not build_type:
sys.ex... | #!/usr/bin/env python3
# Copyright (c) 2014, Ruslan Baratov
# All rights reserved.
import os
import subprocess
import sys
def run():
toolchain = os.getenv('TLC')
if not toolchain:
sys.exit('Environment variable TLC is empty (TooLChain)')
config = os.getenv('CFG')
if not config:
sys.exit('Environment... | Use short axis names to prevent windows path overflow | Use short axis names to prevent windows path overflow
| Python | bsd-2-clause | headupinclouds/polly,ruslo/polly,headupinclouds/polly,idscan/polly,idscan/polly,headupinclouds/polly,ruslo/polly |
92340a1238636d9160ce120cd9a12ed260007aca | app/__init__.py | app/__init__.py | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from config import config
app = Flask(__name__)
app.config.from_object(config['development'])
bootstrap = Bootstrap(app)
db = SQLAlchemy(app)
login_manager = LoginMana... | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from config import config
app = Flask(__name__)
app.config.from_object(config['development'])
bootstrap = Bootstrap(app)
db = SQLAlchemy(app)
login_manager = LoginMana... | Add default login manager message category | Add default login manager message category
| Python | mit | timzdevz/fm-flask-app |
dbfc1a11c0ced8ab7a997944e943a17ff0069199 | lexer.py | lexer.py | import ply.lex as lex
import re
tokens = ( 'SECTION',
'IDENTIFIER',
'LBRACE',
'RBRACE',
'SEMI',
'TRUE',
'FALSE' )
def t_SECTION(t):
r'section'
return t
def t_TRUE(t):
r'(true|1)'
return t
def t_FALSE(t):
r'(false|0)'
... | import ply.lex as lex
import re
tokens = ( 'SECTION',
'IDENTIFIER',
'STRING',
'LBRACE',
'RBRACE',
'SEMI',
'EQU',
'TRUE',
'FALSE' )
def t_SECTION(t):
r'section'
return t
def t_TRUE(t):
r'(true|1)'
retur... | Add rudimentary string support and a token for '=' sign. | Add rudimentary string support and a token for '=' sign.
| Python | cc0-1.0 | dmbaturin/ply-example |
8e28c627c0a84939bb44c2c77fa3e4b3de4932bf | erroneous/models.py | erroneous/models.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
class Error(models.Model):
"""
Model for storing the individual errors.
"""
kind = models.CharField(_('type'),
null=True, blank=True, max_length=128, db_index=True
)
info = models.TextField(
nul... | from django.db import models
from django.utils.translation import ugettext_lazy as _
class Error(models.Model):
"""
Model for storing the individual errors.
"""
kind = models.CharField(_('type'),
null=True, blank=True, max_length=128, db_index=True
)
info = models.TextField(
nul... | Remove verify_exists kwarg, which was deprecated in django 1.3 and causes an error in django 1.5 | Remove verify_exists kwarg, which was deprecated in django 1.3 and causes an error in django 1.5 | Python | mit | mbelousov/django-erroneous,mbelousov/django-erroneous,mridang/django-erroneous |
79d02616ab6d70b029876b8a2de425026e6268c4 | pycalc.py | pycalc.py | import sys
import lexer
import execute
while True:
instr = input("» ")
toks = lexer.to_toks(instr)
rpn = lexer.to_rpn(toks)
result = execute.eval_rpn(rpn)
if result is not None:
print(result)
if len(sys.argv) >= 2:
break
| # vim: set fileencoding=utf-8
import sys
if sys.version_info.major < 3:
print("This program is for python version 3 only.")
sys.exit(3)
import lexer
import execute
while True:
instr = input("» ")
toks = lexer.to_toks(instr)
rpn = lexer.to_rpn(toks)
result = execute.eval_rpn(rpn)
if res... | Make main program throw warning on python2. | Make main program throw warning on python2.
| Python | mit | 5225225/pycalc,5225225/pycalc |
b636affedea494f1733bf413986a8546d3495c53 | chipy_org/apps/meetings/urls.py | chipy_org/apps/meetings/urls.py | from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required
from meetings.views import (PastMeetings,
ProposeTopic,
MyTopics,
RSVP,
PastTopics,
)
urlpatterns = patterns(... | from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required
from meetings.views import (PastMeetings,
ProposeTopic,
MyTopics,
RSVP,
PastTopics,
)
urlpatterns = patterns(... | Add url for anonymous rsvp with key | Add url for anonymous rsvp with key
| Python | mit | agfor/chipy.org,bharathelangovan/chipy.org,bharathelangovan/chipy.org,agfor/chipy.org,tanyaschlusser/chipy.org,bharathelangovan/chipy.org,brianray/chipy.org,brianray/chipy.org,tanyaschlusser/chipy.org,brianray/chipy.org,chicagopython/chipy.org,chicagopython/chipy.org,tanyaschlusser/chipy.org,chicagopython/chipy.org,chi... |
ee61dab40c4c3eaa1553397091a17a3292dcf9d6 | grako/ast.py | grako/ast.py | from collections import OrderedDict, Mapping
import json
class AST(Mapping):
def __init__(self, **kwargs):
self._elements = OrderedDict(**kwargs)
def add(self, key, value):
previous = self._elements.get(key, None)
if previous is None:
self._elements[key] = [value]
e... | from collections import OrderedDict, Mapping
import json
__all__ = ['AST']
class AST(Mapping):
def __init__(self, **kwargs):
self._elements = OrderedDict(**kwargs)
def add(self, key, value):
previous = self._elements.get(key, None)
if previous is None:
self._elements[key] ... | Allow to set items in AST. | Allow to set items in AST.
| Python | bsd-2-clause | frnknglrt/grako,vmuriart/grako |
5442facddbcf9b8adff247edcf3bd27a8fda2c10 | great/tap.py | great/tap.py | from __future__ import absolute_import
from minion.twisted import MinionResource
from twisted.application import strports
from twisted.python import usage
from twisted.python.filepath import FilePath
from twisted.web import server
from twisted.web.static import File
import twisted.web.resource
from great.web import c... | from __future__ import absolute_import
from minion.twisted import MinionResource
from twisted.application import strports
from twisted.python import usage
from twisted.python.filepath import FilePath
from twisted.web import server
from twisted.web.static import File
import alembic
import alembic.config
import twisted.... | Add a flag during startup. | Add a flag during startup.
| Python | mit | Julian/Great,Julian/Great,Julian/Great |
b4613b6b20c6fae1b73095363078201e666bd5bc | djangosaml2/urls.py | djangosaml2/urls.py | # Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# 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
#
# ... | # Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# 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
#
# ... | Fix imports for Django 1.6 and above | Fix imports for Django 1.6 and above
| Python | apache-2.0 | damienmarie-alation/djangosaml2,writepython/djangosaml2,BetterWorks/djangosaml2,knaperek/djangosaml2,writepython/djangosaml2,WebSpider/djangosaml2,knaperek/djangosaml2,MiguelSR/djangosaml2,WebSpider/djangosaml2,BetterWorks/djangosaml2,MiguelSR/djangosaml2,damienmarie-alation/djangosaml2 |
99ea4348efe1212ddb814680272643829ffabf8f | djangosaml2/urls.py | djangosaml2/urls.py | # Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# 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
#
# ... | # Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# 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
#
# ... | Fix imports for Django 1.6 and above | Fix imports for Django 1.6 and above
| Python | apache-2.0 | City-of-Helsinki/djangosaml2,WiserTogether/djangosaml2,shabda/djangosaml2,kviktor/djangosaml2-py3,advisory/djangosaml2_tenant,advisory/djangosaml2_tenant,GradConnection/djangosaml2,WiserTogether/djangosaml2,City-of-Helsinki/djangosaml2,shabda/djangosaml2,GradConnection/djangosaml2,kviktor/djangosaml2-py3 |
22ba81ee7bed81c3a1da4b8d2ace4c38a957b5dd | server.py | server.py | import bottle
import waitress
import controller
import breathe
if __name__ == '__main__':
bottle_app = bottle.app()
breather = breathe.Breathe()
my_controller = controller.Controller(bottle_app, breather)
waitress.serve(bottle_app, host='0.0.0.0', port=7000)
| import bottle
import waitress
import controller
import breathe
from pytz import timezone
from apscheduler.schedulers.background import BackgroundScheduler
bottle_app = bottle.app()
scheduler = BackgroundScheduler()
scheduler.configure(timezone=timezone('US/Pacific'))
breather = breathe.Breathe()
my_controller = contro... | Add scheduler. Schedule lights on for 9:00pm and lights off for 11:00pm | Add scheduler. Schedule lights on for 9:00pm and lights off for 11:00pm
| Python | mit | tipsqueal/duwamish-lighthouse,tipsqueal/duwamish-lighthouse,YonasBerhe/duwamish-lighthouse,illumenati/duwamish-lighthouse,illumenati/duwamish-lighthouse |
b8f893089a35627305b2a6dd1f6ba27268f8e865 | openphoto/multipart_post.py | openphoto/multipart_post.py | import mimetypes
import mimetools
def encode_multipart_formdata(params, files):
boundary = mimetools.choose_boundary()
lines = []
for name in params:
lines.append("--" + boundary)
lines.append("Content-Disposition: form-data; name=\"%s\"" % name)
lines.append("")
lines.appe... | import os
import mimetypes
import mimetools
def encode_multipart_formdata(params, files):
boundary = mimetools.choose_boundary()
lines = []
for name in params:
lines.append("--" + boundary)
lines.append("Content-Disposition: form-data; name=\"%s\"" % name)
lines.append("")
... | Expand "~" to home path | Expand "~" to home path
| Python | apache-2.0 | photo/openphoto-python,photo/openphoto-python |
605011cbb7953e8629f844d16d62f4632727b023 | core/cachecontroller/schedinstances/ArtPackages.py | core/cachecontroller/schedinstances/ArtPackages.py | from core.cachecontroller.BaseURLTasksProvider import BaseURLTasksProvider
import queue, threading
from datetime import datetime, timedelta
import logging
class ArtPackages(BaseURLTasksProvider):
BASIC_PRIORITY = 1
lock = threading.RLock()
logger = logging.getLogger(__name__ + ' ArtPackages')
def get... | from core.cachecontroller.BaseURLTasksProvider import BaseURLTasksProvider
import queue, threading
from datetime import datetime, timedelta
import logging
class ArtPackages(BaseURLTasksProvider):
BASIC_PRIORITY = 1
N_DAYS_WINDOW = 14
lock = threading.RLock()
logger = logging.getLogger(__name__ + ' Art... | Increase the timewindow check of ART tests in cachecontroller | Increase the timewindow check of ART tests in cachecontroller
| Python | apache-2.0 | PanDAWMS/panda-bigmon-core,PanDAWMS/panda-bigmon-core,PanDAWMS/panda-bigmon-core,PanDAWMS/panda-bigmon-core |
a5626b61892549aa376969e44a26c01a69ddd8f8 | lib/oeqa/runtime/cases/parselogs_rpi.py | lib/oeqa/runtime/cases/parselogs_rpi.py | from oeqa.runtime.cases.parselogs import *
rpi_errors = [
'bcmgenet fd580000.genet: failed to get enet-eee clock',
'bcmgenet fd580000.genet: failed to get enet-wol clock',
'bcmgenet fd580000.genet: failed to get enet clock',
]
ignore_errors['raspberrypi4'] = rpi_errors + common_errors
ignore_errors['raspb... | from oeqa.runtime.cases.parselogs import *
rpi_errors = [
'bcmgenet fd580000.genet: failed to get enet-eee clock',
'bcmgenet fd580000.genet: failed to get enet-wol clock',
'bcmgenet fd580000.genet: failed to get enet clock',
'bcmgenet fd580000.ethernet: failed to get enet-eee clock',
'bcmgenet fd58... | Add 5.4 specific error messages to ignore list | oeqa: Add 5.4 specific error messages to ignore list
with 5.4 fd580000.genet has been replaced with fd580000.ethernet in the
error text
Fixes
https://github.com/raspberrypi/linux/issues/3884
Signed-off-by: Khem Raj <729d64b6f67515e258459a5f6d20ec88b2caf8df@gmail.com>
| Python | mit | agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,schnitzeltony/meta-raspberrypi,schnitzeltony/meta-raspberrypi,schnitzeltony/meta-raspberrypi,agherzan/meta-raspberrypi |
b4e065bb15cdc7eda91c89fc0bc3472064d5aac0 | djangocms_spa/decorators.py | djangocms_spa/decorators.py | from functools import wraps
from django.conf import settings
from django.core.cache import cache
from django.template.response import ContentNotRenderedError
from django.utils.decorators import available_attrs
def cache_view(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view... | from functools import wraps
from django.conf import settings
from django.core.cache import cache
from django.template.response import ContentNotRenderedError
from django.utils.decorators import available_attrs
def cache_view(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view... | Use full path as cache key | Use full path as cache key
| Python | mit | dreipol/djangocms-spa,dreipol/djangocms-spa |
8a34e665539b10a8e90c86f89a7e2d5881b36519 | functional_tests.py | functional_tests.py | from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://localhost:8000')
assert 'Django' in browser.title
| from selenium import webdriver
import unittest
class NewVisitorTest(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.quit()
def test_can_start_a_list_and_retrieve_it_later(self):
self.... | Add first FT spec comments | Add first FT spec comments
| Python | mit | rodowi/remember-the-beer |
e53232a0d4118f415f694084deb602bcc05cb635 | scripts/server_socket.py | scripts/server_socket.py | # Echo server program
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
... | #!/usr/bin/python
import socket
import rospy
from geometry_msgs.msg import (
Twist
)
from std_msgs.msg import (
String,
)
class SocketListener(object):
def __init__(self, host, port, topic):
# ROS stuff first
rospy.init_node("myo_socket_listener")
self._pub = rospy.Publisher(topi... | Create class for server and create publisher | Create class for server and create publisher
| Python | mit | ipab-rad/myo_baxter_pc,ipab-rad/baxter_myo,ipab-rad/baxter_myo,ipab-rad/myo_baxter_pc |
7a408eb5186ef5a7adce026f0629ee1592cd6077 | inpassing/config.py | inpassing/config.py | # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
SQLALCHEMY_DATABASE_URI='sqlite:///db.sqlite3'
SQLALCHEMY_TRACK_MODIFICATIONS=False
| # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
import os
SECRET_KEY=os.getenv('INPASSING_SECRET_KEY')
SQLALCHEMY_DATABASE_URI='sqlite:///db.sqlite3'
SQLALCHEMY_TRACK_MODIFICATIONS=False
| Use a secret key (get it from an env var) | Use a secret key (get it from an env var)
| Python | mit | lukesanantonio/inpassing-backend,lukesanantonio/inpassing-backend |
7c2311534cf1cbef7880795827c88e7ce075e2ae | tests/pthread_barrier/tests/01-run.py | tests/pthread_barrier/tests/01-run.py | #!/usr/bin/env python3
import sys
from testrunner import run
def testfunc(child):
child.expect(r'NUM_CHILDREN: (\d+), NUM_ITERATIONS: (\d+)\r\n')
children = int(child.match.group(1))
iterations = int(child.match.group(2))
for i in range(children):
child.expect(f'Start {i + 1}')
for _ in r... | #!/usr/bin/env python3
import sys
from testrunner import run
def testfunc(child):
child.expect(r'NUM_CHILDREN: (\d+), NUM_ITERATIONS: (\d+)\r\n')
children = int(child.match.group(1))
iterations = int(child.match.group(2))
for i in range(children):
child.expect('Start {}'.format(i + 1))
fo... | Remove f string in test | tests/thread_pthread_barrier: Remove f string in test
This causes nightlies to fail as the HiL test runners don't have python3.6+
| Python | lgpl-2.1 | kYc0o/RIOT,OlegHahm/RIOT,OlegHahm/RIOT,ant9000/RIOT,miri64/RIOT,kaspar030/RIOT,jasonatran/RIOT,OlegHahm/RIOT,ant9000/RIOT,miri64/RIOT,kaspar030/RIOT,kaspar030/RIOT,RIOT-OS/RIOT,kYc0o/RIOT,kYc0o/RIOT,ant9000/RIOT,miri64/RIOT,miri64/RIOT,OlegHahm/RIOT,jasonatran/RIOT,RIOT-OS/RIOT,ant9000/RIOT,jasonatran/RIOT,jasonatran/R... |
bfbb685854724285bdbfcd583b3d6c41674a6222 | vext/syspy/pyinfo.py | vext/syspy/pyinfo.py | """
This file is run by the system python, and outputs paths the
import mechanism in the virtualenv will need to be able to
import libraries from.
"""
import json
import os
import sys
"""
Return paths from the system python
"""
def py_info():
data = {
"path": os.environ['PATH'],
"sys.path": sys.p... | """
This file is run by the system python, and outputs paths the
import mechanism in the virtualenv will need to be able to
import libraries from.
"""
import json
import os
import sys
"""
Return paths from the system python
"""
def py_info():
data = {
"path": os.environ['PATH'].split(os.pathsep),
... | Make sure path is in a list | Make sure path is in a list
| Python | mit | stuaxo/vext |
fd48bda18bac9fe5380205ba1333af0d4066ae82 | tests/test_types.py | tests/test_types.py | import numpy as np
from pybotics.types import Vector
def test_vector():
x = [1.1, 2.2, 3.3]
assert isinstance(x, Vector)
x = np.array([1.1, 2.2, 3.3])
assert isinstance(x, Vector)
x = (1.1, 2.2, 3.3)
assert isinstance(x, Vector)
pass
| import numpy as np
from typing import List
from pybotics.types import Vector
def test_vector():
pass
| Revert "want to be able to test for Vector type" | Revert "want to be able to test for Vector type"
This reverts commit 93f09d784a73adcdccef3a77cf8fdc2d12ce4518.
| Python | mit | nnadeau/pybotics |
436b005217ab92fd06526d9681bc37266c394212 | estmator_project/est_quote/views.py | estmator_project/est_quote/views.py | from .models import Quote, Category, Product
from django.views.generic.edit import CreateView, UpdateView
class QuoteCreateView(CreateView):
model = Quote
fields = ['name']
template_name = 'quote.html'
success_url = '/'
def get_form(self, form):
form = super(QuoteCreateView, self).get_for... | from .models import Quote, Category, Product
from django.views.generic.edit import CreateView, UpdateView
class QuoteCreateView(CreateView):
model = Quote
fields = ['name']
template_name = 'quote.html'
success_url = '/'
def get_form(self):
form = super(QuoteCreateView, self).get_form()
... | Update view for basic quote form. | Update view for basic quote form.
| Python | mit | Estmator/EstmatorApp,Estmator/EstmatorApp,Estmator/EstmatorApp |
9d2161ada6a0d957ca13e49431533770ef672014 | files.py | files.py | import numpy as np
from scipy.io import wavfile
def normalize(samples):
max_value = np.max(np.abs(samples))
return samples / max_value if max_value != 0 else samples
def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))-1):
'''
Saves samples in given sampling frequency to ... | import numpy as np
from scipy.io import wavfile
def normalize(samples):
max_value = np.max(np.abs(samples))
return samples / max_value if max_value != 0 else samples
def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))-1):
'''
Saves samples in given sampling frequency to ... | Allow mixing the loaded WAV file from stereo to mono. | Allow mixing the loaded WAV file from stereo to mono.
| Python | mit | bzamecnik/tfr,bzamecnik/tfr |
a4bdb7113dba8ed819d8454a1e8f2916ee33d9a6 | dns/exception.py | dns/exception.py | # Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED "... | # Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED "... | Support string representation for all DNSExceptions. | Support string representation for all DNSExceptions.
Doc string is used in cases where more specific message was not provided
during instantiation/raise.
| Python | isc | rcorrieri/dnspython,leeclemens/dnspython,Abhayakara/dnspython,fjxhkj/dnspython,tow/dnspython,cluck/dnspython,tomlanyon/dnspython,preo/dnspython |
b3b85d3a481e4b2cf9df37666a9527ccf8a13bfc | build/fbcode_builder/specs/fbthrift.py | build/fbcode_builder/specs/fbthrift.py | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import spec... | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.fmt as fmt
import specs.rsocke... | Migrate from Folly Format to fmt | Migrate from Folly Format to fmt
Summary: Migrate from Folly Format to fmt which provides smaller compile times and per-call binary code size.
Reviewed By: alandau
Differential Revision: D14954926
fbshipit-source-id: 9d2c39e74a5d11e0f90c8ad0d71b79424c56747f
| Python | unknown | phoad/rsocket-cpp,rsocket/rsocket-cpp,ReactiveSocket/reactivesocket-cpp,rsocket/rsocket-cpp,phoad/rsocket-cpp,ReactiveSocket/reactivesocket-cpp,phoad/rsocket-cpp,phoad/rsocket-cpp,rsocket/rsocket-cpp,rsocket/rsocket-cpp,phoad/rsocket-cpp,ReactiveSocket/reactivesocket-cpp |
3dc90a8173dd3520fd4f335efe9adb77b9167f80 | setup.py | setup.py | #! /usr/bin/env python3
from distutils.core import setup
setup(
description = 'File downloader for danbooru',
author = 'Todd Gaunt',
url = 'https://www.github.com/toddgaunt/danboorsync',
download_url = 'https://www.github.com/toddgaunt/danboorsync',
author_email = 'toddgaunt@protonmail.ch',
ver... | #! /usr/bin/env python3
from distutils.core import setup
setup(
description = 'File downloader for danbooru',
author = 'Todd Gaunt',
url = 'https://www.github.com/toddgaunt/danboorsync',
download_url = 'https://www.github.com/toddgaunt/danboorsync',
author_email = 'toddgaunt@protonmail.ch',
ver... | Fix data_files to install man and license documents | Setup: Fix data_files to install man and license documents
| Python | isc | toddgaunt/imgfetch |
f94bc30004aa9977bac652d337f69069efc132bd | marmoset/pxe/__init__.py | marmoset/pxe/__init__.py | from .label import Label
from .client_config import ClientConfig
def create(args):
pxe_client = ClientConfig(args.ip_address, args.password, args.script)
pxe_client.create(Label.find(args.label))
msg = 'Created %s with password %s'
print(msg % (pxe_client.file_path(), pxe_client.password))
def list(... | from .label import Label
from .client_config import ClientConfig
def create(args):
pxe_client = ClientConfig(args.ip_address, args.password, args.script)
used_options = pxe_client.create(Label.find(args.label))
msg = 'Created %s with following Options:'
print(msg % pxe_client.file_path())
for op... | Implement better result output for pxe config file crete | Implement better result output for pxe config file crete
| Python | agpl-3.0 | aibor/marmoset |
bfbc2bc38cbc7cbcd0afbb8d077fccf1925c0c16 | gaphor/SysML/blocks/grouping.py | gaphor/SysML/blocks/grouping.py | from gaphor.diagram.grouping import AbstractGroup, Group
from gaphor.SysML.blocks.block import BlockItem
from gaphor.SysML.blocks.property import PropertyItem
@Group.register(BlockItem, PropertyItem)
class NodeGroup(AbstractGroup):
"""
Add node to another node.
"""
def group(self):
self.paren... | from gaphor.diagram.grouping import AbstractGroup, Group
from gaphor.SysML.blocks.block import BlockItem
from gaphor.SysML.blocks.property import PropertyItem
@Group.register(BlockItem, PropertyItem)
class PropertyGroup(AbstractGroup):
"""
Add Property to a Block.
"""
def group(self):
self.pa... | Fix name for property/block group | Fix name for property/block group
| Python | lgpl-2.1 | amolenaar/gaphor,amolenaar/gaphor |
a48eb39dacba67b4c8638664c9df717837099c05 | genthreads/actor.py | genthreads/actor.py | from multiprocessing import process
class Actor(process.BaseProcess):
def __init__(self):
super(Actor, self).__init__()
self._inbox = list()
def send(self, value):
self._inbox.append(value)
@property
def inbox(self):
return self._inbox
| from multiprocessing import Process
class Actor(Process):
def __init__(self):
super(Actor, self).__init__()
self._inbox = list()
def send(self, value):
self._inbox.append(value)
@property
def inbox(self):
return self._inbox
| Change BaseProcess to Process as a parent class for Actor | Change BaseProcess to Process as a parent class for Actor
| Python | mit | f1sty/genthreads |
04f3003c8ac261edd862323624bbdba565b9e36c | download.py | download.py | # coding=utf-8
import urllib2
import json
import re
# album_url = 'http://www.ximalaya.com/7712455/album/6333174'
album_url = 'http://www.ximalaya.com/7712455/album/4474664'
headers = {'User-Agent': 'Safari/537.36'}
resp = urllib2.urlopen(urllib2.Request(album_url, headers=headers))
ids = re.search('sound_ids=\"(.*)\... | # coding=utf-8
import urllib2
import json
import re
# album_url = 'http://www.ximalaya.com/7712455/album/6333174'
album_url = 'http://www.ximalaya.com/7712455/album/4474664'
headers = {'User-Agent': 'Safari/537.36'}
resp = urllib2.urlopen(urllib2.Request(album_url, headers=headers))
ids = re.search('sound_ids=\"(.*)\... | Remove jsondata variable to simplify the code | Remove jsondata variable to simplify the code
| Python | mit | bangbangbear/ximalayaDownloader |
7d82f3accce0cf174fd7cf176d5c289ffc791647 | ds_queue.py | ds_queue.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
class Queue(object):
"""Queue class."""
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0, i... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
class Queue(object):
"""Queue class."""
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def peek(self):
return self.items[-1]
def ... | Revise Queue instance to q | Revise Queue instance to q
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
2916006bf7dc9a689a9ab5678d37a858d380345e | api/migrations/0002_migrate_legacy.py | api/migrations/0002_migrate_legacy.py | from django.apps import apps as global_apps
from django.db import migrations
from django.db.utils import OperationalError
sql = '''
'''
reverse_sql = '''
'''
def forwards(app, schema_editor):
models = app.all_models['api']
try:
schema_editor.execute('alter table south_migrationhistory rename to lega... | from django.apps import apps as global_apps
from django.db import migrations
from django.db.utils import OperationalError
from django.db.backends.postgresql.schema import DatabaseSchemaEditor as PgSE
sql = '''
'''
reverse_sql = '''
'''
def forwards(app, schema_editor):
models = app.all_models['api']
if no... | Update migration to check for Postgres as target | Update migration to check for Postgres as target
| Python | bsd-2-clause | chop-dbhi/biorepo-portal,chop-dbhi/biorepo-portal,chop-dbhi/biorepo-portal,chop-dbhi/biorepo-portal |
f94347a734df84811b627e767a55dc99831e0076 | src/models.py | src/models.py | from flask_sqlalchemy import Model
from sqlalchemy import Column, Integer, Unicode, UnicodeText, ForeignKey
from sqlalchemy.orm import relationship
class User(Model):
__tablename__ = "user"
ROLE_ADMIN = 0
ROLE_USER = 1
id = Column(Integer, primary_key=True)
name = Column(Unicode(64), index=True)
... | from flask_sqlalchemy import Model
from __init__ import db
class User(Model):
__tablename__ = "user"
ROLE_ADMIN = 0
ROLE_USER = 1
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode(64), index=True)
username = db.Column(db.Unicode(20), index=True)
password_hash = db.Co... | Use local database namespace instead of package. | Use local database namespace instead of package.
| Python | mit | BrambleLLC/Artizanz,BrambleLLC/Artizanz,BrambleLLC/Artizanz |
12bb9882c1e2cc3f04b7bef30d4aaf8267793622 | opps/images/tests/__init__.py | opps/images/tests/__init__.py | # -*- coding: utf-8 -*-
from opps.images.tests.generate import *
| # -*- coding: utf-8 -*-
from opps.images.tests.generate import *
from opps.images.tests.test_models import *
| Add test_models on image test init | Add test_models on image test init
| Python | mit | williamroot/opps,williamroot/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,opps/opps,opps/opps,YACOWS/opps,opps/opps,opps/opps,YACOWS/opps |
7606689e5d83a6c3bfa71ede25e4b92978d94bd4 | hdbscan/__init__.py | hdbscan/__init__.py | from .hdbscan_ import HDBSCAN, hdbscan
from .robust_single_linkage_ import RobustSingleLinkage, robust_single_linkage
| from .hdbscan_ import HDBSCAN, hdbscan
from .robust_single_linkage_ import RobustSingleLinkage, robust_single_linkage
from .validity import validity_index
| Add validity_index to default imports. | Add validity_index to default imports.
| Python | bsd-3-clause | scikit-learn-contrib/hdbscan,scikit-learn-contrib/hdbscan,lmcinnes/hdbscan,lmcinnes/hdbscan |
f8b52162748ccf62db881fad101e6a91ed014bd4 | plugins/Hitman_Codename_47.py | plugins/Hitman_Codename_47.py | import os
from lib.base_plugin import BasePlugin
from lib.paths import SteamGamesPath
class HitmanCodename47Plugin(BasePlugin):
Name = "Hitman: Codename 47"
support_os = ["Windows"]
def backup(self, _):
_.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')
def... | import os
from lib.base_plugin import BasePlugin
from lib.paths import SteamGamesPath
class HitmanCodename47Plugin(BasePlugin):
Name = "Hitman: Codename 47"
support_os = ["Windows"]
def backup(self, _):
_.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')
... | Add backuping config files for Hitman: Codename 47 | Add backuping config files for Hitman: Codename 47
| Python | mit | Pr0Ger/SGSB |
85542282162158e9e3d0ff339ee67d7809fb2a3c | src/models.py | src/models.py | from sqlalchemy import create_engine, Column, Float, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.engine.url import URL
import settings
DeclarativeBase = declarative_base()
def db_connect():
"""
Performs database connection using database settings from settings.py.
... | from sqlalchemy import create_engine, Column, Float, Integer, String
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.engine.url import URL
import settings
DeclarativeBase = declarative_base()
def db_connect():
"""
Performs database conn... | Add model for storing words. | Add model for storing words.
| Python | mit | piatra/ssl-project |
f9f65019230f8c694a61053d571093cd87db4950 | setup.py | setup.py | from distutils.core import setup
setup(
name = 'gdaxcli',
packages = ['gdaxcli'],
version = '0.1',
description = 'Commandline client for trading on GDAX',
author = 'Son Pham',
author_email = 'sp@sonpham.me',
url = 'https://github.com/sonph/gdaxcli',
download_url = 'https://github.com/son... | from distutils.core import setup
setup(
name = 'gdaxcli',
packages = ['gdaxcli'],
version = '0.1',
description = 'Commandline client for trading on GDAX',
author = 'Son Pham',
author_email = 'sp@sonpham.me',
url = 'https://github.com/sonph/gdaxcli',
download_url = 'https://github.com/son... | Add instructions for uploading to pypitest | Add instructions for uploading to pypitest
| Python | mit | sonph/gdaxcli,sonph/gdaxcli |
542ab347d5a0195c88be212d966253d4385b8af5 | api.py | api.py | import webapp2
from google.appengine.api import channel
from google.appengine.api import users
open_channels = set()
class ChannelDidConnect(webapp2.RequestHandler):
def post(self):
print "Got connection"
open_channels.add(self.request.get("from"))
class ChannelDisconnect(webapp2.RequestHandler... | import webapp2
from google.appengine.api import channel
from google.appengine.api import users
open_channels = set()
class ChannelDidConnect(webapp2.RequestHandler):
def post(self):
print "Got connection"
open_channels.add(self.request.get("from"))
class ChannelDisconnect(webapp2.RequestHandler... | Allow messages to come in through GET | Allow messages to come in through GET
| Python | mit | misterwilliam/gae-channels-sample,misterwilliam/gae-channels-sample,misterwilliam/gae-channels-sample |
c69b7b80c75e170f1b83d1204fb531544a9fc831 | rpifake/__init__.py | rpifake/__init__.py | # After this function, any futher calls to import RPi.GPIO
# will instead import .gpio.Gpio instead
def patch_fake_gpio():
print('Warning, not in RPi, using mock GPIO')
# Idea taken from RPLCD who commented it as being from:
# reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio
import mock
from... | # After this function, any futher calls to import RPi.GPIO
# will instead import .gpio.Gpio instead
def patch_fake_gpio():
import sys
import mock
from .gpio import Gpio as FakeGpio
MockRPi = mock.MagicMock()
MockRPi.GPIO = FakeGpio()
modules = {
'RPi': MockRPi,
'RPi.GPIO': MockRP... | Make override more global, not just within patch scope | Make override more global, not just within patch scope
| Python | mit | rfarley3/lcd-restful,rfarley3/lcd-restful |
9a2e56c5721fad4df75339feac6676897f40ac01 | src/tpn/data_io.py | src/tpn/data_io.py | #!/usr/bin/env python
import zipfile
import cPickle
import numpy as np
"""
track_obj: {
frames: 1 by n numpy array,
anchors: 1 by n numpy array,
features: m by n numpy array,
scores: c by n numpy array,
boxes: 4 by n numpy array,
rois: 4 by n numpy array
}
"""
d... | #!/usr/bin/env python
import zipfile
import cPickle
import numpy as np
"""
track_obj: {
frames: 1 by n numpy array,
anchors: 1 by n numpy array,
features: m by n numpy array,
scores: c by n numpy array,
boxes: 4 by n numpy array,
rois: 4 by n numpy array
}
"""
d... | Enable zip64 to store tracks larger than 2GB. | Enable zip64 to store tracks larger than 2GB.
| Python | mit | myfavouritekk/TPN |
59d44ba76a9b2f98375fa2f893dabc0376de6f82 | localeurl/models.py | localeurl/models.py | from django.conf import settings
from django.core import urlresolvers
from django.utils import translation
from localeurl import utils
def reverse(*args, **kwargs):
reverse_kwargs = kwargs.get('kwargs') or {}
locale = utils.supported_language(reverse_kwargs.pop(
'locale', translation.get_language()... | from django.conf import settings
from django.core import urlresolvers
from django.utils import translation
from django.contrib.auth import views as auth_views
from localeurl import utils
def reverse(*args, **kwargs):
reverse_kwargs = kwargs.get('kwargs') or {}
locale = utils.supported_language(reverse_kwargs.... | Patch redirect_to_login to maintain locale | Patch redirect_to_login to maintain locale
Signed-off-by: Simon Luijk <088e16a1019277b15d58faf0541e11910eb756f6@simonluijk.com>
| Python | mit | simonluijk/django-localeurl |
7cd3cc1a6a023a093c9c6d8df4dd1b9d6c871faa | auto/src/rabird/auto/mouse_xdotool.py | auto/src/rabird/auto/mouse_xdotool.py | '''
@date 2015-02-21
@author Hong-She Liang <starofrainnight@gmail.com>
'''
import os
import re
import subprocess
from .mouse_constant import *
class Mouse(object):
## return current mouse absolute position
@classmethod
def position(cls):
p = subprocess.Popen(["xdotool", "getmouselocation"], stdou... | '''
@date 2015-02-21
@author Hong-She Liang <starofrainnight@gmail.com>
'''
import os
import re
import subprocess
from .mouse_constant import *
class Mouse(object):
## return current mouse absolute position
@classmethod
def position(cls):
output = subprocess.check_output(["xdotool", "getmouselocat... | Convert all os.system() to subprocess.check_output(). | Convert all os.system() to subprocess.check_output().
| Python | apache-2.0 | starofrainnight/rabird.core,starofrainnight/rabird.auto |
ad069a50ec7a4b4e6b1dac679e071279e128c824 | been/source/markdowndirectory.py | been/source/markdowndirectory.py | from been.core import DirectorySource, source_registry
from hashlib import sha1
import re
import unicodedata
import time
import markdown
# slugify from Django source (BSD license)
def slugify(value):
value = unicodedata.normalize('NFKD', unicode(value)).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-... | from been.core import DirectorySource, source_registry
from hashlib import sha1
import re
import unicodedata
import time
import markdown
# slugify from Django source (BSD license)
def slugify(value):
value = unicodedata.normalize('NFKD', unicode(value)).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-... | Allow MarkdownDirectory events to specify author. | Allow MarkdownDirectory events to specify author.
| Python | bsd-3-clause | chromakode/been |
f286dc748670c67845df226ca7d400e745dd502f | awx/main/notifications/email_backend.py | awx/main/notifications/email_backend.py | # Copyright (c) 2016 Ansible, Inc.
# All Rights Reserved.
import pprint
from django.utils.encoding import smart_text
from django.core.mail.backends.smtp import EmailBackend
class CustomEmailBackend(EmailBackend):
init_parameters = {"host": {"label": "Host", "type": "string"},
"port": {"la... | # Copyright (c) 2016 Ansible, Inc.
# All Rights Reserved.
import pprint
from django.utils.encoding import smart_text
from django.core.mail.backends.smtp import EmailBackend
class CustomEmailBackend(EmailBackend):
init_parameters = {"host": {"label": "Host", "type": "string"},
"port": {"la... | Fix an issue with the email notifier | Fix an issue with the email notifier
Incorrect body format assumptions in the email notifier
| Python | apache-2.0 | wwitzel3/awx,snahelou/awx,wwitzel3/awx,wwitzel3/awx,snahelou/awx,snahelou/awx,snahelou/awx,wwitzel3/awx |
ae1c6c020225423bcfaff5b3c830345467d87b2d | tedx/views.py | tedx/views.py | from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import RegistrationForm
from .models import Registration
import utils
def handle_registration(request):
if request.method == 'POST':
form = RegistrationForm(request.POST... | from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseRedirect
from django.shortcuts import render
from clubs.models import Team
from .forms import RegistrationForm
from .models import Registration
import utils
def handle_regis... | Add permission check for TEDx | Add permission check for TEDx
| Python | agpl-3.0 | osamak/student-portal,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz,enjaz/enjaz,enjaz/enjaz |
a47ab820870caebcc00daf32531cfad3abd2e532 | src/engine/SCons/Platform/darwin.py | src/engine/SCons/Platform/darwin.py | """engine.SCons.Platform.darwin
Platform-specific initialization for Mac OS X systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004 Steven Knight
#
# Permi... | """engine.SCons.Platform.darwin
Platform-specific initialization for Mac OS X systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of char... | Fix __COPYRIGHT__ and __REVISION__ in new Darwin module. | Fix __COPYRIGHT__ and __REVISION__ in new Darwin module.
| Python | mit | andrewyoung1991/scons,timj/scons,timj/scons,andrewyoung1991/scons,andrewyoung1991/scons,timj/scons,andrewyoung1991/scons,timj/scons,andrewyoung1991/scons,timj/scons,andrewyoung1991/scons,timj/scons,andrewyoung1991/scons,andrewyoung1991/scons,timj/scons,timj/scons,andrewyoung1991/scons,timj/scons |
a2430b67423ce036d2a96541e86d356ace04db69 | Twitch/cogs/words.py | Twitch/cogs/words.py |
from twitchio.ext import commands
@commands.cog()
class Words:
def __init__(self, bot):
self.bot = bot
@commands.command()
async def audiodefine(self, ctx, word):
url = f"http://api.wordnik.com:80/v4/word.json/{word}/audio"
params = {"useCanonical": "false", "limit": 1, "api_key": self.bot.WORDNIK_API_KE... |
from twitchio.ext import commands
@commands.cog()
class Words:
def __init__(self, bot):
self.bot = bot
@commands.command()
async def audiodefine(self, ctx, word):
url = f"http://api.wordnik.com:80/v4/word.json/{word}/audio"
params = {"useCanonical": "false", "limit": 1, "api_key": self.bot.WORDNIK_API_KE... | Use f-string for define command | [TwitchIO] Use f-string for define command
| Python | mit | Harmon758/Harmonbot,Harmon758/Harmonbot |
7be606951b22d77a53274d014cd94aae30af93f5 | samples/oauth2_for_devices.py | samples/oauth2_for_devices.py | # -*- coding: utf-8 -*-
# See: https://developers.google.com/accounts/docs/OAuth2ForDevices
import httplib2
from six.moves import input
from oauth2client.client import OAuth2WebServerFlow
from googleapiclient.discovery import build
CLIENT_ID = "some+client+id"
CLIENT_SECRET = "some+client+secret"
SCOPES = ("https:/... | # -*- coding: utf-8 -*-
# See: https://developers.google.com/accounts/docs/OAuth2ForDevices
import httplib2
from six.moves import input
from oauth2client.client import OAuth2WebServerFlow
from googleapiclient.discovery import build
CLIENT_ID = "some+client+id"
CLIENT_SECRET = "some+client+secret"
SCOPES = ("https:/... | Fix example to be Python3 compatible, use format() | Fix example to be Python3 compatible, use format()
Both print() and format() are compatible from 2.6. Also, format() is much nicer to use for internationalization since you can define the location of your substitutions. It works similarly to Java and .net's format() as well. Great stuff!
Should I tackle the other e... | Python | apache-2.0 | googleapis/oauth2client,jonparrott/oauth2client,google/oauth2client,jonparrott/oauth2client,clancychilds/oauth2client,googleapis/oauth2client,google/oauth2client,clancychilds/oauth2client |
033ee318e6694ca4b251adf759d8cb62a100fdca | tickertape.py | tickertape.py | #!/usr/bin/env python
"""Display stock quotes on LEDs."""
import RPi.GPIO as GPIO
from seven_segment import print_leds
from ystockquote import get_price, get_change
pins = [17, 23, 24, 22, 27, 25, 5]
GPIO.setmode(GPIO.BCM)
GPIO.setup(pins, GPIO.OUT)
print_leds(' ')
symbols = ['AAPL', 'MSFT', 'F', 'T', 'KO', 'GOOG'... | #!/usr/bin/env python
"""Display stock quotes on LEDs."""
import RPi.GPIO as GPIO
from seven_segment import print_leds
from ystockquote import get_price, get_change
pins = [17, 23, 24, 22, 27, 25, 5]
GPIO.setmode(GPIO.BCM)
GPIO.setup(pins, GPIO.OUT)
print_leds(' ', pins)
symbols = ['AAPL', 'MSFT', 'F', 'T', 'KO', ... | Improve ctrl-c handling. Fix the clear-display line. | Improve ctrl-c handling. Fix the clear-display line.
| Python | mit | zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie |
18b4d5196fe18479e4aedfaa9030e5ba443d6a85 | test_input/test70.py | test_input/test70.py | 'test checking constant conditions'
# __pychecker__ = ''
def func1(x):
'should not produce a warning'
if 1:
pass
while 1:
print x
break
assert x, 'test'
return 0
def func2(x):
'should produce a warning'
__pychecker__ = 'constant1'
if 1:
pass
while 1... | 'test checking constant conditions'
# __pychecker__ = ''
def func1(x):
'should not produce a warning'
if 1:
pass
while 1:
print x
break
assert x, 'test'
return 0
def func2(x):
'should produce a warning'
__pychecker__ = 'constant1'
if 1:
pass
while 1... | Fix a problem reported by Greg Ward and pointed out by John Machin when doing: | Fix a problem reported by Greg Ward and pointed out by John Machin when doing:
return (need_quotes) and ('"%s"' % text) or (text)
The following warning was generated:
Using a conditional statement with a constant value ("%s")
This was because even the stack wasn't modified after a BINARY_MODULO
to s... | Python | bsd-3-clause | mitar/pychecker,mitar/pychecker |
1f7f058d97c6599401558a280d85affed7fb5394 | testing/hdiv_proj.py | testing/hdiv_proj.py | from __future__ import absolute_import, print_function, division
from firedrake import *
mesh = UnitSquareMesh(2, 2)
RT = FiniteElement("RT", triangle, 1)
V = FunctionSpace(mesh, RT)
u = TrialFunction(V)
v = TestFunction(V)
f = Function(V)
x = SpatialCoordinate(mesh)
f.project(as_vector([x[1], x[0]]))
r = Function(... | from __future__ import absolute_import, print_function, division
from firedrake import *
mesh = UnitSquareMesh(2, 2)
RT = FiniteElement("RT", triangle, 1)
V = FunctionSpace(mesh, RT)
u = TrialFunction(V)
v = TestFunction(V)
f = Function(V)
x = SpatialCoordinate(mesh)
assemble(42*dot(v, FacetNormal(mesh))*ds, tensor=... | Update projection experiment for HDiv functions | Update projection experiment for HDiv functions
| Python | mit | thomasgibson/firedrake-hybridization |
b172ee1c1ed76836e570e08f0624a456c07cc388 | get_max_audio.py | get_max_audio.py | """
Test obtaining peak audio values with PyAV:
time python pyav_audio_vol.py ~/Videos/sample.mp4
Reference:
https://ffmpeg.org/doxygen/trunk/group__lavu__sampfmts.html
"""
import sys
import av
import numpy as np
# import matplotlib.pyplot as plt
video_file = sys.argv[1]
container = av.open(video_file)
audioStream... | """
Test obtaining peak audio values with PyAV:
time python pyav_audio_vol.py ~/Videos/sample.mp4
Reference:
https://ffmpeg.org/doxygen/trunk/group__lavu__sampfmts.html
"""
import sys
import av
import numpy as np
import matplotlib.pyplot as plt
video_file = sys.argv[1]
container = av.open(video_file)
audioStream =... | Use RMS for better filtering | Use RMS for better filtering | Python | bsd-2-clause | yan123/BitBox,yan123/QABox,yan123/QABox |
0d90da8fca411033d66c3a82096a67e12fca830e | util/time_multi.py | util/time_multi.py | #!/usr/bin/python
#
# Small helper for perftest runs.
#
import os
import sys
import subprocess
def main():
count = int(sys.argv[1])
time_min = None
for i in xrange(count):
cmd = [
'time',
'-f', '%U',
'--quiet',
sys.argv[2], # cmd
sys.argv[3] # testcase
]
#print(repr(cmd))
p = subproce... | #!/usr/bin/python
#
# Small helper for perftest runs.
#
import os
import sys
import subprocess
def main():
count = int(sys.argv[1])
time_min = None
for i in xrange(count):
cmd = [
'time',
'-f', '%U',
'--quiet',
sys.argv[2], # cmd
sys.argv[3] # testcase
]
#print(repr(cmd))
p = subproce... | Add exitcode and segv check for timing util | Add exitcode and segv check for timing util
| Python | mit | reqshark/duktape,jmptrader/duktape,harold-b/duktape,chenyaqiuqiu/duktape,harold-b/duktape,nivertech/duktape,zeropool/duktape,harold-b/duktape,zeropool/duktape,harold-b/duktape,chenyaqiuqiu/duktape,jmptrader/duktape,harold-b/duktape,chenyaqiuqiu/duktape,kphillisjr/duktape,skomski/duktape,nivertech/duktape,skomski/duktap... |
3d7459f7b1d40bb94a64d3f08d41942feabf4c12 | manager/jobs/migrations/0003_auto_20200723_0219.py | manager/jobs/migrations/0003_auto_20200723_0219.py | # Generated by Django 3.0.8 on 2020-07-23 02:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('jobs', '0002_auto_20200708_2203'),
]
operations = [
migrations.AlterField(
model_name='job',
name='id',
... | # Generated by Django 3.0.8 on 2020-07-23 02:19.
# Manually modified by Nokome Bentley on 2020-11-09 because the original
# `AlterField` operation was causing the following error on Postgres:
# django.db.utils.ProgrammingError: operator class "varchar_pattern_ops" does not accept data type bigint
# In production, tha... | Allow migration to run on Postgres | chore(Jobs): Allow migration to run on Postgres
| Python | apache-2.0 | stencila/hub,stencila/hub,stencila/hub,stencila/hub,stencila/hub |
5b8edee2b6fa13fc1b05e15961d8b7920e6f9739 | csunplugged/general/urls.py | csunplugged/general/urls.py | """URL routing for the general application."""
from django.conf.urls import url
from . import views
urlpatterns = [
url(r"^$", views.GeneralIndexView.as_view(), name="home"),
url(r"^about/$", views.GeneralAboutView.as_view(), name="about"),
url(r"^computational-thinking/$", views.ComputationalThinkingVie... | """URL routing for the general application."""
from django.conf.urls import url
from . import views
urlpatterns = [
url(
r"^$",
views.GeneralIndexView.as_view(),
name="home"
),
url(
r"^about/$",
views.GeneralAboutView.as_view(),
name="about"
),
url(... | Update URLs file to match layout of other URLs files | Update URLs file to match layout of other URLs files
| Python | mit | uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged |
48d18015b2cf55638cc7bda43ae3751789fa2323 | games/management/commands/autocreate_steamdb_installers.py | games/management/commands/autocreate_steamdb_installers.py | import json
from django.core.management.base import BaseCommand
from games import models
from accounts.models import User
class Command(BaseCommand):
def handle(self, *args, **options):
with open("steamdb.json") as steamdb_file:
steamdb = json.loads(steamdb_file.read())
steam_runner = ... | import json
from django.core.management.base import BaseCommand
from games import models
from accounts.models import User
class Command(BaseCommand):
def handle(self, *args, **options):
with open("steamdb.json") as steamdb_file:
steamdb = json.loads(steamdb_file.read())
steam_runner = ... | Update installer autocreate for games with no icon | Update installer autocreate for games with no icon
| Python | agpl-3.0 | lutris/website,lutris/website,lutris/website,Turupawn/website,Turupawn/website,Turupawn/website,Turupawn/website,lutris/website |
0c89a78d3a0574ef491d3695366cd786b4c3f950 | indico/migrations/versions/20200904_1543_f37d509e221c_add_user_profile_picture_column.py | indico/migrations/versions/20200904_1543_f37d509e221c_add_user_profile_picture_column.py | """Add column for profile picture type to User
Revision ID: f37d509e221c
Revises: c997dc927fbc
Create Date: 2020-09-04 15:43:18.413156
"""
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum
from indico.modules.users.models.users import ProfilePictureSource
# revision ide... | """Add column for profile picture type to User
Revision ID: f37d509e221c
Revises: c997dc927fbc
Create Date: 2020-09-04 15:43:18.413156
"""
from enum import Enum
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum
# revision identifiers, used by Alembic.
revision = 'f37d5... | Use embedded enum in alembic revision | Use embedded enum in alembic revision
Unlikely to matter here but like this it will work correctly even in a
future where someone may add new sources to the original enum (in that
case this particular revision should not add those newer ones, which
would be the case when using the imported enum)
| Python | mit | DirkHoffmann/indico,indico/indico,DirkHoffmann/indico,ThiefMaster/indico,indico/indico,indico/indico,pferreir/indico,ThiefMaster/indico,pferreir/indico,pferreir/indico,pferreir/indico,indico/indico,ThiefMaster/indico,DirkHoffmann/indico,DirkHoffmann/indico,ThiefMaster/indico |
75fc7888cf4db89ae55324b325afc44452799cb3 | filesystems/interfaces.py | filesystems/interfaces.py | from zope.interface import Interface
from filesystems import _PY3
class Path(Interface):
def __str__():
"""
Render the path as a string.
"""
if _PY3:
def __truediv__(other):
"""
Traverse to a child of this path.
"""
def __fspath__(... | from zope.interface import Interface
from filesystems import _PY3
class Path(Interface):
def __str__():
"""
Render the path as a string.
"""
if _PY3:
def __fspath__():
"""
Render the path as a string.
"""
def __truediv__(other):
... | Fix the fspath interface and div docstring. | Fix the fspath interface and div docstring.
| Python | mit | Julian/Filesystems |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.