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 |
|---|---|---|---|---|---|---|---|---|---|
213b889a580f58f5dea13fa63c999ca7dac04450 | src/extras/__init__.py | src/extras/__init__.py | __author__ = 's7a'
# All imports
from logger import Logger
from sanitizer import Sanitizer
from kucera_francis import KuceraFrancis | __author__ = 's7a'
# All imports
from logger import Logger
from sanitizer import Sanitizer
from kucera_francis import KuceraFrancis
from stemmed_kucera_francis import StemmedKuceraFrancis | Add Stemmed Kucera Francis to extras package | Add Stemmed Kucera Francis to extras package
| Python | mit | Somsubhra/Simplify,Somsubhra/Simplify,Somsubhra/Simplify |
06349ea257219e8ad1808fa4fd77f34f7371894a | test/test.py | test/test.py | import os, shutil
from nose import with_setup
from mbutil import mbtiles_to_disk, disk_to_mbtiles
def clear_data():
try: shutil.rmtree('test/output')
except Exception: pass
try: os.path.mkdir('test/output')
except Exception: pass
@with_setup(clear_data, clear_data)
def test_mbtiles_to_disk():
mbt... | import os, shutil
from nose import with_setup
from mbutil import mbtiles_to_disk, disk_to_mbtiles
def clear_data():
try: shutil.rmtree('test/output')
except Exception: pass
@with_setup(clear_data, clear_data)
def test_mbtiles_to_disk():
mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output')
asse... | Remove dead code, os.path.mkdir does not even exist | Remove dead code, os.path.mkdir does not even exist
| Python | bsd-3-clause | davvo/mbutil-eniro,mapbox/mbutil,mapbox/mbutil |
d91b8f96290498f1e36d64bd797fcea5e43d3df1 | apps/events/api.py | apps/events/api.py | from tastypie.resources import ModelResource
from models import Event
class EventResource(ModelResource):
class Meta:
queryset = Event.objects.all()
resource_name = 'events'
| from copy import copy
from tastypie.resources import ModelResource
from models import Event
class EventResource(ModelResource):
def alter_list_data_to_serialize(self, request, data):
# Rename list data object to 'events'.
if isinstance(data, dict):
data['events'] = copy(data['objects']... | Rename data objects to 'events' | Rename data objects to 'events'
| Python | mit | dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4 |
0ce7a7b396dd62c7e52e355108f8f037335bc5ca | src/sentry/api/endpoints/project_environments.py | src/sentry/api/endpoints/project_environments.py | from __future__ import absolute_import
from rest_framework.response import Response
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.serializers import serialize
from sentry.models import EnvironmentProject
environment_visibility_filter_options = {
'all': lambda queryset: queryset,
'hidd... | from __future__ import absolute_import
from rest_framework.response import Response
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.serializers import serialize
from sentry.models import EnvironmentProject
environment_visibility_filter_options = {
'all': lambda queryset: queryset,
'hidd... | Hide "No Environment" environment from project environments | api: Hide "No Environment" environment from project environments
| Python | bsd-3-clause | beeftornado/sentry,beeftornado/sentry,mvaled/sentry,ifduyue/sentry,ifduyue/sentry,mvaled/sentry,mvaled/sentry,beeftornado/sentry,mvaled/sentry,looker/sentry,looker/sentry,looker/sentry,ifduyue/sentry,ifduyue/sentry,mvaled/sentry,looker/sentry,mvaled/sentry,ifduyue/sentry,looker/sentry |
e652e57be097949d06acd06cef813fd28a45afc2 | base_report_auto_create_qweb/__manifest__.py | base_report_auto_create_qweb/__manifest__.py | # -*- coding: utf-8 -*-
# Authors: See README.RST for Contributors
# Copyright 2015-2016 See __openerp__.py for Authors
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Report qweb auto generation",
"version": "9.0.1.0.0",
"depends": [
"report",
],
"external_d... | # -*- coding: utf-8 -*-
# Authors: See README.RST for Contributors
# Copyright 2015-2016 See __openerp__.py for Authors
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Report qweb auto generation",
"version": "9.0.1.0.0",
"depends": [
"report",
],
"external_d... | Change authors to new ones | base_report_auto_create_qweb: Change authors to new ones
| Python | agpl-3.0 | ovnicraft/server-tools,ovnicraft/server-tools,ovnicraft/server-tools |
c94be38207dc9ec0cdf9c3d406954a249ff6e6ac | awsume/awsumepy/lib/saml.py | awsume/awsumepy/lib/saml.py | import base64
import xmltodict
import json
import colorama
from . safe_print import safe_print
from . exceptions import SAMLAssertionParseError
def parse_assertion(assertion: str) -> list:
roles = []
response = xmltodict.parse(base64.b64decode(assertion))
if response.get('saml2p:Response') is not None:
... | import base64
import xmltodict
import json
import colorama
from . safe_print import safe_print
from . exceptions import SAMLAssertionParseError
def parse_assertion(assertion: str) -> list:
roles = []
response = xmltodict.parse(base64.b64decode(assertion))
if response.get('saml2p:Response') is not None:
... | Handle having a single role in the SAML assertion | Handle having a single role in the SAML assertion
| Python | mit | trek10inc/awsume,trek10inc/awsume |
79ee512bb989056c521e3e38d9d8a52c2bd3d3fc | tests/__init__.py | tests/__init__.py | # -*- coding: utf8 -*-
import sys
import os
import libcrowds_statistics as plugin
# Use the PyBossa test suite
sys.path.append(os.path.abspath("./pybossa/test"))
os.environ['STATISTICS_SETTINGS'] = '../settings_test.py'
def setUpPackage():
"""Setup the plugin."""
from default import flask_app
with flas... | # -*- coding: utf8 -*-
import sys
import os
import libcrowds_statistics as plugin
# Use the PyBossa test suite
sys.path.append(os.path.abspath("./pybossa/test"))
os.environ['STATISTICS_SETTINGS'] = '../settings_test.py'
def setUpPackage():
"""Setup the plugin."""
from default import flask_app
with flas... | Remove duplicate setting of config variable | Remove duplicate setting of config variable
| Python | bsd-3-clause | LibCrowds/libcrowds-statistics,LibCrowds/libcrowds-statistics,LibCrowds/libcrowds-statistics |
27668d5e5c1c40b342ca4d280ed3aaa49532c845 | email-ping.py | email-ping.py | import smtplib
import time
from email.mime.text import MIMEText
to_list = ('',) # add recipient (your remote account) here
from_email = '' # email from which the e-mail is sent; must be accepted by SMTP
s = smtplib.SMTP('') # SMTP address
s.login('', '') # ('smtp login', 'smtp password')
for to in to_list:
m... | #!/usr/bin/python
import smtplib
import time
from email.mime.text import MIMEText
to_list = ('',) # add recipient (your remote account) here
from_email = '' # email from which the e-mail is sent; must be accepted by SMTP
s = smtplib.SMTP_SSL('') # SMTP address
s.login('', '') # ('smtp login', 'smtp password')
fo... | Update email_ping.py with header and SSL default | Update email_ping.py with header and SSL default | Python | mit | krzysztofr/gmail-force-check |
72b0ed654749bdd01989567a5eee2234cb8328ce | registration/admin.py | registration/admin.py | from django.contrib import admin
from registration.models import RegistrationProfile
class RegistrationAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'activation_key_expired')
search_fields = ('user__username', 'user__first_name')
admin.site.register(RegistrationProfile, RegistrationAdmin)
| from django.contrib import admin
from registration.models import RegistrationProfile
class RegistrationAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'activation_key_expired')
raw_id_fields = ['user']
search_fields = ('user__username', 'user__first_name')
admin.site.register(RegistrationProfil... | Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users. | Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.
| Python | bsd-3-clause | lubosz/django-registration,lubosz/django-registration |
bc9656c1ced31f0592b6d73a0678386843afa5b5 | db/migrations/migration5.py | db/migrations/migration5.py | import sqlite3
def migrate(database_path):
print "migrating to db version 5"
conn = sqlite3.connect(database_path)
conn.text_factory = str
cursor = conn.cursor()
# update settings table to include smtp server settings
cursor.execute('''ALTER TABLE sales ADD COLUMN "unread" INTEGER''')
curs... | import sqlite3
def migrate(database_path):
print "migrating to db version 5"
conn = sqlite3.connect(database_path)
conn.text_factory = str
cursor = conn.cursor()
# update settings table to include smtp server settings
cursor.execute('''ALTER TABLE sales ADD COLUMN "unread" INTEGER''')
cur... | Initialize unread column to 0 | Initialize unread column to 0
| Python | mit | tyler-smith/OpenBazaar-Server,tyler-smith/OpenBazaar-Server,OpenBazaar/OpenBazaar-Server,cpacia/OpenBazaar-Server,cpacia/OpenBazaar-Server,tyler-smith/OpenBazaar-Server,OpenBazaar/Network,OpenBazaar/OpenBazaar-Server,OpenBazaar/Network,saltduck/OpenBazaar-Server,OpenBazaar/Network,tomgalloway/OpenBazaar-Server,cpacia/O... |
1abf1add68f9a1224fe5f754b0f01a86dbb1008c | maras/nestdb.py | maras/nestdb.py | '''
Create a stock database with a built in nesting key index
'''
# Import maras libs
import maras.database
import maras.tree_index
# We can likely build these out as mixins, making it easy to apply high level
# constructs to multiple unerlying database implimentations
class NestDB(maras.database.Database):
'''
... | '''
Create a stock database with a built in nesting key index
'''
# Import maras libs
import maras.database
import maras.tree_index
# We can likely build these out as mixins, making it easy to apply high level
# constructs to multiple unerlying database implimentations
class NestDB(maras.database.Database):
'''
... | Clean out the _key from the data, no need to double entry | Clean out the _key from the data, no need to double entry
| Python | apache-2.0 | thatch45/maras_old |
a2713927beb4b80ba62cc0273df24d33cca4a689 | namuhub/__init__.py | namuhub/__init__.py | """namuhub --- namu.wiki contribution graph"""
from flask import Flask, jsonify, render_template, request, url_for
app = Flask('namuhub')
@app.route('/', methods=['GET'])
def index():
return render_template('index.html')
@app.route('/<user>', methods=['GET'])
def index_user(user=''):
return render_template('... | """namuhub --- namu.wiki contribution graph"""
import time
from collections import defaultdict
from datetime import timedelta
from flask import Flask, jsonify, render_template, request, url_for
from namuhub import namu as namuwiki
app = Flask('namuhub')
@app.route('/', methods=['GET'])
def index():
return rende... | Return namu.wiki contribution data as JSON | Return namu.wiki contribution data as JSON
| Python | apache-2.0 | ssut/namuhub,ssut/namuhub,ssut/namuhub |
f3978f2bee9fdbef4e2d415e4a6e584e451f4da4 | nbtutor/__init__.py | nbtutor/__init__.py | # -*- coding: utf-8 -*-
"""
nbtutor - a small utility to indicate which cells should be cleared (exercises).
"""
import os
try:
from nbconvert.preprocessors.base import Preprocessor
except ImportError:
from IPython.nbconvert.preprocessors.base import Preprocessor
from traitlets import Unicode
class ClearEx... | # -*- coding: utf-8 -*-
"""
nbtutor - a small utility to indicate which cells should be cleared (exercises).
"""
import os
try:
from nbconvert.preprocessors.base import Preprocessor
except ImportError:
from IPython.nbconvert.preprocessors.base import Preprocessor
from traitlets import Unicode
class ClearEx... | Update to use tags instead of custom metadata | Update to use tags instead of custom metadata
| Python | bsd-2-clause | jorisvandenbossche/nbtutor,jorisvandenbossche/nbtutor |
89422fb5aaa10a99b3d9d0e576551fdd4d111a27 | tests/registryd/test_registry_startup.py | tests/registryd/test_registry_startup.py | PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties'
ACCESSIBLE_IFACE = 'org.a11y.atspi.Accessible'
def get_property(proxy, iface_name, prop_name):
return proxy.Get(iface_name, prop_name, dbus_interface=PROPERTIES_IFACE)
def test_accessible_iface_properties(registry, session_manager):
values = [
('Nam... | PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties'
ACCESSIBLE_IFACE = 'org.a11y.atspi.Accessible'
def get_property(proxy, iface_name, prop_name):
return proxy.Get(iface_name, prop_name, dbus_interface=PROPERTIES_IFACE)
def test_accessible_iface_properties(registry, session_manager):
values = [
('Nam... | Test ChildCount on an empty registry | Test ChildCount on an empty registry
| Python | lgpl-2.1 | GNOME/at-spi2-core,GNOME/at-spi2-core,GNOME/at-spi2-core |
a0bb9cbcb2999d06747dec78b4959baad8d374d8 | organizer/models.py | organizer/models.py | from django.db import models
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Tag(models.Model):
name = models.CharField(max_length=31)
slug = models.SlugField()
class Startup(models.Model):
name = models.CharField(max_length=31)
slug = models.SlugField()
... | from django.db import models
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Tag(models.Model):
name = models.CharField(max_length=31)
slug = models.SlugField()
class Startup(models.Model):
name = models.CharField(max_length=31)
slug = models.SlugField()
... | Define NewsLink model related fields. | Ch03: Define NewsLink model related fields. [skip ci]
https://docs.djangoproject.com/en/1.8/ref/models/fields/#foreignkey
The NewsLink model now has a ForeignKey pointing to the Startup model.
External news articles may thus only point to a single startup business,
but any of our startup businesses may have multi... | Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 |
1090ecf891dd7c0928cdaae385464d3be660fdbf | penn/base.py | penn/base.py | from requests import get
class WrapperBase(object):
def __init__(self, bearer, token):
self.bearer = bearer
self.token = token
@property
def headers(self):
"""The HTTP headers needed for signed requests"""
return {
"Authorization-Bearer": self.bearer,
... | from requests import get
class WrapperBase(object):
def __init__(self, bearer, token):
self.bearer = bearer
self.token = token
@property
def headers(self):
"""The HTTP headers needed for signed requests"""
return {
"Authorization-Bearer": self.bearer,
... | Add better error handling for non-200 responses | Add better error handling for non-200 responses
| Python | mit | pennlabs/penn-sdk-python,pennlabs/penn-sdk-python |
4ee3900c8ac78c8ed1d0145f9d99a0485b542141 | senic_hub/backend/views/setup_config.py | senic_hub/backend/views/setup_config.py | from cornice.service import Service
from ..commands import create_configuration_files_and_restart_apps_
from ..config import path
configuration_service = Service(
name='configuration_create',
path=path('setup/config'),
renderer='json',
accept='application/json',
)
@configuration_service.post()
def ... | from cornice.service import Service
from ..commands import create_configuration_files_and_restart_apps_
from ..config import path
from ..supervisor import get_supervisor_rpc_client, stop_program
configuration_service = Service(
name='configuration_create',
path=path('setup/config'),
renderer='json',
... | Stop device discovery after onboarding | Stop device discovery after onboarding
| Python | mit | grunskis/nuimo-hub-backend,grunskis/senic-hub,grunskis/nuimo-hub-backend,grunskis/nuimo-hub-backend,getsenic/senic-hub,grunskis/senic-hub,grunskis/senic-hub,grunskis/senic-hub,grunskis/nuimo-hub-backend,getsenic/senic-hub,grunskis/nuimo-hub-backend,grunskis/senic-hub,grunskis/senic-hub |
608298a3bed65a36312500f15d58ac6c3cd6663d | pybeam/beam_file.py | pybeam/beam_file.py | from beam_construct import beam
class BeamFile(object):
def __init__(self, filename):
self._tree = beam.parse(file(filename,"r").read())
def selectChunkByName(self, name):
for c in self._tree.chunk:
if c.chunk_name == name:
return c
raise KeyError(name)
@property
def atoms(self):
return self.selec... | from beam_construct import beam
class BeamFile(object):
def __init__(self, filename):
self._tree = beam.parse(file(filename,"r").read())
def selectChunkByName(self, name):
for c in self._tree.chunk:
if c.chunk_name == name:
return c
raise KeyError(name)
@property
def atoms(self):
return self.selec... | Add @property exports Add @property imports | Add @property exports
Add @property imports
| Python | mit | matwey/pybeam |
164e4b5f02fbe9558e9fa50b12e7b28921f5be9b | wxGestalt.py | wxGestalt.py | # -*- coding: utf-8 -*-
import wx
import wxClass
class wxGestaltApp(wxClass.MyFrame1):
def __init__(self, *args, **kw):
super(wxGestaltApp, self).__init__(*args, **kw)
self.InitUI()
def InitUI(self):
self.Show()
def On_Quit( self, event ):
self.Close(True)
def On_S... | # -*- coding: utf-8 -*-
# Modules
# Modules for the wx Gui
import wx
import wxClass
# Modules for the serial communication
import serial
import glob
# Variables
# Current global setting for the Serial port in use
SerialPortInUse = ""
# Functions
def ScanSerialPorts():
# Scan for available ports. return a list ... | Add the functionality for choosing the serial port | Add the functionality for choosing the serial port
| Python | mit | openp2pdesign/wxGestalt |
2e23898ea287b6b9efcf6bcb8758cf61fca25256 | rest/serializers.py | rest/serializers.py | # Author: Braedy Kuzma
from rest_framework import serializers
from dash.models import Post, Author, Comment, Category
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
model = Author
fields = ('id', 'host', 'url')
def to_representation(self, author):
rv = serializers.Mo... | # Author: Braedy Kuzma
from rest_framework import serializers
from dash.models import Post, Author, Comment, Category
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
model = Author
fields = ('id', 'host', 'url', 'github')
def to_representation(self, author):
rv = seri... | Add missing github field to Author serializer. | Add missing github field to Author serializer.
| Python | apache-2.0 | CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project |
427b894fdd5690bc7a52dbcea42c4918b87d0046 | run_tests.py | run_tests.py | #!/usr/bin/env python3
# Copyright (c) 2013 Spotify AB
#
# 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 python3
# Copyright (c) 2013 Spotify AB
#
# 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 ... | Make coverage module optional during test run | Make coverage module optional during test run
Change-Id: I79f767a90a84c7b482e0cc9acd311619611802e9
| Python | apache-2.0 | brainly/check-growth |
5e1ea27b1334f74dee4f7d3f3823f80037da3690 | serrano/cors.py | serrano/cors.py | from warnings import warn
from django.conf import settings
def patch_response(request, response, methods):
if getattr(settings, 'SERRANO_CORS_ENABLED', False):
if hasattr(settings, 'SERRANO_CORS_ORIGIN'):
warn('SERRANO_CORS_ORIGIN has been deprecated in favor '
'of SERRANO_COR... | from warnings import warn
from django.conf import settings
def patch_response(request, response, methods):
if getattr(settings, 'SERRANO_CORS_ENABLED', False):
if hasattr(settings, 'SERRANO_CORS_ORIGIN'):
warn('SERRANO_CORS_ORIGIN has been deprecated in favor '
'of SERRANO_COR... | Remove truth assertion on origin | Remove truth assertion on origin
This is a remnant from testing in the SERRANO_CORS_ORIGIN string. Now
that the `in` applies to a list, this assertion is no longer needed.
| Python | bsd-2-clause | chop-dbhi/serrano,rv816/serrano_night,chop-dbhi/serrano,rv816/serrano_night |
6924b1326b664e405f926c36753192603204034e | salt/modules/nfs.py | salt/modules/nfs.py | '''
Module for managing NFS.
'''
# Import python libs
import logging
import salt.utils
log = logging.getLogger(__name__)
def __virtual__():
'''
Only work on posix-like systems
'''
# Disable on these platorms, specific service modules exist:
disable = [
'Windows',
]
if not sa... | '''
Module for managing NFS.
'''
# Import python libs
import logging
import salt.utils
log = logging.getLogger(__name__)
def __virtual__():
'''
Only work on posix-like systems
'''
# Disable on these platorms, specific service modules exist:
disable = [
'Windows',
]
if not sa... | Add multiple permissions to a single export | Add multiple permissions to a single export
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
7492133cbf46c2bfcf07b18d4d68de896c9eac69 | svs_interface.py | svs_interface.py | #!/usr/bin/env python
import subprocess
from Tkinter import *
from tkFileDialog import *
import os
class GpgApp(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.text = Text()
self.text.pack()
menu = Menu(master)
root.config(menu=menu)
... | #!/usr/bin/env python
import subprocess
from Tkinter import *
from tkFileDialog import *
import os
GPG = 'gpg2'
SERVER_KEY = '' # replace with gpg key ID of server key
class GpgApp(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.text = Text()
self.tex... | Add method to encrypt files | Add method to encrypt files
| Python | agpl-3.0 | jrosco/securedrop,heartsucker/securedrop,ehartsuyker/securedrop,chadmiller/securedrop,heartsucker/securedrop,garrettr/securedrop,jaseg/securedrop,chadmiller/securedrop,kelcecil/securedrop,jeann2013/securedrop,ageis/securedrop,harlo/securedrop,jeann2013/securedrop,conorsch/securedrop,conorsch/securedrop,chadmiller/secur... |
b89e210f95b8f41efa8019ee66d6449b7242d56f | tikplay/audio.py | tikplay/audio.py | import json
import logging
import pysoundcard
import pysoundfile
from tikplay.database import interface
class API():
""" Implements the audio parsing interface for tikplay.
Parses song metadata, handles database updating, and pushes the audio to soundcard
Also implements basic song metadata fetching fro... | import json
import logging
from pyglet import media
from tikplay.database import interface
class API():
""" Implements the audio parsing interface for tikplay.
Parses song metadata, handles database updating, and pushes the audio to soundcard
Also implements basic song metadata fetching from the databas... | Change pysoundcard and pysoundfile to pyglet | Change pysoundcard and pysoundfile to pyglet
| Python | mit | tietokilta-saato/tikplay,tietokilta-saato/tikplay,tietokilta-saato/tikplay,tietokilta-saato/tikplay |
b1edf4678a57bb25220bd4c50f05ceb7fbd5e7fe | users/filters.py | users/filters.py | """Filter classes corresponding to each one of the works app's models that has the
same fields as the model for an equalTo filter.
There can be added extra fields inside each class as gt, lt, gte, lte and so on for
convinience.
"""
import django_filters
from django.contrib.auth.models import User, Group
class UserFi... | """Filter classes corresponding to each one of the works app's models that has the
same fields as the model for an equalTo filter.
There can be added extra fields inside each class as gt, lt, gte, lte and so on for
convinience.
"""
import django_filters
from django.contrib.auth.models import User, Group
class UserFi... | Change name of a filter field | Change name of a filter field
| Python | mit | fernandolobato/balarco,fernandolobato/balarco,fernandolobato/balarco |
4e4390db6ed35de4fb7ad42579be5180a95bb96f | src/settings.py | src/settings.py | import re
import os
# Root directory that we scan for music from
# Do not change this unless you're not using the docker-compose
# It is preferred you use just change the volume mapping on the docker-compose.yml
MUSIC_DIRECTORY = os.environ.get("FTMP3_MUSIC", "/media/Music")
# Tells flask to serve the mp3 files
# Typi... | import re
import os
# Root directory that we scan for music from
# Do not change this unless you're not using the docker-compose
# It is preferred you use just change the volume mapping on the docker-compose.yml
MUSIC_DIRECTORY = os.environ.get("FTMP3_MUSIC", r"/media/Music/")
# Tells flask to serve the mp3 files
# Ty... | Allow for case-insensitive checking of file formats. Support m4a | Allow for case-insensitive checking of file formats. Support m4a
| Python | apache-2.0 | nhydock/ftmp3,lunared/ftmp3,nhydock/ftmp3,lunared/ftmp3,lunared/ftmp3 |
ac3db8b26bd6ac2e0db2c8221521aead9c996ec0 | blog/views.py | blog/views.py | from django.shortcuts import (
get_object_or_404, render)
from django.views.generic import View
from .models import Post
def post_detail(request, year, month, slug):
post = get_object_or_404(
Post,
pub_date__year=year,
pub_date__month=month,
slug=slug)
return render(
... | from django.shortcuts import (
get_object_or_404, render)
from django.views.generic import View
from .models import Post
def post_detail(request, year, month, slug):
post = get_object_or_404(
Post,
pub_date__year=year,
pub_date__month=month,
slug=slug)
return render(
... | Use attribute for template in Post List. | Ch05: Use attribute for template in Post List.
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 |
ef43e04970151ec5bba9688f268b2f85b5debd3f | bfg9000/builtins/__init__.py | bfg9000/builtins/__init__.py | import functools
import glob
import os
import pkgutil
_all_builtins = {}
_loaded_builtins = False
class Binder(object):
def __init__(self, fn):
self.fn = fn
def bind(self, build_inputs, env):
return functools.partial(self.fn, build_inputs, env)
def builtin(fn):
bound = Binder(fn)
_al... | import functools
import glob
import os
import pkgutil
_all_builtins = {}
_loaded_builtins = False
class Binder(object):
def __init__(self, fn):
self.fn = fn
def bind(self, build_inputs, env):
return functools.partial(self.fn, build_inputs, env)
def builtin(fn):
bound = Binder(fn)
_al... | Make the Environment object available to build.bfg files | Make the Environment object available to build.bfg files
| Python | bsd-3-clause | jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000 |
c30b4aa0d577e545193229d0f33b55998405cba2 | trex/urls.py | trex/urls.py | # -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from trex.views import project
urlpatterns = patterns(
'',
url(r"^$",
Te... | # -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from trex.views import project
urlpatterns = patterns(
'',
url(r"^$",
Te... | Add url mapping for the tag details view | Add url mapping for the tag details view
| Python | mit | bjoernricks/trex,bjoernricks/trex |
c7d2e917df5e0c2182e351b5157271b6e62a06cd | app/soc/modules/gsoc/models/timeline.py | app/soc/modules/gsoc/models/timeline.py | #!/usr/bin/env python2.5
#
# Copyright 2009 the Melange authors.
#
# 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 applic... | #!/usr/bin/env python2.5
#
# Copyright 2009 the Melange authors.
#
# 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 applic... | Change verbage on program profile info. | Change verbage on program profile info.
Fixes issue 1601.
| Python | apache-2.0 | rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son |
0e2dbbd204d9c1c9bd31f4be78b0a76ce39786d2 | test/test_ev3_lcd.py | test/test_ev3_lcd.py | from ev3.ev3dev import Lcd
# -*- coding: utf-8 -*-
import unittest
from util import get_input
import time
from PIL import Image,ImageDraw,ImageFont
class TestLcd(unittest.TestCase):
def test_lcd(self):
get_input('Test lcd')
d= Lcd()
d.draw.ellipse((20, 20, 60, 60))
d.update(... | # -*- coding: utf-8 -*-
import unittest
from ev3.ev3dev import Lcd
from util import get_input
import time
from PIL import Image,ImageDraw,ImageFont
class TestLcd(unittest.TestCase):
def test_lcd(self):
get_input('Test lcd')
d= Lcd()
d.draw.ellipse((20, 20, 60, 60))
d.update(... | Fix encoding issue when test lcd | Fix encoding issue when test lcd
| Python | apache-2.0 | MaxNoe/python-ev3,evz/python-ev3,topikachu/python-ev3,MaxNoe/python-ev3,evz/python-ev3,topikachu/python-ev3 |
89cb9f325403e3094a5fb2090ef4ea5f804b9d20 | pq.py | pq.py | # Chapter 2: The pq-system
def make_axiom(n):
assert type(n) == int
assert n > 0
x = '-' * n
return x + 'p' + '-q' + x + '-'
def next_theorem(theorem):
assert 'p' in theorem
assert 'q' in theorem
iq = theorem.find('q')
return theorem[:iq] + '-' + theorem[iq:] + '-'
# make a basic axiom
a1 = make_axio... | # Chapter 2: The pq-system
import re
import random
axiom_pattern = re.compile('(-*)p-q(-*)-')
theorem_pattern = re.compile('(-*)p(-*)q(-*)')
def make_axiom(n):
assert type(n) == int
assert n > 0
x = '-' * n
return x + 'p' + '-q' + x + '-'
def next_theorem(theorem):
assert 'p' in theorem
assert 'q' in the... | Add axiom and theorem checks | Add axiom and theorem checks
| Python | mit | ericfs/geb |
b0e21495e0421a3656ed4507fe7b43b65601f16f | bluebottle/settings/travis.py | bluebottle/settings/travis.py |
# SECRET_KEY and DATABASES needs to be defined before the base settings is imported.
SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q=='
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
from .base import *
#
# Put the travis-ci e... |
# SECRET_KEY and DATABASES needs to be defined before the base settings is imported.
SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q=='
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
from .base import *
#
# Put the travis-ci e... | Enable Selenium tests for Travis. | Enable Selenium tests for Travis.
| Python | bsd-3-clause | onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site |
1f25d3a8d73fe776a2182ee68c027105fd15ab04 | tiamat/decorators.py | tiamat/decorators.py | import json
from functools import wraps
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
def as_json(func):
def decorator(request, *ar, **kw):
output = func(request, *ar, **kw)
if not isinstance(output, dict):
... | import json
from functools import wraps
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
def as_json(func):
def decorator(request, *ar, **kw):
output = func(request, *ar, **kw)
return HttpResponse(json.dumps(output), '... | Fix problem in as_json and as_jsonp | Fix problem in as_json and as_jsonp
| Python | bsd-2-clause | rvause/django-tiamat |
6fd5e51a797f3d85954f6a4c97eacc008b0e4d48 | tohu/v5/namespace.py | tohu/v5/namespace.py | from bidict import bidict, ValueDuplicationError
def is_anonymous(name):
return name.startswith("ANONYMOUS_ANONYMOUS_ANONYMOUS_")
class TohuNamespaceError(Exception):
"""
Custom exception.
"""
class TohuNamespace:
def __init__(self):
self.generators = bidict()
def __len__(self):
... | from mako.template import Template
import textwrap
from bidict import bidict, ValueDuplicationError
def is_anonymous(name):
return name.startswith("ANONYMOUS_ANONYMOUS_ANONYMOUS_")
class TohuNamespaceError(Exception):
"""
Custom exception.
"""
class TohuNamespace:
def __init__(self):
... | Add repr method for TohuNamespace | Add repr method for TohuNamespace
| Python | mit | maxalbert/tohu |
e9862c50c1d71800602ca78bf9bdd8aad2def0a2 | run.py | run.py | import os
tag = 'celebA_dcgan'
dataset = 'celebA'
command = 'python main.py --dataset %s --is_train True ' \
'--sample_dir samples_%s --checkpoint_dir checkpoint_%s --tensorboard_run %s '%(dataset, tag, tag, tag)
os.system(command)
| import os
tag = 'celebA_dcgan'
dataset = 'celebA'
command = 'python main.py --dataset %s --is_train True --is_crop ' \
'--sample_dir samples_%s --checkpoint_dir checkpoint_%s --tensorboard_run %s '%(dataset, tag, tag, tag)
os.system(command)
| Add is_crop for celebA example | Add is_crop for celebA example | Python | mit | MustafaMustafa/WassersteinGAN-TensorFlow |
96db3441a0cc2e3010606b2017c900a16c6a8f2f | astropy/nddata/tests/test_nddatabase.py | astropy/nddata/tests/test_nddatabase.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# Tests of NDDataBase
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from ..nddatabase import NDDataBase
from ...tests.helper import pytest
class MinimalSubclass(NDDataBase):
def __init_... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# Tests of NDDataBase
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from ..nddatabase import NDDataBase
from ...tests.helper import pytest
class MinimalSubclass(NDDataBase):
def __init_... | Add returns to test class properties | Add returns to test class properties
| Python | bsd-3-clause | tbabej/astropy,lpsinger/astropy,dhomeier/astropy,larrybradley/astropy,pllim/astropy,dhomeier/astropy,AustereCuriosity/astropy,stargaser/astropy,mhvk/astropy,astropy/astropy,AustereCuriosity/astropy,pllim/astropy,lpsinger/astropy,MSeifert04/astropy,tbabej/astropy,stargaser/astropy,bsipocz/astropy,joergdietrich/astropy,j... |
1e63d21d5751da12ad4104b6d2a0c170cc3898ff | problem_3/solution.py | problem_3/solution.py | def largest_prime_factor(n, h):
for i in xrange(2, n+1):
d, m = divmod(n, i)
if m == 0:
largest_prime_factor(d, i)
break
if n == 1: print h
largest_prime_factor(600851475143, 0)
| import time
def largest_prime_factor(n, h):
for i in xrange(2, n+1):
d, m = divmod(n, i)
if m == 0:
largest_prime_factor(d, i)
break
if n == 1: return h
t1 = time.time()
largest_prime_factor(600851475143, 0)
t2 = time.time()
print "=> largest_prime_factor(600851475143, 0)... | Add timing for problem 3's python implementation | Add timing for problem 3's python implementation
| Python | mit | mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler |
16a85be6597388092e497e642cdad8650fdfea95 | app/tasks/twitter/listener.py | app/tasks/twitter/listener.py | # -*- coding: utf-8 -*-
import time
import json
import sys
import pika
from tweepy.streaming import StreamListener
class Listener(StreamListener):
def __init__(self):
#setup rabbitMQ Connection
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
self.channel = conn... | # -*- coding: utf-8 -*-
import time
import json
import sys
import pika
import os
from tweepy.streaming import StreamListener
class Listener(StreamListener):
def __init__(self):
#setup rabbitMQ Connection
host = os.environ['CLOUDAMQP_URL']
connection = pika.BlockingConnection(pika.Connectio... | Set up environment specific connection to rabbitmq | Set up environment specific connection to rabbitmq
| Python | mit | robot-overlord/syriarightnow |
0a136631d78ee518aec96a1a6ec24ed3e7d4c613 | taOonja/game/models.py | taOonja/game/models.py | import os
from django.db import models
def get_image_path(filename):
return os.path.join('photos',filename)
class Location(models.Model):
name = models.CharField(max_length=250)
local_name = models.CharField(max_length=250)
visited = models.BooleanField(default=False)
class Detail(models.Model):
... | import os
from django.db import models
#def get_image_path(filename):
# return os.path.join('media')
class Location(models.Model):
name = models.CharField(max_length=250)
local_name = models.CharField(max_length=250)
visited = models.BooleanField(default=False)
def __str__(self):
return s... | Change model File to Show Better and Correct Image Field | Change model File to Show Better and Correct Image Field
| Python | mit | Javid-Izadfar/TaOonja,Javid-Izadfar/TaOonja,Javid-Izadfar/TaOonja |
ed12fe8cde425c75d02dbb9beb98abd8a814292a | alg_selection_sort.py | alg_selection_sort.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def selection_sort(ls):
"""Selection Sort algortihm.
Time complexity: O(n^2).
Space complexity: O(1).
"""
# Start from the last elemenet reversely: len(ls) - 1, ..., 0.
for i_max in re... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def selection_sort(ls):
"""Selection Sort algortihm.
Time complexity: O(n^2).
Space complexity: O(1).
"""
# Start from the last position reversely: len(ls) - 1, ..., 0.
for i in revers... | Refactor selection sort w/ comments | Refactor selection sort w/ comments
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
63a4a2dfa733fab15bb7e0d632c8efe6528b82cb | escpos/impl/__init__.py | escpos/impl/__init__.py | # -*- coding: utf-8 -*-
#
# escpos/impl/__init__.py
#
# Copyright 2015 Base4 Sistemas Ltda ME
#
# 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.... | # -*- coding: utf-8 -*-
#
# escpos/impl/__init__.py
#
# Copyright 2015 Base4 Sistemas Ltda ME
#
# 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.... | Fix import to support Python3 | Fix import to support Python3
| Python | apache-2.0 | base4sistemas/pyescpos |
a492b0395ff56f150d2fde506b6536f0324f31f6 | teerace/local_tests.py | teerace/local_tests.py | from django.test.simple import run_tests as default_run_tests
from django.conf import settings
def run_tests(test_labels, *args, **kwargs):
del test_labels
return default_run_tests(settings.OUR_APPS, *args, **kwargs)
| from django.test.simple import DjangoTestSuiteRunner
from django.conf import settings
class LocalTestSuiteRunner(DjangoTestSuiteRunner):
def run_tests(self, test_labels, extra_tests=None, **kwargs):
del test_labels
super(LocalTestSuiteRunner, self).run_tests(settings.OUR_APPS, extra_tests, **kwargs)
| Test runner is now class-based. | Test runner is now class-based.
| Python | bsd-3-clause | SushiTee/teerace,SushiTee/teerace,SushiTee/teerace |
252bc8df092f59ecd092ea5904fcc845dc22bee8 | dbaas/util/update_instances_with_offering.py | dbaas/util/update_instances_with_offering.py | # coding: utf-8
class UpdateInstances(object):
@staticmethod
def do():
from dbaas_cloudstack.models import DatabaseInfraOffering
from dbaas_cloudstack.models import PlanAttr
infra_offerings = DatabaseInfraOffering.objects.all()
for infra_offering in infra_offerings:
... | # coding: utf-8
class UpdateInstances(object):
@staticmethod
def do():
from dbaas_cloudstack.models import DatabaseInfraOffering
from dbaas_cloudstack.models import PlanAttr
infra_offerings = DatabaseInfraOffering.objects.all()
for infra_offering in infra_offerings:
... | Change script to update offering on Host instead Instance | Change script to update offering on Host instead Instance
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service |
579101f714201ba2cc933f64c83ca6cfda8eca8c | test/wheel_velocity.py | test/wheel_velocity.py | #!/usr/bin/python
from config import Config
from motor import Motor
import Rpi.GPIO as GPIO
import json
import sys
import time
def _init_motor(self, pin1_s, pin2_s, pinE_s):
pin1 = self.config.get("motors", pin1_s)
pin2 = self.config.get("motors", pin2_s)
pinE = self.config.get("motors", pinE_s)
if pi... | #!/usr/bin/python
from config import Config
from motor import Motor
from encoder import Encoder
import Rpi.GPIO as GPIO
import json
import sys
import time
def _init_motor(config, pin1_s, pin2_s, pinE_s):
pin1 = config.get("motors", pin1_s)
pin2 = config.get("motors", pin2_s)
pinE = config.get("motors", pi... | Add encoder to wheel velocity test | Add encoder to wheel velocity test
| Python | mit | thomasweng15/rover |
799d6738bd189fa202f45c10e7b5361f71f14c57 | bin/request_domain.py | bin/request_domain.py | #!/usr/bin/python
"""An example demonstrating the client-side usage
of the cretificate request API endpoint.
"""
import requests, sys, json
otp = sys.argv[1]
domain_req_url = 'https://spire.cloudfleet.io/api/v1/blimp/domain'
domain_txt_path = '/opt/cloudfleet/data/config/domain.txt'
print('retrieving domain for bli... | #!/usr/bin/python
"""An example demonstrating the client-side usage
of the cretificate request API endpoint.
"""
import requests, sys, json
otp = sys.argv[1]
domain_req_url = 'https://spire.cloudfleet.io/api/v1/blimp/domain'
domain_txt_path = '/opt/cloudfleet/data/config/domain.txt'
print('retrieving domain for bli... | Clarify error if otp is wrong | Clarify error if otp is wrong | Python | agpl-3.0 | cloudfleet/blimp-engineroom,cloudfleet/blimp-engineroom |
970eb92f6db8b2fd22594d662a7142a976d60559 | airflow/contrib/hooks/__init__.py | airflow/contrib/hooks/__init__.py | # Imports the hooks dynamically while keeping the package API clean,
# abstracting the underlying modules
from airflow.utils import import_module_attrs as _import_module_attrs
_hooks = {
'ftp_hook': ['FTPHook'],
'vertica_hook': ['VerticaHook'],
'ssh_hook': ['SSHHook'],
'bigquery_hook': ['BigQueryHook']... | # Imports the hooks dynamically while keeping the package API clean,
# abstracting the underlying modules
from airflow.utils import import_module_attrs as _import_module_attrs
_hooks = {
'ftp_hook': ['FTPHook'],
'ftps_hook': ['FTPSHook'],
'vertica_hook': ['VerticaHook'],
'ssh_hook': ['SSHHook'],
'b... | Add FTPSHook in _hooks register. | Add FTPSHook in _hooks register. | Python | apache-2.0 | cjqian/incubator-airflow,KL-WLCR/incubator-airflow,dmitry-r/incubator-airflow,yiqingj/airflow,rishibarve/incubator-airflow,vineet-rh/incubator-airflow,ty707/airflow,preete-dixit-ck/incubator-airflow,saguziel/incubator-airflow,sdiazb/airflow,NielsZeilemaker/incubator-airflow,subodhchhabra/airflow,yiqingj/airflow,preete-... |
7db3a14636402a5c66179a9c60df33398190bd3e | app/modules/frest/api/__init__.py | app/modules/frest/api/__init__.py | # -*- coding: utf-8 -*-
from functools import wraps, partial
from flask import request
from flask_api import status
from flask.wrappers import Response
from app.config import API_ACCEPT_HEADER
def API(method=None):
if method is None:
return partial(API)
@wraps(method)
def decorated(*args, **kwa... | # -*- coding: utf-8 -*-
from functools import wraps, partial
from flask import request
from flask_api import status
from flask.wrappers import Response
from app.config import API_ACCEPT_HEADER, API_VERSION
def API(method=None):
if method is None:
return partial(API)
@wraps(method)
def decorated... | Return http status code 301 when api version is wrong | Return http status code 301 when api version is wrong
| Python | mit | h4wldev/Frest |
a46c152adb78996538128b63e441b00bea2790ea | django_su/forms.py | django_su/forms.py | # -*- coding: utf-8 -*-
from django import forms
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from . import get_user_model
class UserSuForm(forms.Form):
user = forms.ModelChoiceField(
label=_('Users'), queryset=get_user_model()._default_manager.order_by(
... | # -*- coding: utf-8 -*-
from django import forms
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from . import get_user_model
class UserSuForm(forms.Form):
username_field = get_user_model().USERNAME_FIELD
user = forms.ModelChoiceField(
label=_('Users'), que... | Update UserSuForm to enhance compatibility with custom user models. | Update UserSuForm to enhance compatibility with custom user models.
In custom user models, we cannot rely on there being a 'username'
field. Instead, we should use whichever field has been specified as
the username field.
| Python | mit | adamcharnock/django-su,PetrDlouhy/django-su,PetrDlouhy/django-su,adamcharnock/django-su |
f3cf8b8e36dc7d2ed5096e17dcfa1f9456a7a996 | Project-AENEAS/issues/models.py | Project-AENEAS/issues/models.py | from django.db import models
# Create your models here.
| """Mini Issue Tracker program. Originally taken from Paul Bissex's blog post:
http://news.e-scribe.com/230 and snippet: http://djangosnippets.org/snippets/28/
"""
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import ugettext_lazy ... | Add an initial model for an issue | Add an initial model for an issue
| Python | bsd-3-clause | zooming-tan/Project-AENEAS,zooming-tan/Project-AENEAS,zooming-tan/Project-AENEAS,zooming-tan/Project-AENEAS |
cd5d291fc1ccf3e2171ccfc0444e4748de450d3c | 99_misc/control_flow.py | 99_misc/control_flow.py | #!/usr/bin/env python
# function
def sum(op1, op2):
return op1 + op2
my_sum = sum
print my_sum(1, 2)
print my_sum("I am ", "zzz");
# Default value in a fuction
init = 12
def accumulate(val = init):
val += val
return val
my_accu = accumulate
init = 11
print my_accu() # is 12 + 12 rather than 11 + 11
# De... | #!/usr/bin/env python
# function
def sum(op1, op2):
return op1 + op2
my_sum = sum
print my_sum(1, 2)
print my_sum("I am ", "zzz");
# Default value in a fuction
init = 12
def accumulate(val = init):
val += val
return val
my_accu = accumulate
init = 11
print my_accu() # is 12 + 12 rather than 11 + 11
# De... | Test variable argument in a function | Test variable argument in a function
| Python | bsd-2-clause | zzz0072/Python_Exercises,zzz0072/Python_Exercises |
f9aeede7af207a672a867c4f310d7d357a4d47c9 | icekit/utils/fluent_contents.py | icekit/utils/fluent_contents.py | from django.contrib.contenttypes.models import ContentType
# USEFUL FUNCTIONS FOR FLUENT CONTENTS #############################################################
# Fluent Contents Helper Functions #################################################################
def create_content_instance(content_plugin_class, test_p... | from django.contrib.contenttypes.models import ContentType
# USEFUL FUNCTIONS FOR FLUENT CONTENTS #############################################################
# Fluent Contents Helper Functions #################################################################
def create_content_instance(content_plugin_class, test_p... | Improve error reporting for content item testing utils | Improve error reporting for content item testing utils
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit |
e9efe7ff408fe5dd3be596ce9ded3bce312cb9e6 | shell/src/hook.py | shell/src/hook.py | import threading
import contextlib
the_current_shell = threading.local()
the_current_shell.value = None
@contextlib.contextmanager
def set_current_shell(shell):
outer = the_current_shell.value
the_current_shell.value = shell
try:
yield
finally:
the_current_shell.value = outer
def cu... | import threading
import contextlib
the_current_shell = threading.local()
the_current_shell.value = None
@contextlib.contextmanager
def set_current_shell(shell):
outer = the_current_shell.value
the_current_shell.value = shell
try:
yield
finally:
the_current_shell.value = outer
def cu... | Make sure that the wrapped function inherits doctring | Make sure that the wrapped function inherits doctring
| Python | apache-2.0 | probcomp/bayeslite,probcomp/bayeslite |
331ce5fde1a653997900f3e247f9d34a2c47fb54 | projects/models.py | projects/models.py | # -*- coding: utf-8
from django.conf import settings
from django.db import models
class InlistItem(models.Model):
text = models.CharField(max_length=255, default='')
user = models.ForeignKey(settings.AUTH_USER_MODEL)
def __str__(self):
return self.text
class Meta:
unique_together = ('... | # -*- coding: utf-8
from django.conf import settings
from django.db import models
class InlistItem(models.Model):
text = models.CharField(max_length=255, default='')
user = models.ForeignKey(settings.AUTH_USER_MODEL)
def __str__(self):
return self.text
class Meta:
unique_together = ('... | Add explicit ordering to inlist items | Add explicit ordering to inlist items
| Python | mit | XeryusTC/projman,XeryusTC/projman,XeryusTC/projman |
c23e697ccc64340027d3b07728032247bb5b21a4 | kerze.py | kerze.py | from turtle import *
GROESSE = 0.5
FARBE = "red"
FAERBEN = True
SHAPE = "turtle"
fillcolor(FARBE)
shape(SHAPE)
def zeichneKerze(brennt):
pd()
begin_fill()
forward(GROESSE*100)
left(90)
forward(GROESSE*400)
left(90)
forward(GROESSE*100)
right(90)
forward(GROESSE*30)
back(GROESS... | import turtle as t
GROESSE = 0.5
FARBE = "red"
FAERBEN = True
SHAPE = "turtle"
t.fillcolor(FARBE)
t.shape(SHAPE)
def zeichneKerze(brennt):
t.pd()
t.begin_fill()
t.forward(GROESSE*100)
t.left(90)
t.forward(GROESSE*400)
t.left(90)
t.forward(GROESSE*100)
t.right(90)
t.forward(GROESSE... | Make imports compliant to PEP 8 suggestion | Make imports compliant to PEP 8 suggestion
| Python | mit | luforst/adventskranz |
a6fe31d7f687df6934143fd2dda1cd323f3d31fb | uvloop/_patch.py | uvloop/_patch.py | import asyncio
from asyncio import coroutines
def _format_coroutine(coro):
if asyncio.iscoroutine(coro) and not hasattr(coro, 'cr_code'):
# Most likely a Cython coroutine
coro_name = '{}()'.format(coro.__qualname__ or coro.__name__)
if coro.cr_running:
return '{} running'.form... | import asyncio
from asyncio import coroutines
def _format_coroutine(coro):
if asyncio.iscoroutine(coro) \
and not hasattr(coro, 'cr_code') \
and not hasattr(coro, 'gi_code'):
# Most likely a Cython coroutine
coro_name = '{}()'.format(coro.__qualname__ or coro.__name__)
... | Fix patched _format_coroutine to support Cython generators | Fix patched _format_coroutine to support Cython generators
| Python | apache-2.0 | 1st1/uvloop,MagicStack/uvloop,MagicStack/uvloop |
7e15a22ed01b4aa68a73a0e8e10d88d9b3785062 | aiohttp_json_rpc/__init__.py | aiohttp_json_rpc/__init__.py | from .decorators import raw_response, validate # NOQA
from .client import JsonRpcClient # NOQA
from .rpc import JsonRpc # NOQA
from .exceptions import ( # NOQA
RpcGenericServerDefinedError,
RpcInvalidRequestError,
RpcMethodNotFoundError,
RpcInvalidParamsError,
RpcError,
)
| from .decorators import raw_response, validate # NOQA
from .client import JsonRpcClient, JsonRpcClientContext # NOQA
from .rpc import JsonRpc # NOQA
from .exceptions import ( # NOQA
RpcGenericServerDefinedError,
RpcInvalidRequestError,
RpcMethodNotFoundError,
RpcInvalidParamsError,
RpcError,
)
| Add import JsonRpcClientContext in the main module | Add import JsonRpcClientContext in the main module
| Python | apache-2.0 | pengutronix/aiohttp-json-rpc,pengutronix/aiohttp-json-rpc,pengutronix/aiohttp-json-rpc |
a692c339983ae0252577635751b67324985275dc | background_hang_reporter_job/tracked.py | background_hang_reporter_job/tracked.py | class AllHangs(object):
title = "All Hangs"
@staticmethod
def matches_hang(_):
return True
class DevtoolsHangs(object):
title = "Devtools Hangs"
@staticmethod
def matches_hang(hang):
#pylint: disable=unused-variable
stack, duration, thread, runnable, process, annotatio... | class AllHangs(object):
title = "All Hangs"
@staticmethod
def matches_hang(_):
return True
class DevtoolsHangs(object):
title = "Devtools Hangs"
@staticmethod
def matches_hang(hang):
#pylint: disable=unused-variable
stack, duration, thread, runnable, process, annotatio... | Fix Activity Stream category title | Fix Activity Stream category title
| Python | mit | squarewave/background-hang-reporter-job,squarewave/background-hang-reporter-job |
56b5b4d49973702bcb95bb36dcd1e35f40b57a1d | hyper/http20/exceptions.py | hyper/http20/exceptions.py | # -*- coding: utf-8 -*-
"""
hyper/http20/exceptions
~~~~~~~~~~~~~~~~~~~~~~~
This defines exceptions used in the HTTP/2 portion of hyper.
"""
class HTTP20Error(Exception):
"""
The base class for all of ``hyper``'s HTTP/2-related exceptions.
"""
pass
class HPACKEncodingError(HTTP20Error):
"""
... | # -*- coding: utf-8 -*-
"""
hyper/http20/exceptions
~~~~~~~~~~~~~~~~~~~~~~~
This defines exceptions used in the HTTP/2 portion of hyper.
"""
class HTTP20Error(Exception):
"""
The base class for all of ``hyper``'s HTTP/2-related exceptions.
"""
pass
class HPACKEncodingError(HTTP20Error):
"""
... | Add exception for streams forcefully reset | Add exception for streams forcefully reset
| Python | mit | Lukasa/hyper,plucury/hyper,fredthomsen/hyper,irvind/hyper,fredthomsen/hyper,lawnmowerlatte/hyper,lawnmowerlatte/hyper,Lukasa/hyper,plucury/hyper,irvind/hyper |
91b281a2d8e0938404fa533c7a4ff9f2a251d1b1 | backend/populate_targets.py | backend/populate_targets.py | import django
import os
import yaml
from backend.settings import BASE_DIR
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
django.setup()
from breach.models import Target
def create_target(target):
t = Target(
endpoint=target['endpoint'],
prefix=target['prefix'],
alpha... | import django
import os
import yaml
from backend.settings import BASE_DIR
from django.db import IntegrityError
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
django.setup()
from breach.models import Target
def create_target(target):
t = Target(
name=target['name'],
endpoint=... | Add name when creating Target | Add name when creating Target
| Python | mit | dimkarakostas/rupture,dionyziz/rupture,dionyziz/rupture,dimkarakostas/rupture,dimriou/rupture,dimriou/rupture,esarafianou/rupture,dimriou/rupture,dionyziz/rupture,dionyziz/rupture,esarafianou/rupture,dimriou/rupture,dimkarakostas/rupture,dimriou/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dionyziz/rupture,esara... |
a055f97a342f670171f30095cabfd4ba1bfdad17 | images/singleuser/user-config.py | images/singleuser/user-config.py | import os
mylang = 'test'
family = 'wikipedia'
custom_path = os.path.expanduser('~/user-config.py')
if os.path.exists(custom_path):
with open(custom_path, 'rb') as f:
exec(compile(f.read(), custom_path, 'exec'), globals())
del f
# Clean up temp variables, since pwb issues a warning otherwise
# to he... | import os
mylang = 'test'
family = 'wikipedia'
custom_path = os.path.expanduser('~/user-config.py')
if os.path.exists(custom_path):
with open(custom_path, 'rb') as f:
exec(compile(f.read(), custom_path, 'exec'), globals())
del f
# Clean up temp variables, since pwb issues a warning otherwise
# to he... | Fix dictionary access pattern for setting auth tokens | Fix dictionary access pattern for setting auth tokens
| Python | mit | yuvipanda/paws,yuvipanda/paws |
d05a16474c9eabc7f52d8d9c6811e4d01bea6080 | bongo/settings/travis.py | bongo/settings/travis.py | from bongo.settings.prod import *
# The same settings as production, but no database password.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'bongo_test',
'USER': 'postgres',
'PASSWORD': '',
'HOST': '127.0.0.1',
'PORT': '5432... | from bongo.settings.prod import *
# The same settings as production, but no database password.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'bongo_test',
'USER': 'postgres',
'PASSWORD': '',
'HOST': '127.0.0.1',
'PORT': '5432... | Make test output more verbose so we can figure out what is hanging | Make test output more verbose so we can figure out what is hanging
| Python | mit | BowdoinOrient/bongo,BowdoinOrient/bongo,BowdoinOrient/bongo,BowdoinOrient/bongo |
8f4c8760dd5f6f21b1c59579332a3c81fa58ed13 | buildlet/runner/__init__.py | buildlet/runner/__init__.py | """
Runner classes to execute tasks.
"""
_namemodmap = dict(
SimpleRunner='simple',
IPythonParallelRunner='ipythonparallel',
MultiprocessingRunner='multiprocessingpool',
)
def getrunner(classname):
import sys
module = 'buildlet.runner.{0}'.format(_namemodmap[classname])
__import__(module)
... | """
Runner classes to execute tasks.
"""
_namemodmap = dict(
SimpleRunner='simple',
IPythonParallelRunner='ipythonparallel',
MultiprocessingRunner='multiprocessingpool',
)
def getrunner(classname):
"""
Get a runner class named `classname`.
"""
import sys
module = 'buildlet.runner.{0}'... | Document utility functions in buildlet.runner | Document utility functions in buildlet.runner
| Python | bsd-3-clause | tkf/buildlet |
62503058850008d7b346d6e6b70943f5e2a1efba | app/taskqueue/celeryconfig.py | app/taskqueue/celeryconfig.py | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be usefu... | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be usefu... | Set celery task results to expire in 1h | Set celery task results to expire in 1h
| Python | lgpl-2.1 | kernelci/kernelci-backend,kernelci/kernelci-backend |
97105453db680c2d99becd10f91604339c970591 | linkatos.py | linkatos.py | #! /usr/bin/env python
import os
from slackclient import SlackClient
import pyrebase
import linkatos.firebase as fb
import linkatos.activities as activities
# starterbot environment variables
BOT_ID = os.environ.get("BOT_ID")
SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN")
# instantiate Slack clients
slack_clien... | #! /usr/bin/env python
import os
from slackclient import SlackClient
import pyrebase
import linkatos.firebase as fb
import linkatos.activities as activities
# Main
if __name__ == '__main__':
# starterbot environment variables
BOT_ID = os.environ.get("BOT_ID")
SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN... | Move initialisations inside main to avoid running them if not necessary | refactor: Move initialisations inside main to avoid running them if not necessary
| Python | mit | iwi/linkatos,iwi/linkatos |
46074e64289995aab5e1129f1eead705a53010b9 | learning_journal/models.py | learning_journal/models.py | from sqlalchemy import (
Column,
DateTime,
Integer,
Unicode,
UnicodeText,
)
from sqlalchemy.ext.declarative import declarative_base
import datetime
import psycopg2
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
)
from zope.sqlalchemy import ZopeTransactionExtension
DB... | import datetime
import psycopg2
from sqlalchemy import (
Column,
DateTime,
Integer,
Unicode,
UnicodeText,
)
from pyramid.security import Allow, Everyone
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
)
from zope.sqla... | Add acl method to Entry model | Add acl method to Entry model
| Python | mit | DZwell/learning_journal,DZwell/learning_journal,DZwell/learning_journal |
c59c762be198b9c976d25b093860f1d14e9d2271 | backend/scripts/ddirdenorm.py | backend/scripts/ddirdenorm.py | #!/usr/bin/env python
import rethinkdb as r
conn = r.connect('localhost', 30815, db='materialscommons')
if __name__ == "__main__":
selection = list(r.table('datadirs').run(conn))
for datadir in selection:
print "Updating datadir %s" % (datadir['name'])
ddir = {}
ddir['id'] = datadir['... | #!/usr/bin/env python
import rethinkdb as r
import optparse
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port",
help="rethinkdb port", default=30815)
(options, args) = parser.parse_args()
conn = r.connect('localhost', int(op... | Add options for setting the port. | Add options for setting the port.
| Python | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org |
cc6bb949b0f4a3c4b6344b219f8b5bae2081e0a4 | slave/skia_slave_scripts/download_skimage_files.py | slave/skia_slave_scripts/download_skimage_files.py | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Download the image files needed to run skimage tool. """
from build_step import BuildStep
from utils import gs_utils
from util... | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Download the image files needed to run skimage tool. """
from build_step import BuildStep
from utils import gs_utils
from util... | Use posixpath for paths in the cloud. | Use posixpath for paths in the cloud.
Fixes build break on Windows.
R=borenet@google.com
Review URL: https://codereview.chromium.org/18074002
git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@9792 2bbb7eff-a529-9590-31e7-b0007b416f81
| Python | bsd-3-clause | google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Ti... |
e2959ec01b25c3f447fdd31608b30f19c2dc3599 | engine.py | engine.py | # Use x, y coords for unit positions
# (97, 56) ... (104, 56)
# ... ...
# (97, 49) ... (104, 49)
#
# Algebraic notation for a position is:
# algebraic_pos = chr(x) + chr(y)
def _coord_to_algebraic(coord):
x, y = coord
return chr(x) + chr(y)
def _algebraic_to_coord(algebraic):
x, y = algebrai... | # Use x, y coords for unit positions
# (97, 56) ... (104, 56)
# ... ...
# (97, 49) ... (104, 49)
#
# Algebraic notation for a position is:
# algebraic_pos = chr(x) + chr(y)
def _coord_to_algebraic(coord):
x, y = coord
return chr(x) + chr(y)
def _algebraic_to_coord(algebraic):
x, y = algebrai... | Add _is_pos_on_board() to determine if a position is on the board | Add _is_pos_on_board() to determine if a position is on the board
| Python | mit | EyuelAbebe/gamer,EyuelAbebe/gamer |
3671f6f1e3a2e518255a6a04d0aadf52d5fcca97 | tests/functions_tests/test_dropout.py | tests/functions_tests/test_dropout.py | import unittest
import numpy
import chainer
from chainer import cuda
from chainer import functions
from chainer import testing
from chainer.testing import attr
if cuda.available:
cuda.init()
class TestDropout(unittest.TestCase):
def setUp(self):
self.x = numpy.random.uniform(-1, 1, (2, 3)).astype... | import unittest
import numpy
import chainer
from chainer import cuda
from chainer import functions
from chainer import testing
from chainer.testing import attr
if cuda.available:
cuda.init()
class TestDropout(unittest.TestCase):
def setUp(self):
self.x = numpy.random.uniform(-1, 1, (2, 3)).astype... | Add unittest for type check during backward in TestDropout | Add unittest for type check during backward in TestDropout
| Python | mit | benob/chainer,truongdq/chainer,ronekko/chainer,sou81821/chainer,t-abe/chainer,anaruse/chainer,kashif/chainer,okuta/chainer,sinhrks/chainer,niboshi/chainer,jnishi/chainer,woodshop/chainer,elviswf/chainer,ktnyt/chainer,keisuke-umezawa/chainer,wkentaro/chainer,wkentaro/chainer,niboshi/chainer,cupy/cupy,1986ks/chainer,jfsa... |
5dcac8299e754a4209f6f4177eb0df8ecea914c1 | namelist.py | namelist.py | #!/usr/bin/env python
# Copyright 2015, Google Inc.
# Author: Dave Crossland (dave@understandinglimited.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
#
# http://www.apache.... | #!/usr/bin/env python
# Copyright 2015, Google Inc.
# Author: Dave Crossland (dave@understandinglimited.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
#
# http://www.apache.... | Format codepoints according to the Namelist spec. | [tools] Format codepoints according to the Namelist spec.
| Python | apache-2.0 | googlefonts/gftools,googlefonts/gftools |
8dcbb031aa00afc35900243142d8f49814834d19 | powerline/renderers/ipython.py | powerline/renderers/ipython.py | # vim:fileencoding=utf-8:noet
from powerline.renderers.shell import ShellRenderer
from powerline.theme import Theme
class IpythonRenderer(ShellRenderer):
'''Powerline ipython segment renderer.'''
escape_hl_start = '\x01'
escape_hl_end = '\x02'
def get_segment_info(self, segment_info):
r = self.segment_info.co... | # vim:fileencoding=utf-8:noet
from powerline.renderers.shell import ShellRenderer
from powerline.theme import Theme
class IpythonRenderer(ShellRenderer):
'''Powerline ipython segment renderer.'''
escape_hl_start = '\x01'
escape_hl_end = '\x02'
def get_segment_info(self, segment_info):
r = self.segment_info.co... | Make IPython renderer shutdown properly | Make IPython renderer shutdown properly
| Python | mit | S0lll0s/powerline,IvanAli/powerline,Liangjianghao/powerline,cyrixhero/powerline,blindFS/powerline,bezhermoso/powerline,blindFS/powerline,EricSB/powerline,keelerm84/powerline,QuLogic/powerline,cyrixhero/powerline,darac/powerline,magus424/powerline,cyrixhero/powerline,dragon788/powerline,prvnkumar/powerline,keelerm84/pow... |
7cbc6ae58357ef647a007e1b505884e523d924c2 | numba/tests/test_ctypes_call.py | numba/tests/test_ctypes_call.py | import os
import ctypes
from numba import *
@autojit(backend='ast', nopython=True)
def call_ctypes_func(func, value):
return func(value)
def test_ctypes_calls():
libc = ctypes.CDLL(ctypes.util.find_library('c'))
puts = libc.puts
puts.argtypes = [ctypes.c_char_p]
assert call_ctypes_func(puts, "He... | import os
import ctypes
from numba import *
@autojit(backend='ast', nopython=True)
def call_ctypes_func(func, value):
return func(value)
def test_ctypes_calls():
# Test puts for no segfault
libc = ctypes.CDLL(ctypes.util.find_library('c'))
puts = libc.puts
puts.argtypes = [ctypes.c_char_p]
c... | Fix ctypes call test for windows | Fix ctypes call test for windows
| Python | bsd-2-clause | sklam/numba,pitrou/numba,GaZ3ll3/numba,numba/numba,jriehl/numba,sklam/numba,IntelLabs/numba,IntelLabs/numba,jriehl/numba,pitrou/numba,shiquanwang/numba,gdementen/numba,stonebig/numba,pombredanne/numba,gmarkall/numba,cpcloud/numba,stonebig/numba,jriehl/numba,ssarangi/numba,gdementen/numba,stuartarchibald/numba,ssarangi/... |
65050e11fd951968b100640c503c0ca7999283c0 | templates/quantum_conf_template.py | templates/quantum_conf_template.py | import string
template = string.Template("""
[APISERVER]
api_server_ip = $__contrail_api_server_ip__
api_server_port = $__contrail_api_server_port__
multi_tenancy = $__contrail_multi_tenancy__
contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:... | import string
template = string.Template("""
[APISERVER]
api_server_ip = $__contrail_api_server_ip__
api_server_port = $__contrail_api_server_port__
multi_tenancy = $__contrail_multi_tenancy__
contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:... | Add the new contrail extension to neutron plugin config file | Add the new contrail extension to neutron plugin config file
Change-Id: I2a1e90a2ca31314b7a214943b0f312471b11da9f
| Python | apache-2.0 | Juniper/contrail-provisioning,Juniper/contrail-provisioning |
540a589a3d20b4841e9a9c936673cc30a2f0a9ff | csportal/portal/views.py | csportal/portal/views.py | from django.shortcuts import render
def home(request):
return render(request, 'portal/home.html')
| from django.shortcuts import render
def home(request):
return render(request, 'portal/home.html')
def about(request):
return render(request, 'portal/home.html')
| Add an a function(view) about which is going to render about page when it is requested | Add an a function(view) about which is going to render about page when it is requested
| Python | mit | utailab/cs-portal,utailab/cs-portal |
5e86c516927bca9089541fdc3b60616bee8ec117 | scripts/analytics/tabulate_emails.py | scripts/analytics/tabulate_emails.py | # -*- coding: utf-8 -*-
"""Scripts for counting recently added users by email domain; pushes results
to the specified project.
"""
import datetime
import collections
from cStringIO import StringIO
from dateutil.relativedelta import relativedelta
from framework.mongo import database
from website import models
from w... | # -*- coding: utf-8 -*-
"""Scripts for counting recently added users by email domain; pushes results
to the specified project.
"""
import datetime
import collections
from cStringIO import StringIO
from dateutil.relativedelta import relativedelta
from framework.mongo import database
from website import models
from w... | Make user metric criteria consistent. | Make user metric criteria consistent.
[Resolves #1768]
| Python | apache-2.0 | chennan47/osf.io,zachjanicki/osf.io,jolene-esposito/osf.io,haoyuchen1992/osf.io,Nesiehr/osf.io,cslzchen/osf.io,brianjgeiger/osf.io,RomanZWang/osf.io,zachjanicki/osf.io,felliott/osf.io,cwisecarver/osf.io,caneruguz/osf.io,GageGaskins/osf.io,pattisdr/osf.io,acshi/osf.io,fabianvf/osf.io,njantrania/osf.io,CenterForOpenScien... |
2ed36e3f99d0dfb1f66e141f96a0eec79a81c7a5 | tdb/concatenate.py | tdb/concatenate.py | import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--files', nargs='*', default=[], help="tsvs that will be concatenated")
parser.add_argument('-o', '--output', type=str, default="data/titers_complete.tsv")
def concat(files,out):
with open(out, 'w') as o:
for filename in files:
... | import argparse
parser = argparse.ArgumentParser()
parser.add_argument('files', nargs='+', default=[], help="tsvs that will be concatenated")
def concat(files):
for filename in files:
print "Concatenating and annotating %s." % (filename)
if "cdc" in filename.lower():
source = "cdc"
... | Change input method, write to stdout and fix minor issues. | Change input method, write to stdout and fix minor issues.
| Python | agpl-3.0 | blab/nextstrain-db,nextstrain/fauna,blab/nextstrain-db,nextstrain/fauna |
d5966f60491c408eede66221bc820e4ede93fc0c | pyramid_keystone/__init__.py | pyramid_keystone/__init__.py |
default_settings = [
('auth_url', str, 'http://localhost:5000/v3'),
('region', str, 'RegionOne'),
('user_domain_name', str, 'Default'),
('cacert', str, ''),
]
def parse_settings(settings):
parsed = {}
def populate(name, convert, default):
sname = '%s%s' % ('keystone.',... |
default_settings = [
('auth_url', str, 'http://localhost:5000/v3'),
('region', str, 'RegionOne'),
('user_domain_name', str, 'Default'),
('cacert', str, ''),
]
def parse_settings(settings):
parsed = {}
def populate(name, convert, default):
sname = '%s%s' % ('keystone.',... | Add directive allowing users to use our auth policy | Add directive allowing users to use our auth policy
| Python | isc | bertjwregeer/pyramid_keystone |
47f46e3237ba2f746193e9074136f805e71bacec | pysteps/cascade/interface.py | pysteps/cascade/interface.py |
from pysteps.cascade import decomposition, bandpass_filters
_cascade_methods = dict()
_cascade_methods['fft'] = decomposition.decomposition_fft
_cascade_methods['gaussian'] = bandpass_filters.filter_gaussian
_cascade_methods['uniform'] = bandpass_filters.filter_uniform
def get_method(name):
"""
Return a cal... | from pysteps.cascade import decomposition, bandpass_filters
_cascade_methods = dict()
_cascade_methods['fft'] = decomposition.decomposition_fft
_cascade_methods['gaussian'] = bandpass_filters.filter_gaussian
_cascade_methods['uniform'] = bandpass_filters.filter_uniform
def get_method(name):
"""
Return a call... | Raise exception on incorrect argument type | Raise exception on incorrect argument type
| Python | bsd-3-clause | pySTEPS/pysteps |
ef75047fa9bd0d4bc5dd6c263f399f446827daab | radar/lib/models/__init__.py | radar/lib/models/__init__.py | from radar.lib.models.cohorts import *
from radar.lib.models.common import *
from radar.lib.models.comorbidities import *
from radar.lib.models.diagnosis import *
from radar.lib.models.dialysis import *
from radar.lib.models.data_sources import *
from radar.lib.models.genetics import *
from radar.lib.models.hospitalisa... | from radar.lib.models.cohorts import *
from radar.lib.models.common import *
from radar.lib.models.comorbidities import *
from radar.lib.models.diagnosis import *
from radar.lib.models.dialysis import *
from radar.lib.models.data_sources import *
from radar.lib.models.family_history import *
from radar.lib.models.genet... | Add family history and pathology client-side | Add family history and pathology client-side
| Python | agpl-3.0 | renalreg/radar,renalreg/radar,renalreg/radar,renalreg/radar |
956cfc16cee4d4069fdf21f980b881c3fa1864d6 | office365/sharepoint/group.py | office365/sharepoint/group.py | from office365.runtime.client_object import ClientObject
from office365.runtime.odata.odata_path_parser import ODataPathParser
from office365.sharepoint.principal import Principal
from office365.runtime.resource_path_entry import ResourcePathEntry
class Group(Principal):
"""Represents a collection of users in a S... | from office365.runtime.client_object import ClientObject
from office365.runtime.odata.odata_path_parser import ODataPathParser
from office365.sharepoint.principal import Principal
from office365.runtime.resource_path_entry import ResourcePathEntry
class Group(Principal):
"""Represents a collection of users in a S... | Fix resource_path of Group resource | Fix resource_path of Group resource
| Python | mit | vgrem/SharePointOnline-REST-Python-Client,vgrem/Office365-REST-Python-Client |
3471dd3196c134f7aee35aa38370c93915be2197 | example/__init__.py | example/__init__.py |
import webapp2
class IntroHandler(webapp2.RequestHandler):
def get(self):
pass
app = webapp2.WSGIApplication([
('/', IntroHandler),
])
| #
# Copyright 2012 WebFilings, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | Add basic draft of example code. | Add basic draft of example code.
| Python | apache-2.0 | robertkluin/furious,Workiva/furious,rosshendrickson-wf/furious,andreleblanc-wf/furious,rosshendrickson-wf/furious,andreleblanc-wf/furious,beaulyddon-wf/furious,Workiva/furious,mattsanders-wf/furious,beaulyddon-wf/furious,mattsanders-wf/furious |
0e8cc65317e7c443b4319b028395951185ef80de | filebrowser/urls.py | filebrowser/urls.py | from django.conf.urls.defaults import *
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
# filebrowser urls
url(r'^browse/$', redirect_to, {'url': '/admin/business/photo/?_popup=1'}, name="fb_browse"),
url(r'^mkdir/', 'filebrowser.views.mkdir', name="fb_mkdir"),
url(r... | from django.conf.urls.defaults import *
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
# filebrowser urls
url(r'^browse/$', 'filebrowser.views.browse', name="fb_browse"),
url(r'^mkdir/', 'filebrowser.views.mkdir', name="fb_mkdir"),
url(r'^upload/', 'filebrowser.view... | Revert URL redirect (didn't work) | Revert URL redirect (didn't work)
| Python | bsd-3-clause | django-wodnas/django-filebrowser-no-grappelli,sandow-digital/django-filebrowser-no-grappelli-sandow,sandow-digital/django-filebrowser-no-grappelli-sandow,django-wodnas/django-filebrowser-no-grappelli,sandow-digital/django-filebrowser-no-grappelli-sandow,django-wodnas/django-filebrowser-no-grappelli |
32191547567e9ce0cdec954d0079fb18f85b38ce | requests_oauthlib/oauth2_auth.py | requests_oauthlib/oauth2_auth.py | from __future__ import unicode_literals
from oauthlib.oauth2 import WebApplicationClient, InsecureTransportError
from .utils import is_secure_transport
class OAuth2(object):
"""Adds proof of authorization (OAuth2 token) to the request."""
def __init__(self, client_id=None, client=None, token=None):
... | from __future__ import unicode_literals
from oauthlib.oauth2 import WebApplicationClient, InsecureTransportError
from oauthlib.oauth2 import is_secure_transport
class OAuth2(object):
"""Adds proof of authorization (OAuth2 token) to the request."""
def __init__(self, client_id=None, client=None, token=None):
... | Use newly exposed oauth2.is_secure_transport instead of duplicate. | Use newly exposed oauth2.is_secure_transport instead of duplicate.
| Python | isc | requests/requests-oauthlib,lucidbard/requests-oauthlib,dongguangming/requests-oauthlib,elafarge/requests-oauthlib,abhi931375/requests-oauthlib,gras100/asks-oauthlib,sigmavirus24/requests-oauthlib,jayvdb/requests-oauthlib,jsfan/requests-oauthlib,jayvdb/requests-oauthlib,singingwolfboy/requests-oauthlib |
bf4af59b4a9d0637d3743b6b6ff0eaef18dbb902 | flask_restplus/namespace.py | flask_restplus/namespace.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
class ApiNamespace(object):
def __init__(self, api, name, description=None, endpoint=None, path=None, **kwargs):
self.api = api
self.name = name
self.path = path or ('/' + name)
self.description = description
s... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
class ApiNamespace(object):
def __init__(self, api, name, description=None, endpoint=None, path=None, **kwargs):
self.api = api
self.name = name
self.path = path or ('/' + name)
self.description = description
s... | Hide resource if doc is False | Hide resource if doc is False | Python | mit | leiserfg/flask-restplus,luminusnetworks/flask-restplus,awiddersheim/flask-restplus,awiddersheim/flask-restplus,fixedd/flask-restplus,luminusnetworks/flask-restplus,fixedd/flask-restplus,leiserfg/flask-restplus |
69ac16b1501f9affa008c68d4b8197b320ae00b8 | cleanup.py | cleanup.py | #!/usr/bin/env python
from collections import defaultdict
import subprocess
import os
KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4)
def find_obsolete_images(images):
for image_name, versions in images.items():
if len(versions) > KEEP_LAST_VERSIONS:
obsolete_versions = sorted(ve... | #!/usr/bin/env python
from collections import defaultdict
import subprocess
import os
KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4)
def find_obsolete_images(images):
for image_name, versions in images.items():
if len(versions) > KEEP_LAST_VERSIONS:
obsolete_versions = sorted(ve... | Delete images instead of printing | Delete images instead of printing
| Python | mit | dreipol/cleanup-deis-images,dreipol/cleanup-deis-images |
c733126501690c7168d757ab9f14a4877e8544da | resolwe/flow/managers/workload_connectors/__init__.py | resolwe/flow/managers/workload_connectors/__init__.py | """.. Ignore pydocstyle D400.
===================
Workload Connectors
===================
The workload management system connectors are used as glue between the
Resolwe Manager and various concrete workload management systems that
might be used by it. Since the only functional requirement is job
submission, they can ... | """.. Ignore pydocstyle D400.
===================
Workload Connectors
===================
The workload management system connectors are used as glue between the
Resolwe Manager and various concrete workload management systems that
might be used by it. Since the only functional requirement is job
submission, they can ... | Add Kubernetes workload connector to documentation | Add Kubernetes workload connector to documentation
| Python | apache-2.0 | genialis/resolwe,genialis/resolwe |
b6fd1c849402d42bd00467406ae8c5dff42f2d03 | tests/test_style.py | tests/test_style.py | import pkg_resources
import unittest
class CodeStyleTestCase(unittest.TestCase):
def test_code_style(self):
flake8 = pkg_resources.load_entry_point('flake8', 'console_scripts', 'flake8')
try:
flake8([])
except SystemExit as e:
if e.code != 0:
self.fa... | import logging
import pkg_resources
import unittest
class CodeStyleTestCase(unittest.TestCase):
def test_code_style(self):
logger = logging.getLogger('flake8')
logger.setLevel(logging.ERROR)
flake8 = pkg_resources.load_entry_point('flake8', 'console_scripts', 'flake8')
try:
... | Decrease noise from code-style test | Decrease noise from code-style test
| Python | mit | ministryofjustice/django-moj-irat |
6518911dad0d22e878d618f9a9a1472de7a7ee1e | config/fuzz_pox_mesh.py | config/fuzz_pox_mesh.py | from experiment_config_lib import ControllerConfig
from sts.topology import MeshTopology
from sts.control_flow import Fuzzer, Interactive
from sts.input_traces.input_logger import InputLogger
from sts.invariant_checker import InvariantChecker
from sts.simulation_state import SimulationConfig
# Use POX as our controlle... | from experiment_config_lib import ControllerConfig
from sts.topology import MeshTopology
from sts.control_flow import Fuzzer, Interactive
from sts.input_traces.input_logger import InputLogger
from sts.invariant_checker import InvariantChecker
from sts.simulation_state import SimulationConfig
# Use POX as our controlle... | Use the mock discovery module | Use the mock discovery module
| Python | apache-2.0 | jmiserez/sts,ucb-sts/sts,ucb-sts/sts,jmiserez/sts |
7a324d85ef76604c919c2c7e2f38fbda17b3d01c | docs/examples/led_travis.py | docs/examples/led_travis.py | from travispy import TravisPy
from gpiozero import LED
from gpiozero.tools import negated
from time import sleep
from signal import pause
def build_passed(repo='RPi-Distro/python-gpiozero', delay=3600):
t = TravisPy()
r = t.repo(repo)
while True:
yield r.last_build_state == 'passed'
sleep(d... | from travispy import TravisPy
from gpiozero import LED
from gpiozero.tools import negated
from time import sleep
from signal import pause
def build_passed(repo):
t = TravisPy()
r = t.repo(repo)
while True:
yield r.last_build_state == 'passed'
red = LED(12)
green = LED(16)
green.source = build_pas... | Use source_delay instead of sleep, and tidy up a bit | Use source_delay instead of sleep, and tidy up a bit | Python | bsd-3-clause | RPi-Distro/python-gpiozero,waveform80/gpio-zero,MrHarcombe/python-gpiozero |
e979aab8ffdd5a2e86be7dd8fcacb5f10953a994 | src/SeleniumLibrary/utils/types.py | src/SeleniumLibrary/utils/types.py | # Copyright 2008-2011 Nokia Networks
# Copyright 2011-2016 Ryan Tomac, Ed Manlove and contributors
# Copyright 2016- Robot Framework Foundation
#
# 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 Licens... | # Copyright 2008-2011 Nokia Networks
# Copyright 2011-2016 Ryan Tomac, Ed Manlove and contributors
# Copyright 2016- Robot Framework Foundation
#
# 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 Licens... | Remove is_string because it exist in RF 2.9 | Remove is_string because it exist in RF 2.9
| Python | apache-2.0 | robotframework/SeleniumLibrary,emanlove/robotframework-selenium2library,emanlove/robotframework-selenium2library,rtomac/robotframework-selenium2library,emanlove/robotframework-selenium2library,robotframework/SeleniumLibrary,robotframework/SeleniumLibrary,rtomac/robotframework-selenium2library,rtomac/robotframework-sele... |
4e243ade9b96c5ea6e68c27593fb578c52c85f1a | huffman.py | huffman.py | class Node:
def __init__(self):
self.name = ''
self.weight = 0
self.code = ''
def initSet(self, name, weight):
self.name = name
self.weight = weight
| class Node:
def __init__(self):
self.name = ''
self.weight = 0
self.code = ''
def initSet(self, name, weight):
self.name = name
self.weight = weight
def setRoot(self, root):
self.root = root
def setLeft(self, left):
self.left = left
def se... | Add functions about setting the parent & children nodes and codes. | Add functions about setting the parent & children nodes and codes.
| Python | mit | hane1818/Algorithm_HW3_huffman_code |
d72e13f22eab7bf61b56b1d5fa33b006c5f13299 | tests/cli_test.py | tests/cli_test.py | from pork.cli import CLI
from mock import Mock
class TestCLI:
def it_has_a_data_attribute(self):
assert CLI().data is not None
| from pork.cli import CLI, main
from mock import Mock, patch
from StringIO import StringIO
patch.TEST_PREFIX = 'it'
@patch('pork.cli.Data')
class TestCLI:
def it_has_a_data_attribute(self, Data):
assert CLI().data is not None
def it_sets_keys(self, Data):
cli = CLI()
cli.start(['foo',... | Add test coverage for pork.cli. | Add test coverage for pork.cli.
| Python | mit | jimmycuadra/pork,jimmycuadra/pork |
09931cfbba746daf5127b6113187042341e3be3d | tests/conftest.py | tests/conftest.py | import pytest
@pytest.fixture
def credentials():
"""Fake set of MWS credentials"""
return {
"access_key": "AAAAAAAAAAAAAAAAAAAA",
"secret_key": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
"account_id": "AAAAAAAAAAAAAA",
}
| import pytest
@pytest.fixture
def access_key():
return "AAAAAAAAAAAAAAAAAAAA"
@pytest.fixture
def secret_key():
return "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
@pytest.fixture
def account_id():
return "AAAAAAAAAAAAAA"
@pytest.fixture
def timestamp():
return '2017-08-12T19:40:35Z'
@pytest.fix... | Add more pytest fixtures (access_key, secret_key, account_id, timestamp) | Add more pytest fixtures (access_key, secret_key, account_id, timestamp)
| Python | unlicense | GriceTurrble/python-amazon-mws,Bobspadger/python-amazon-mws |
17f6d104810f53a3ceac4943f3b80def3917b356 | textx/__init__.py | textx/__init__.py | # flake8: noqa
from textx.metamodel import metamodel_from_file, metamodel_from_str
from textx.model import get_children_of_type, get_parent_of_type, \
get_model, get_metamodel, get_children, get_location, textx_isinstance
from textx.exceptions import TextXError, TextXSyntaxError, \
TextXSemanticError, TextXRegi... | # flake8: noqa
from textx.metamodel import metamodel_from_file, metamodel_from_str
from textx.model import get_children_of_type, get_parent_of_type, \
get_model, get_metamodel, get_children, get_location, textx_isinstance
from textx.exceptions import TextXError, TextXSyntaxError, \
TextXSemanticError, TextXRegi... | Remove click dependent import from the main module. | Remove click dependent import from the main module.
This leads to import error when textX is installed without CLI support.
| Python | mit | igordejanovic/textX,igordejanovic/textX,igordejanovic/textX |
9619ecae61514bf1681425c503c38ccbe17f4b47 | src/commoner/registration/admin.py | src/commoner/registration/admin.py | from django.contrib import admin
from commoner.registration.models import PartialRegistration
class PartialRegistrationAdmin(admin.ModelAdmin):
list_filter = ('complete',)
admin.site.register(PartialRegistration, PartialRegistrationAdmin)
| from django.contrib import admin
from commoner.registration.models import PartialRegistration
class PartialRegistrationAdmin(admin.ModelAdmin):
list_filter = ('complete',)
fieldsets = (
(None, {
'fields':('last_name', 'first_name', 'email', 'complete', 'transaction_id', 'user'),
'descriptio... | Send welcome emails when registrations are added through the web interface. | Send welcome emails when registrations are added through the web
interface.
| Python | agpl-3.0 | cc-archive/commoner,cc-archive/commoner |
3426f160d24f98a897149110bb6b67891e73dcca | tests/test_gen_addons_table.py | tests/test_gen_addons_table.py | import os
import subprocess
import unittest
class TestGenAddonsTable(unittest.TestCase):
def test_1(self):
dirname = os.path.dirname(__file__)
cwd = os.path.join(dirname, 'test_repo')
gen_addons_table = os.path.join(dirname, '..', 'tools',
'gen_addo... | import os
import subprocess
import sys
def test_1():
dirname = os.path.dirname(__file__)
cwd = os.path.join(dirname, 'test_repo')
readme_filename = os.path.join(dirname, 'test_repo', 'README.md')
with open(readme_filename) as f:
readme_before = f.read()
readme_expected_filename = os.path.j... | Make gen_addons_table test generate coverage | Make gen_addons_table test generate coverage
This is done by invoking subprocess with sys.executable,
pytest-cov does the rest.
Also change test style to pytest instead of unittest.
| Python | agpl-3.0 | Yajo/maintainer-tools,Yajo/maintainer-tools,OCA/maintainer-tools,OCA/maintainer-tools,OCA/maintainer-tools,OCA/maintainer-tools,acsone/maintainer-tools,acsone/maintainer-tools,Yajo/maintainer-tools,acsone/maintainer-tools,acsone/maintainers-tools,Yajo/maintainer-tools,acsone/maintainer-tools,acsone/maintainers-tools,ac... |
8157ee43f31bd106d00c86ac4a7bc35a79c29e41 | django_payzen/app_settings.py | django_payzen/app_settings.py | """ Default payzen settings.
All settings should be set in the django settings file and not
directly in this file.
We deliberately do not set up default values here in order to
force user to setup explicitely the default behaviour."""
from django.conf import settings
PAYZEN_REQUEST_URL = 'https://secure.payzen.eu/v... | """ Default payzen settings.
All settings should be set in the django settings file and not
directly in this file.
We deliberately do not set up default values here in order to
force user to setup explicitely the default behaviour."""
from django.conf import settings
PAYZEN_REQUEST_URL = 'https://secure.payzen.eu/v... | Set essential payzen settings as mandatory for django_payzen. | Set essential payzen settings as mandatory for django_payzen.
| Python | mit | zehome/django-payzen,bsvetchine/django-payzen,zehome/django-payzen,bsvetchine/django-payzen |
80d1126418af0890a36a4bac9ddf53a2ab40e851 | cpp_coveralls/report.py | cpp_coveralls/report.py | from __future__ import absolute_import
from __future__ import print_function
import requests
import json
URL = 'https://coveralls.io/api/v1/jobs'
def post_report(coverage):
"""Post coverage report to coveralls.io."""
response = requests.post(URL, files={'json_file': json.dumps(coverage)})
try:
r... | from __future__ import absolute_import
from __future__ import print_function
import requests
import json
import os
URL = os.getenv('COVERALLS_ENDPOINT', 'https://coveralls.io') + "/api/v1/jobs"
def post_report(coverage):
"""Post coverage report to coveralls.io."""
response = requests.post(URL, files={'json_f... | Support COVERALLS_ENDPOINT for Enterprise usage | Support COVERALLS_ENDPOINT for Enterprise usage | Python | apache-2.0 | eddyxu/cpp-coveralls,eddyxu/cpp-coveralls |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.