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 |
|---|---|---|---|---|---|---|---|---|---|
56c0d2ea610aae35edfef2d242e0c4ca6a236a4d | crypto.py | crypto.py | from Crypto.Cipher import AES
import os
from file_io import *
from settings import *
def get_cipher(iv, text):
try:
key = read_file(KEY_FILE, 'rt').strip()
except IOError:
key = input(text)
return AES.new(key, AES.MODE_CBC, iv)
def encrypt(bytes):
iv = os.urandom(16)
c = get_ciphe... | from Crypto.Cipher import AES
import os
from settings import *
def get_cipher(iv, text):
try:
with open(KEY_FILE, 'rt') as f:
key = f.read().strip()
except IOError:
key = input(text)
return AES.new(key, AES.MODE_CBC, iv)
def encrypt(bytes):
iv = os.urandom(16)
c = get_... | Replace file_io usage with open | Replace file_io usage with open
| Python | unlicense | kvikshaug/pwkeeper |
a19a5dfacd09ffebe8fdc2f5edcbf1aec6d73751 | tests/django_settings.py | tests/django_settings.py | # Minimum settings that are needed to run django test suite
import os
import tempfile
SECRET_KEY = 'WE DONT CARE ABOUT IT'
if "postgresql" in os.getenv("TOX_ENV_NAME", ""):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
# Should be the same defined in .travis... | # Minimum settings that are needed to run django test suite
import os
import secrets
import tempfile
SECRET_KEY = secrets.token_hex()
if "postgresql" in os.getenv("TOX_ENV_NAME", ""):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
# Should be the same defined... | Use a different django secret key for each test run. | Use a different django secret key for each test run.
| Python | bsd-3-clause | smn/django-dirtyfields,romgar/django-dirtyfields |
0f688ac6b05caada0f2b72e5e6bc484c1b45ac04 | fmriprep/workflows/bold/__init__.py | fmriprep/workflows/bold/__init__.py | # -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
# pylint: disable=unused-import
"""
Pre-processing fMRI - BOLD signal workflows
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. automodule:: fmriprep.workflows.bold.base
.. automodu... | # -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
# pylint: disable=unused-import
"""
Pre-processing fMRI - BOLD signal workflows
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. automodule:: fmriprep.workflows.bold.base
.. automodu... | Update bold init for imports | Update bold init for imports
| Python | bsd-3-clause | poldracklab/fmriprep,oesteban/preprocessing-workflow,poldracklab/preprocessing-workflow,oesteban/fmriprep,poldracklab/preprocessing-workflow,poldracklab/fmriprep,oesteban/fmriprep,oesteban/preprocessing-workflow,oesteban/fmriprep,poldracklab/fmriprep |
7f93f3a8b8fb703588b7f1b5fee9856d0a597636 | tests/test_serialize.py | tests/test_serialize.py | from hypothesis import given
from hypothesis.strategies import binary
from aiortp.packet import rtphdr, pack_rtp, parse_rtp
from aiortp.packet import rtpevent, pack_rtpevent, parse_rtpevent
@given(binary(min_size=rtphdr.size, max_size=rtphdr.size + 1000))
def test_rtp_decode_inverts_encode(pkt):
assert pack_rtp(p... | from hypothesis import given
from hypothesis.strategies import binary
from aiortp.packet import rtphdr, pack_rtp, parse_rtp
from aiortp.packet import rtpevent, pack_rtpevent, parse_rtpevent
@given(binary(min_size=rtphdr.size, max_size=rtphdr.size + 1000))
def test_rtp_decode_inverts_encode(pkt):
assert pack_rtp(p... | Add test make sure rtpevent inside rtp parses | Add test make sure rtpevent inside rtp parses
| Python | apache-2.0 | vodik/aiortp |
c371d3663fc1de7d99246d97ec054c7da865e4cf | testshop/test_models.py | testshop/test_models.py | # -*- coding: utf-8
from __future__ import unicode_literals
from django.test import TestCase
from django.contrib.auth import get_user_model
from shop.models.defaults.address import ShippingAddress, BillingAddress # noqa
from shop.models.defaults.customer import Customer
class AddressTest(TestCase):
def setUp(se... | # -*- coding: utf-8
from __future__ import unicode_literals
from django.test import TestCase
from django.contrib.auth import get_user_model
from shop.models.defaults.address import ShippingAddress
from shop.models.defaults.customer import Customer
class AddressTest(TestCase):
def setUp(self):
super(Addre... | Address model testing coverage: 100% | Address model testing coverage: 100%
| Python | bsd-3-clause | jrief/django-shop,khchine5/django-shop,khchine5/django-shop,rfleschenberg/django-shop,rfleschenberg/django-shop,divio/django-shop,khchine5/django-shop,awesto/django-shop,awesto/django-shop,jrief/django-shop,rfleschenberg/django-shop,nimbis/django-shop,nimbis/django-shop,rfleschenberg/django-shop,khchine5/django-shop,aw... |
32a093a95bb1b94fba3ea36dc10b6e81086d9a5b | dbaas/dbaas_services/analyzing/tasks/analyze.py | dbaas/dbaas_services/analyzing/tasks/analyze.py | # -*- coding: utf-8 -*-
from dbaas.celery import app
from account.models import User
from logical.models import Database
from util.decorators import only_one
from simple_audit.models import AuditRequest
from dbaas_services.analyzing.integration import AnalyzeService
@app.task
@only_one(key="analyze_databases_service_... | # -*- coding: utf-8 -*-
import logging
from dbaas.celery import app
from account.models import User
from logical.models import Database
from util.decorators import only_one
from simple_audit.models import AuditRequest
from dbaas_services.analyzing.integration import AnalyzeService
from dbaas_services.analyzing.exceptio... | Check if service is working | Check if service is working
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service |
8fc6ba648347a48065ab2fb26f940dc92919feeb | bands/__init__.py | bands/__init__.py | import shutil
from cherrypy.lib.static import serve_file
from uber.common import *
from panels import *
from bands._version import __version__
from bands.config import *
from bands.models import *
import bands.model_checks
import bands.automated_emails
static_overrides(join(bands_config['module_root'], 'static'))
te... | import shutil
from cherrypy.lib.static import serve_file
from uber.common import *
from panels import *
from bands._version import __version__
from bands.config import *
from bands.models import *
import bands.model_checks
import bands.automated_emails
static_overrides(join(bands_config['module_root'], 'static'))
te... | Implement new python-based menu format | Implement new python-based menu format
| Python | agpl-3.0 | magfest/bands,magfest/bands |
ba649e4bce746f19712f127ac15e77345a5ec837 | parkings/api/public/parking_area_statistics.py | parkings/api/public/parking_area_statistics.py | from django.utils import timezone
from rest_framework import serializers, viewsets
from parkings.models import Parking, ParkingArea
from ..common import WGS84InBBoxFilter
class ParkingAreaStatisticsSerializer(serializers.ModelSerializer):
current_parking_count = serializers.SerializerMethodField()
def get_... | from django.db.models import Case, Count, When
from django.utils import timezone
from rest_framework import serializers, viewsets
from parkings.models import ParkingArea
from ..common import WGS84InBBoxFilter
class ParkingAreaStatisticsSerializer(serializers.ModelSerializer):
current_parking_count = serializers... | Improve parking area statistics performance | Improve parking area statistics performance
| Python | mit | tuomas777/parkkihubi |
23df1ed7a02f3c120a0d5075b27cc92f3e1b6429 | src/chime_dash/app/components/navbar.py | src/chime_dash/app/components/navbar.py | """Navigation bar view
"""
from typing import List
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.development.base_component import ComponentMeta
from penn_chime.defaults import Constants
from penn_chime.settings import DEFAULTS
from chime_dash.app.components.base import Compon... | """Navigation bar view
"""
from typing import List
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.development.base_component import ComponentMeta
from penn_chime.defaults import Constants
from penn_chime.settings import DEFAULTS
from chime_dash.app.components.base import Compon... | Fix nav at top of window. Use dark theme to distinguish from content. | Fix nav at top of window. Use dark theme to distinguish from content.
| Python | mit | CodeForPhilly/chime,CodeForPhilly/chime,CodeForPhilly/chime |
7ec28d5b8be40b505a20a4670857278ad41f760b | src/puzzle/puzzlepedia/puzzlepedia.py | src/puzzle/puzzlepedia/puzzlepedia.py | from IPython import display
from puzzle.puzzlepedia import prod_config, puzzle, puzzle_widget
_INITIALIZED = False
def parse(source, hint=None):
_init()
result = puzzle.Puzzle('first stage', source, hint=hint)
interact_with(result)
return result
def interact_with(puzzle):
_init()
display.display(puzzl... | from IPython import display
from puzzle.puzzlepedia import prod_config, puzzle, puzzle_widget
_INITIALIZED = False
def parse(source, hint=None, threshold=None):
_init()
result = puzzle.Puzzle('first stage', source, hint=hint, threshold=threshold)
interact_with(result)
return result
def interact_with(puzzl... | Allow "threshold" to be specified during parse(...). | Allow "threshold" to be specified during parse(...).
| Python | mit | PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge |
2c1cbdfcb28595e945e6069501652f0869733549 | bids/reports/report.py | bids/reports/report.py | """Generate publication-quality data acquisition methods section from BIDS dataset.
"""
from collections import Counter
from bids.reports import utils
class BIDSReport(object):
"""
Generates publication-quality data acquisition methods section from BIDS
dataset.
"""
def __init__(self, layout):
... | """Generate publication-quality data acquisition methods section from BIDS dataset.
"""
from __future__ import print_function
from collections import Counter
from bids.reports import utils
class BIDSReport(object):
"""
Generates publication-quality data acquisition methods section from BIDS
dataset.
... | Add future import for Py2. | Add future import for Py2.
| Python | mit | INCF/pybids |
bdacb243867e1d6cef3573fec383e9069e11523e | eche/tests/test_step1_raed_print.py | eche/tests/test_step1_raed_print.py | import pytest
from eche.reader import read_str
from eche.printer import print_str
import math
@pytest.mark.parametrize("test_input", [
'1',
'-1',
'0',
str(math.pi),
str(math.e)
])
def test_numbers(test_input):
assert print_str(read_str(test_input)) == test_input
@pytest.mark.parametrize("t... | import pytest
from eche.reader import read_str
from eche.printer import print_str
import math
@pytest.mark.parametrize("test_input", [
'1',
'-1',
'0',
str(math.pi),
str(math.e)
])
def test_numbers(test_input):
assert print_str(read_str(test_input)) == test_input
@pytest.mark.parametrize("t... | Add list with list test. | Add list with list test.
| Python | mit | skk/eche |
420a786fb9c5bf476e2c444b181161e75ca801f8 | glitter_news/admin.py | glitter_news/admin.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.contrib import admin
from adminsortable.admin import SortableAdmin
from glitter import block_admin
from glitter.admin import GlitterAdminMixin, GlitterPagePublishedFilter
from .models import Category, LatestN... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.contrib import admin
from adminsortable.admin import SortableAdmin
from glitter import block_admin
from glitter.admin import GlitterAdminMixin, GlitterPagePublishedFilter
from .models import Category, LatestN... | Move is_sticky field into post's advanced options | Move is_sticky field into post's advanced options
For #13
| Python | bsd-2-clause | blancltd/glitter-news |
221134b178bc4106bc39c7eb3120395c27473963 | json2csv_business.py | json2csv_business.py | import json
def main():
# print the header of output csv file
print 'business_id,city,latitude,longitude'
# for each entry in input json file print one csv row
for line in open("data/yelp_academic_dataset_business.json"):
input_json = json.loads(line)
business_id = input_json['busines... | import json
def main():
# print the header of output csv file
print 'business_id,name,city,latitude,longitude'
# for each entry in input json file print one csv row
for line in open("data/yelp_academic_dataset_business.json"):
input_json = json.loads(line)
business_id = input_json['bu... | Add business name to csv output | Add business name to csv output | Python | mit | aysent/yelp-photo-explorer |
af3a1ed1b1114ab85b16a687e0ba29e787c0722b | bookmarks/bookmarks.py | bookmarks/bookmarks.py | from flask import Flask
app = Flask(__name__)
app.config.from_object(__name__)
app.config.update(dict(
SECRET_KEY='development key',
USERNAME='admin',
PASSWORD='default'
))
| from flask import Flask
app = Flask(__name__)
app.config.from_object(__name__)
app.config.update(dict(
SECRET_KEY='development key',
USERNAME='admin',
PASSWORD='default'
))
@app.route('/', methods=['GET'])
def front_page():
return 'Hello, World!'
| Add route '/' with Hello World | Add route '/' with Hello World
| Python | apache-2.0 | byanofsky/bookmarks,byanofsky/bookmarks,byanofsky/bookmarks |
a74a0c0f2066008586114fd5b0908f67c11c0334 | sipa/blueprints/documents.py | sipa/blueprints/documents.py | # -*- coding: utf-8 -*-
from flask import Blueprint, send_file, abort
from os.path import isfile, realpath, join
bp_documents = Blueprint('documents', __name__)
@bp_documents.route('/images/<image>')
def show_image(image):
print("Trying to show image {}".format(image))
filename = realpath("content/images/{}... | # -*- coding: utf-8 -*-
from flask import Blueprint, send_file, abort, send_from_directory, current_app
from os.path import isfile, realpath, join
from flask.views import View
import os
bp_documents = Blueprint('documents', __name__)
class StaticFiles(View):
def __init__(self, directory):
self.directory... | Implement generic static file view | Implement generic static file view
Use the send_from_directory helper function from Flask which is used
to implement the static endpoint of Flask for our custom files
| Python | mit | MarauderXtreme/sipa,agdsn/sipa,lukasjuhrich/sipa,agdsn/sipa,MarauderXtreme/sipa,lukasjuhrich/sipa,agdsn/sipa,agdsn/sipa,lukasjuhrich/sipa,lukasjuhrich/sipa,MarauderXtreme/sipa |
ce13dd0fd049782531e939da9a5238a6f5493b8d | mpld3/test_plots/test_date_ticks.py | mpld3/test_plots/test_date_ticks.py | """Plot to test custom date axis tick locations and labels"""
from datetime import datetime
import matplotlib.pyplot as plt
import mpld3
def create_plot():
times = [datetime(2013, 12, i) for i in range(1, 20)]
ticks = [times[0], times[1], times[2], times[6], times[-2], times[-1]]
labels = [t.strftime("%Y-... | """
Plot to test custom date axis tick locations and labels
NOTE (@vladh): We may see different behaviour in mpld3 vs d3 for the y axis, because we never
specified exactly how we want the y axis formatted. This is ok.
"""
from datetime import datetime
import matplotlib.pyplot as plt
import mpld3
def create_plot():
... | Add note to misleading test | Add note to misleading test
| Python | bsd-3-clause | jakevdp/mpld3,mpld3/mpld3,jakevdp/mpld3,mpld3/mpld3 |
c029905a8ffad7fcf7ef70591dd0ad3f72365c09 | wagtail_uplift/wagtail_hooks.py | wagtail_uplift/wagtail_hooks.py | from django.conf.urls import url
from django.utils.html import format_html
from django.contrib.staticfiles.templatetags.staticfiles import static
from wagtail.core import hooks
from wagtail.admin.menu import MenuItem
@hooks.register('insert_global_admin_css')
def global_admin_css():
html = '<link rel="stylesheet"... | import django
from django.conf.urls import url
from django.utils.html import format_html
if django.VERSION[0] == "2":
from django.contrib.staticfiles.templatetags.staticfiles import static
elif django.VERSION[0] == "3":
from django.templatetags.static import static
from wagtail.core import hooks
from wagtail.ad... | Update static import to support Django 3 | Update static import to support Django 3
| Python | bsd-3-clause | l1f7/wagtail_uplift,l1f7/wagtail_uplift,l1f7/wagtail_uplift |
5657dd437af76ecccdb671a1a09a4c6f9874aab0 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jonas Gratz
# Copyright (c) 2015 Jonas Gratz
#
# License: MIT
#
"""This module exports the PerlEpages6 plugin class."""
import sublime
from SublimeLinter.lint import Linter, util
class PerlEpages6(Linter):
"""... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jonas Gratz
# Copyright (c) 2015 Jonas Gratz
#
# License: MIT
#
"""This module exports the PerlEpages6 plugin class."""
import sublime
from SublimeLinter.lint import Linter, util
class PerlEpages6(Linter):
"""... | Check if epages6 settings are configured | Check if epages6 settings are configured
| Python | mit | ePages-rnd/SublimeLinter-contrib-perl-epages6 |
46ba4f97d3ad2d673e8f3acb86d8c75905bc319f | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ben Edwards
# Copyright (c) 2015 Ben Edwards
#
# License: MIT
#
"""This module exports the PugLint plugin class."""
from SublimeLinter.lint import NodeLinter, util, highlight
class PugLint(NodeLinter):
"""Prov... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ben Edwards
# Copyright (c) 2015 Ben Edwards
#
# License: MIT
#
"""This module exports the PugLint plugin class."""
from SublimeLinter.lint import NodeLinter, util, highlight
class PugLint(NodeLinter):
"""Prov... | Move attribute to "selector" in defaults from "syntax", as suggested by SublimeLinter | Move attribute to "selector" in defaults from "syntax", as suggested by SublimeLinter
| Python | mit | benedfit/SublimeLinter-contrib-pug-lint,benedfit/SublimeLinter-contrib-jade-lint |
4bf01c350744e8cbf00750ec85d825f22e06dd29 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by NotSqrt
# Copyright (c) 2013 NotSqrt
#
# License: MIT
#
"""
This module exports the Shellcheck plugin class.
Example output with --format gcc
-:230:7: warning: Quote this to prevent word splitting. [SC2046]
-:230:7... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by NotSqrt
# Copyright (c) 2013 NotSqrt
#
# License: MIT
#
"""
This module exports the Shellcheck plugin class.
Example output with --format gcc
-:230:7: warning: Quote this to prevent word splitting. [SC2046]
-:230:7... | Handle new sublime syntax: bash | Handle new sublime syntax: bash
| Python | mit | SublimeLinter/SublimeLinter-shellcheck |
d8ae3ab5f6baf0ee965548f8df37e1a4b331a8aa | install_all_addons.py | install_all_addons.py | import bpy
# install and activate `emboss plane`
bpy.ops.wm.addon_install(filepath='emboss_plane.py')
bpy.ops.wm.addon_enable(module='emboss_plane')
# install and activate `name plate`
bpy.ops.wm.addon_install(filepath='name_plate.py')
bpy.ops.wm.addon_enable(module='name_plate')
# save user preferences
bpy.ops.wm.s... | import bpy
import os
# get current directory
current_dir = os.getcwd()
# install and activate `emboss plane`
emboss_plane_filepath = os.path.join(current_dir, 'emboss_plane.py')
bpy.ops.wm.addon_install(filepath=emboss_plane_filepath)
bpy.ops.wm.addon_enable(module='emboss_plane')
# install and activate `name plate`... | Update install script with full file paths | Update install script with full file paths
This is needed to make the script run on Windows. The `os` package is
used to make sure it will run under any OS.
| Python | mit | TactileUniverse/3D-Printed-Galaxy-Software |
d0136d302524ff08e33ebdbab835b499aeeb2c2c | kboard/board/models.py | kboard/board/models.py | from django.db import models
from django.core.urlresolvers import reverse
from django_summernote import models as summer_model
from django_summernote import fields as summer_fields
class Board(models.Model):
def get_absolute_url(self):
return reverse('board:post_list', args=[self.id])
slug = models.T... | from django.db import models
from django.core.urlresolvers import reverse
from django_summernote import models as summer_model
from django_summernote import fields as summer_fields
class Board(models.Model):
def get_absolute_url(self):
return reverse('board:post_list', args=[self.id])
slug = models.T... | Fix 'get_absolute_url()' refer to url | Fix 'get_absolute_url()' refer to url
| Python | mit | hyesun03/k-board,guswnsxodlf/k-board,hyesun03/k-board,darjeeling/k-board,kboard/kboard,cjh5414/kboard,cjh5414/kboard,guswnsxodlf/k-board,hyesun03/k-board,cjh5414/kboard,guswnsxodlf/k-board,kboard/kboard,kboard/kboard |
4f4ba39bf2d270ef1cb34afe1a5ebe7816d448b7 | manage.py | manage.py | #!/usr/bin/env python
from werkzeug import script
def make_app():
from cadorsfeed.application import CadorsFeed
return CadorsFeed()
def make_shell():
from cadorsfeed import utils
application = make_app()
return locals()
action_runserver = script.make_runserver(make_app, use_reloader=True)
actio... | #!/usr/bin/env python
from werkzeug import script
def make_app():
from cadorsfeed.application import CadorsFeed
return CadorsFeed()
def make_shell():
from cadorsfeed import utils
application = make_app()
return locals()
action_runserver = script.make_runserver(make_app, use_reloader=True, hostn... | Set hostname to '' so the server binds to all interfaces. | Set hostname to '' so the server binds to all interfaces.
| Python | mit | kurtraschke/cadors-parse,kurtraschke/cadors-parse |
7668ba1b467e2c48719fc6e3a53932ec1bfb9d18 | manage.py | manage.py | #!/usr/bin/env python
import os
import sys
# try using cdecimal for faster Decimal type
try:
import cdecimal
except ImportError:
pass
else:
sys.modules["decimal"] = cdecimal
print 'cdecimal'
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "evething.settings")
from ... | #!/usr/bin/env python
import os
import sys
# try using cdecimal for faster Decimal type
try:
import cdecimal
except ImportError:
pass
else:
sys.modules["decimal"] = cdecimal
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "evething.settings")
from django.core.managemen... | Remove the cdecimal debug print | Remove the cdecimal debug print
| Python | bsd-2-clause | cmptrgeekken/evething,madcowfred/evething,cmptrgeekken/evething,Gillingham/evething,Gillingham/evething,Gillingham/evething,cmptrgeekken/evething,madcowfred/evething,madcowfred/evething,madcowfred/evething,Gillingham/evething,cmptrgeekken/evething,cmptrgeekken/evething |
399430076227f42f5d168c5b2264933c32f4b52a | lib/ansible/release.py | lib/ansible/release.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | Update ansible version number to 2.8.0.dev0 | Update ansible version number to 2.8.0.dev0
| Python | mit | thaim/ansible,thaim/ansible |
4a1976c6aa21f519825c527c795e60dffa7f46db | githubsetupircnotifications.py | githubsetupircnotifications.py | """
github-setup-irc-notifications - Configure all repositories in an organization
with irc notifications
"""
import argparse
import getpass
import github3
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--username'),
parser.add_argument('--password'),
args = parser.parse_args()
... | """
github-setup-irc-notifications - Configure all repositories in an organization
with irc notifications
"""
import argparse
import getpass
import github3
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--username'),
parser.add_argument('--password'),
args = parser.parse_args()
... | Print message if signing in failed | Print message if signing in failed
| Python | mit | kragniz/github-setup-irc-notifications |
21b1206da978434e388e43a5258b9c0f09fc0e1e | tumblr/data/cleanup.py | tumblr/data/cleanup.py | import os
def remove_image_from_csvs(image):
for csv in os.listdir("."):
if csv[-4:] != ".csv":
continue
with open(csv, "r") as h:
lines = h.readlines()
modified = False
for x in range(len(lines)):
if image in lines[x]:
del lines[x... | import os
def remove_image_from_csvs(image):
for csv in os.listdir("."):
if csv[-4:] != ".csv":
continue
with open(csv, "r") as h:
lines = h.readlines()
modified = False
for x in range(len(lines)):
if image in lines[x]:
lines[x] = ... | Add suffixes to all gifs | Add suffixes to all gifs
| Python | mit | albertyw/devops-reactions-index,albertyw/devops-reactions-index,albertyw/reaction-pics,albertyw/reaction-pics,albertyw/reaction-pics,albertyw/devops-reactions-index,albertyw/devops-reactions-index,albertyw/reaction-pics |
ecd43e2d3679759d2ee389b35752cb8db18c5b22 | microdrop/microdrop.py | microdrop/microdrop.py | """
Copyright 2011 Ryan Fobel
This file is part of Microdrop.
Microdrop is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
Foundation, either version 3 of the License, or
(at your option) any later version.
Microdrop is distributed in the hope... | """
Copyright 2011 Ryan Fobel
This file is part of Microdrop.
Microdrop is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
Foundation, either version 3 of the License, or
(at your option) any later version.
Microdrop is distributed in the hope... | Change dir to allow script to be run from anywhere | Change dir to allow script to be run from anywhere
| Python | bsd-3-clause | wheeler-microfluidics/microdrop |
78ec7d5336eb65ff845da7ea9f93d34b402f5a0f | ironic/drivers/drac.py | ironic/drivers/drac.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | Add the PXE VendorPassthru interface to PXEDracDriver | Add the PXE VendorPassthru interface to PXEDracDriver
Without the PXE VendorPassthru interface to expose the "pass_deploy_info"
method in the vendor_passthru endpoint of the API the DRAC it can't
continue the deployment after the ramdisk is booted.
Closes-Bug: #1379705
Change-Id: I21042cbb95a486742abfcb430471d01cd73b... | Python | apache-2.0 | NaohiroTamura/ironic,SauloAislan/ironic,openstack/ironic,pshchelo/ironic,naototty/vagrant-lxc-ironic,ramineni/myironic,bacaldwell/ironic,openstack/ironic,rackerlabs/ironic,froyobin/ironic,rdo-management/ironic,pshchelo/ironic,ionutbalutoiu/ironic,Tan0/ironic,hpproliant/ironic,supermari0/ironic,dims/ironic,naototty/vagr... |
fa20d5b6a9b636fec7fc542cf899bf86c00dd8de | bakery/static_urls.py | bakery/static_urls.py | from django.conf import settings
from django.conf.urls import patterns, url
urlpatterns = patterns(
"bakery.static_views",
url(r"^(.*)$", "serve", {
"document_root": settings.BUILD_DIR,
'show_indexes': True,
'default': 'index.html'
}),
)
| from django.conf import settings
from django.conf.urls import url
from bakery.static_views import serve
urlpatterns = [
url(r"^(.*)$", serve, {
"document_root": settings.BUILD_DIR,
'show_indexes': True,
'default': 'index.html'
}),
]
| Upgrade to Django 1.10 style url patterns | Upgrade to Django 1.10 style url patterns
| Python | mit | datadesk/django-bakery,stvkas/django-bakery,stvkas/django-bakery,datadesk/django-bakery,datadesk/django-bakery,stvkas/django-bakery |
8d93082178200834a3df1b09d08cd53073eb07fe | coverage_diff.py | coverage_diff.py | import re
filename_matcher = re.compile(r'^\+\+\+ b/([\w/\._]+)\s+.+$')
diff_line_matcher = re.compile(r'^@@ -\d+,\d+ \+(\d+),(\d+) @@$')
def report_diffs(diff):
for line in diff:
name_match = filename_matcher.match(line)
if name_match:
filename = name_match.group(1)
conti... | import os
import re
filename_matcher = re.compile(r'^\+\+\+ b/([\w/\._]+)\s+.+$')
diff_line_matcher = re.compile(r'^@@ -\d+,\d+ \+(\d+),(\d+) @@$')
def report_diffs(diff):
for line in diff:
name_match = filename_matcher.match(line)
if name_match:
filename = name_match.group(1)
... | Check that coverage file exists | Check that coverage file exists
| Python | apache-2.0 | caio2k/RIDE,fingeronthebutton/RIDE,HelioGuilherme66/RIDE,HelioGuilherme66/RIDE,robotframework/RIDE,fingeronthebutton/RIDE,caio2k/RIDE,robotframework/RIDE,fingeronthebutton/RIDE,robotframework/RIDE,robotframework/RIDE,HelioGuilherme66/RIDE,HelioGuilherme66/RIDE,caio2k/RIDE |
3a1005de48a0883853c632b17220f2331bdc7017 | primes.py | primes.py | #!/usr/bin/env python
""" Tools for checking and generating prime numbers. """
import math
def is_prime(num):
""" Test if a number is prime. """
if num < 2:
return False
# take advantage of the speedup gained by only checking the sqrt
sqrt = int(math.sqrt(num))
# use xrange to generate ... | #!/usr/bin/env python
""" Tools for checking and generating prime numbers. """
import math
def is_prime(num):
""" Test if a number is prime. """
if num < 2:
return False
# take advantage of the speedup gained by only checking the sqrt
sqrt = int(math.sqrt(num))
# use xrange to generate ... | Add tests and a bug fix found by tests. | Add tests and a bug fix found by tests.
Since small numbers might have a sqrt == 2 add +1 to the range used for testing.
| Python | mit | smillet15/project-euler |
e4c5ff6901fe7652c7f76f67189058de76406406 | casepro/cases/forms.py | casepro/cases/forms.py | from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from casepro.msgs.models import Label
from .models import Partner
class PartnerUpdateForm(forms.ModelForm):
labels = forms.ModelMultipleChoiceField(label=_("Can Access"),
... | from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from casepro.msgs.models import Label
from .models import Partner
class BasePartnerForm(forms.ModelForm):
description = forms.CharField(label=_("Description"), max_length=255, required=False,... | Tweak partner form to use textarea for description | Tweak partner form to use textarea for description
| Python | bsd-3-clause | praekelt/casepro,xkmato/casepro,rapidpro/casepro,praekelt/casepro,rapidpro/casepro,rapidpro/casepro,praekelt/casepro,xkmato/casepro |
a75c51594e225fbada37f1be23cf2de581da29a4 | keeper/tasks/dashboardbuild.py | keeper/tasks/dashboardbuild.py | from __future__ import annotations
from typing import TYPE_CHECKING
from celery.utils.log import get_task_logger
from keeper.celery import celery_app
from keeper.models import Product
from keeper.services.dashboard import build_dashboard as build_dashboard_svc
if TYPE_CHECKING:
import celery.task
__all__ = ["b... | from __future__ import annotations
from typing import TYPE_CHECKING
from celery.utils.log import get_task_logger
from keeper.celery import celery_app
from keeper.models import Product
from keeper.services.dashboard import build_dashboard as build_dashboard_svc
if TYPE_CHECKING:
import celery.task
__all__ = ["b... | Fix getting product in build_dashboard task | Fix getting product in build_dashboard task
| Python | mit | lsst-sqre/ltd-keeper,lsst-sqre/ltd-keeper |
faf1535fcc6c743345485cd388be8979cad3dec2 | aspen/__main__.py | aspen/__main__.py | """
python -m aspen
===============
Aspen ships with a server (wsgiref.simple_server) that is
suitable for development and testing. It can be invoked via:
python -m aspen
though even for development you'll likely want to specify a
project root, so a more likely incantation is:
ASPEN_PROJECT_ROOT=/path/to/w... | """
python -m aspen
===============
Aspen ships with a server (wsgiref.simple_server) that is
suitable for development and testing. It can be invoked via:
python -m aspen
though even for development you'll likely want to specify a
project root, so a more likely incantation is:
ASPEN_PROJECT_ROOT=/path/to/w... | Support PORT envvar from `python -m aspen` | Support PORT envvar from `python -m aspen`
| Python | mit | gratipay/aspen.py,gratipay/aspen.py |
c1e6b61b6da9f17f11ce41bbcdaad61fadc075db | serenata_toolbox/datasets/remote.py | serenata_toolbox/datasets/remote.py | import os
from functools import partial
import boto3
from decouple import config
from serenata_toolbox import log
from serenata_toolbox.datasets.contextmanager import status_message
class RemoteDatasets:
def __init__(self):
self.client = None
self.credentials = {
'aws_access_key_id'... | import os
from functools import partial
import boto3
from decouple import config
from serenata_toolbox import log
from serenata_toolbox.datasets.contextmanager import status_message
class RemoteDatasets:
def __init__(self):
self.client = None
self.credentials = {
'aws_access_key_id'... | Make Amazon keys non required | Make Amazon keys non required
| Python | mit | datasciencebr/serenata-toolbox |
b202e1cc5e6c5aa65c3ed22ad1e78ec505fa36c4 | cmsplugin_rst/forms.py | cmsplugin_rst/forms.py | from cmsplugin_rst.models import RstPluginModel
from django import forms
help_text = '<a href="http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html">Reference</a>'
class RstPluginForm(forms.ModelForm):
body = forms.CharField(
widget=forms.Textarea(attrs={
'rows':... | from cmsplugin_rst.models import RstPluginModel
from django import forms
help_text = '<a href="http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html">Reference</a>'
class RstPluginForm(forms.ModelForm):
body = forms.CharField(
widget=forms.Textarea(attrs={
'rows':... | Add "fields" attribute to ModelForm. | Add "fields" attribute to ModelForm.
| Python | bsd-3-clause | pakal/cmsplugin-rst,ojii/cmsplugin-rst |
31ec9a0ae45c42c79f0e2edba3f11fc0578f33c4 | orchard/errors/e500.py | orchard/errors/e500.py | # -*- coding: utf-8 -*-
"""
This module sets up the view for handling ``500 Internal Server Error`` errors.
"""
import flask
import flask_classful
from orchard.errors import blueprint
class Error500View(flask_classful.FlaskView):
"""
View for ``500 Internal Server Error`` errors.
"""
traili... | # -*- coding: utf-8 -*-
"""
This module sets up the view for handling ``500 Internal Server Error`` errors.
"""
import datetime
import flask
import flask_classful
from orchard.errors import blueprint
class Error500View(flask_classful.FlaskView):
"""
View for ``500 Internal Server Error`` errors.
... | Send mail to admins on all internal server errors. | Send mail to admins on all internal server errors.
| Python | mit | BMeu/Orchard,BMeu/Orchard |
aba13a6b443922dd4f4e97b252c073ab23a223c4 | awesomeshop/shop/models/category.py | awesomeshop/shop/models/category.py | # -*- coding: utf8 -*-
# Copyright 2015 Sébastien Maccagnoni-Munch
#
# This file is part of AwesomeShop.
#
# AwesomeShop 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,... | # -*- coding: utf8 -*-
# Copyright 2015 Sébastien Maccagnoni-Munch
#
# This file is part of AwesomeShop.
#
# AwesomeShop 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,... | Make categories easier to request | Make categories easier to request
| Python | agpl-3.0 | tiramiseb/awesomeshop,tiramiseb/awesomeshop,tiramiseb/awesomeshop,tiramiseb/awesomeshop |
b456e982e1cbc902fa1aefaf221b058edb6c778f | backend/uclapi/oauth/app_helpers.py | backend/uclapi/oauth/app_helpers.py | from binascii import hexlify
import os
def generate_user_token():
key = hexlify(os.urandom(30)).decode()
dashes_key = ""
for idx, char in enumerate(key):
if idx % 15 == 0 and idx != len(key)-1:
dashes_key += "-"
else:
dashes_key += char
final = "uc... | from binascii import hexlify
import os
import textwrap
def generate_user_token():
key = hexlify(os.urandom(30)).decode()
dashes_key = ""
'-'.join(textwrap.wrap(key, 15))
final = "uclapi-user" + dashes_key
return final
def generate_random_verification_code():
key = hexlify(o... | Clean up verification code logic, as per @jermenkoo's feedback | Clean up verification code logic, as per @jermenkoo's feedback
| Python | mit | uclapi/uclapi,uclapi/uclapi,uclapi/uclapi,uclapi/uclapi |
dfdb824eb1327a270e1c167e2ed5e161026858ea | antxetamedia/multimedia/handlers.py | antxetamedia/multimedia/handlers.py | from boto.s3.connection import S3Connection
from boto.s3.bucket import Bucket
from boto.exception import S3ResponseError, S3CreateError
from django.conf import settings
def upload(user, passwd, bucket, metadata, key, fd):
conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False)
while bucket... | from boto.s3.connection import S3Connection
from boto.s3.bucket import Bucket
from boto.exception import S3ResponseError, S3CreateError
from django.conf import settings
def upload(user, passwd, bucket, metadata, key, fd):
conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False)
while bucket... | Break lowdly on unicode errors | Break lowdly on unicode errors
| Python | agpl-3.0 | GISAElkartea/antxetamedia,GISAElkartea/antxetamedia,GISAElkartea/antxetamedia |
918df7244162581fb57f301ccf6a4bf4b96ce541 | npc/formatters/__init__.py | npc/formatters/__init__.py | from . import markdown, json
| """
Character listing formatters
These modules encapsulate the logic needed to create a character listing in
various formats. Each module has a single `dump` entry point which accepts, at
minimum, the characters to list and where to put them. Other args are available
in each linter.
"""
from . import markdown, json
| Add docstring to formatters package | Add docstring to formatters package
| Python | mit | aurule/npc,aurule/npc |
8a9e58d2170e3f06228cbc0257d41f0c969da957 | tangled/website/resources.py | tangled/website/resources.py | from tangled.web import Resource, represent
from tangled.site.resources.entry import Entry
class Docs(Entry):
@represent('text/html', template_name='tangled.website:templates/docs.mako')
def GET(self):
static_dirs = self.app.get_all('static_directory', as_dict=True)
links = []
for pr... | from tangled.web import Resource, config
from tangled.site.resources.entry import Entry
class Docs(Entry):
@config('text/html', template_name='tangled.website:templates/docs.mako')
def GET(self):
static_dirs = self.app.get_all('static_directory', as_dict=True)
links = []
for prefix, ... | Replace @represent w/ @config throughout | Replace @represent w/ @config throughout
New name, same functionality.
| Python | mit | TangledWeb/tangled.website |
70c9b92b72edb4612bc05d166c6e1c8539c8c076 | opps/article/models.py | opps/article/models.py | # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Article
from opps.core.models.image import Image
from opps.core.models import Source
class Post(Article):
images = models.ManyToManyField(Image, null=True, blank=True,
... | # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Article
from opps.image.models import Image
from opps.core.models import Source
class Post(Article):
images = models.ManyToManyField(Image, null=True, blank=True,
... | Change namespace image app, use opps image | Change namespace image app, use opps image
| Python | mit | williamroot/opps,opps/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,opps/opps,YACOWS/opps,opps/opps,YACOWS/opps,opps/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,YACOWS/opps |
6dfddd2502ea3ea2682f6caa8824768987d477f3 | facilities/tests/test_pracititioner_models.py | facilities/tests/test_pracititioner_models.py | from django.test import TestCase
from model_mommy import mommy
from ..models import (
PracticeType,
Speciality,
Qualification,
PractitionerQualification,
PractitionerContact,
PractitionerFacility,
Practitioner,
ServiceCategory,
Option,
Service,
FacilityService,
ServiceO... | from django.test import TestCase
from model_mommy import mommy
from ..models import (
PracticeType,
Speciality,
Qualification,
PractitionerQualification,
PractitionerContact,
PractitionerFacility,
Practitioner,
ServiceCategory,
Option,
Service,
FacilityService,
ServiceO... | Add tests for inspection reports and cover report templates. | Add tests for inspection reports and cover report templates.
| Python | mit | urandu/mfl_api,urandu/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,urandu/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,urandu/mfl_api |
404477f4414b921d127a6744f60cddad6cbdeca1 | scrape.py | scrape.py | import discord
import asyncio
from tqdm import tqdm
from sys import argv
script, fileName = argv
client = discord.Client()
@client.event
async def on_ready():
print('Connection successful.')
print('ID: ' + client.user.id)
print('-----')
target = open(fileName, 'w')
print(fileName, 'h... | import discord
import asyncio
from tqdm import tqdm
#from sys import argv
import argparse
parser = argparse.ArgumentParser(description='Discord channel scraper')
requiredNamed = parser.add_argument_group('Required arguments:')
requiredNamed.add_argument('-c', '--channel', type=str, help='Channel to scrape. Req... | Change to use argparse to parse arguments | Change to use argparse to parse arguments
| Python | mit | suclearnub/discordgrapher |
32d9f627e9d592a693e7cc3e778463ebb6dd796d | busstops/management/commands/correct_operator_regions.py | busstops/management/commands/correct_operator_regions.py | from django.core.management.base import BaseCommand
from busstops.models import Operator, Region
class Command(BaseCommand):
@staticmethod
def maybe_move_operator(operator, regions)
if bool(regions) and operator.region not in regions:
if len(regions) == 1:
print 'moving', o... | from django.core.management.base import BaseCommand
from busstops.models import Operator, Region
class Command(BaseCommand):
@staticmethod
def maybe_move_operator(operator, regions):
if bool(regions) and operator.region not in regions:
if len(regions) == 1:
print 'moving', ... | Fix rough command for correcting operator regions | Fix rough command for correcting operator regions
| Python | mpl-2.0 | jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk,jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,jclgoodwin/bustimes.org.uk |
3498ca5117a35d61a5b539067b7ac743497cf8c7 | tests/test_helpers.py | tests/test_helpers.py | """
Tests for our tests helpers 8-}
"""
import os
import sys
from helpers import ArgvContext, EnvironContext
def test_argv_context():
"""
Test if ArgvContext sets the right argvs and resets to the old correctly
"""
old = sys.argv
new = ["Alice", "Bob", "Chris", "Daisy"]
assert sys.argv == o... | """
Tests for our tests helpers 8-}
"""
import os
import sys
from helpers import ArgvContext, EnvironContext
def test_argv_context():
"""
Test if ArgvContext sets the right argvs and resets to the old correctly
"""
old = sys.argv
new = ["Alice", "Bob", "Chris", "Daisy"]
assert sys.argv == o... | Make environ context helper test more accurate | Make environ context helper test more accurate
| Python | bsd-3-clause | mdgart/sentrylogs |
6b2ac1d6be094eddc6a940eb1dafa32e483a6b7e | ereuse_devicehub/resources/device/peripheral/settings.py | ereuse_devicehub/resources/device/peripheral/settings.py | import copy
from ereuse_devicehub.resources.device.schema import Device
from ereuse_devicehub.resources.device.settings import DeviceSubSettings
class Peripheral(Device):
type = {
'type': 'string',
'allowed': {'Router', 'Switch', 'Printer', 'Scanner', 'MultifunctionPrinter', 'Terminal', 'HUB', 'S... | import copy
from ereuse_devicehub.resources.device.schema import Device
from ereuse_devicehub.resources.device.settings import DeviceSubSettings
class Peripheral(Device):
type = {
'type': 'string',
'allowed': {
'Router', 'Switch', 'Printer', 'Scanner', 'MultifunctionPrinter', 'Termina... | Add new types of peripherals | Add new types of peripherals
| Python | agpl-3.0 | eReuse/DeviceHub,eReuse/DeviceHub |
a8112a8ee3723d5ae097998efc7c43bd27cbee95 | engineer/processors.py | engineer/processors.py | # coding=utf-8
import logging
import subprocess
from path import path
from engineer.conf import settings
__author__ = 'tyler@tylerbutler.com'
logger = logging.getLogger(__name__)
# Helper function to preprocess LESS files on demand
def preprocess_less(file):
input_file = path(settings.OUTPUT_CACHE_DIR / settings... | # coding=utf-8
import logging
import platform
import subprocess
from path import path
from engineer.conf import settings
__author__ = 'tyler@tylerbutler.com'
logger = logging.getLogger(__name__)
# Helper function to preprocess LESS files on demand
def preprocess_less(file):
input_file = path(settings.OUTPUT_CACH... | Handle LESS preprocessor errors more gracefully. | Handle LESS preprocessor errors more gracefully.
| Python | mit | tylerbutler/engineer,tylerbutler/engineer,tylerbutler/engineer |
70f4c55d760552829a86b30baa6d6eac3f6dc47f | billy/bin/commands/loaddistricts.py | billy/bin/commands/loaddistricts.py | import os
import logging
import unicodecsv
from billy.core import settings, db
from billy.bin.commands import BaseCommand
logger = logging.getLogger('billy')
class LoadDistricts(BaseCommand):
name = 'loaddistricts'
help = 'Load in the Open States districts'
def add_args(self):
self.add_argument... | import os
import logging
import unicodecsv
from billy.core import settings, db
from billy.bin.commands import BaseCommand
logger = logging.getLogger('billy')
class LoadDistricts(BaseCommand):
name = 'loaddistricts'
help = 'Load in the Open States districts'
def add_args(self):
self.add_argument... | Use division_id in place of bounary_id | Use division_id in place of bounary_id
| Python | bsd-3-clause | loandy/billy,openstates/billy,openstates/billy,sunlightlabs/billy,sunlightlabs/billy,openstates/billy,mileswwatkins/billy,sunlightlabs/billy,mileswwatkins/billy,loandy/billy,loandy/billy,mileswwatkins/billy |
25061826bb3316d0fb25cfae0e5d36a0f329f803 | bayesian_jobs/handlers/clean_postgres.py | bayesian_jobs/handlers/clean_postgres.py | from selinon import StoragePool
from cucoslib.models import WorkerResult, Analysis
from .base import BaseHandler
class CleanPostgres(BaseHandler):
""" Clean JSONB columns in Postgres """
def execute(self):
s3 = StoragePool.get_connected_storage('S3Data')
start = 0
while True:
... | from selinon import StoragePool
from cucoslib.models import WorkerResult, Analysis
from .base import BaseHandler
class CleanPostgres(BaseHandler):
""" Clean JSONB columns in Postgres """
def execute(self):
s3 = StoragePool.get_connected_storage('S3Data')
start = 0
while True:
... | Fix exception when task result is null | Fix exception when task result is null
| Python | apache-2.0 | fabric8-analytics/fabric8-analytics-jobs,fabric8-analytics/fabric8-analytics-jobs |
47bb8e983dad168451d65c0032f5568357a8d359 | battlesnake/plugins/imc2/triggers.py | battlesnake/plugins/imc2/triggers.py | import re
from battlesnake.core.triggers import TriggerTable
from battlesnake.core.triggers import Trigger
from battlesnake.plugins.imc2 import imc2
from battlesnake.plugins.imc2.channel_map import MUX_TO_IMC2_CHANNEL_MAP
class ChannelMessageTrigger(Trigger):
"""
Tries to identify potential IMC2 channel acti... | import re
from battlesnake.core.triggers import TriggerTable
from battlesnake.core.triggers import Trigger
from battlesnake.plugins.imc2 import imc2
from battlesnake.plugins.imc2.channel_map import MUX_TO_IMC2_CHANNEL_MAP
class ChannelMessageTrigger(Trigger):
"""
Tries to identify potential IMC2 channel acti... | Adjust IMC2 trigger regex to handle multiple colons correctly. | Adjust IMC2 trigger regex to handle multiple colons correctly.
| Python | bsd-3-clause | gtaylor/btmux_battlesnake |
f6ddb5b76265d7597568d6169ed877e04c565f4a | games/managers.py | games/managers.py | from django.db.models import Manager
class ScreenshotManager(Manager):
def published(self):
return self.get_query_set().filter(published=True)
| from django.db.models import Manager
class ScreenshotManager(Manager):
def published(self):
return self.get_query_set().filter(published=True).order_by('uploaded_at')
| Order screenshots by ascending upload time in the front-end | Order screenshots by ascending upload time in the front-end
So that it's easy to order them intentionally. :)
... Until we come up with a better ordering solution, with weights or
something.
| Python | agpl-3.0 | lutris/website,Turupawn/website,lutris/website,Turupawn/website,Turupawn/website,lutris/website,Turupawn/website,lutris/website |
ab69aaf5fecf429c99201db4cbcdab47c1afdd46 | server.py | server.py | import socket
def server():
server_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
server_socket.bind(('127.0.0.1', 50000))
server_socket.listen(10)
print "listening..."
try:
while True:
conn, addr = server_socket.accept()
... | import socket
def server():
server_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
server_socket.bind(('127.0.0.1', 50000))
server_socket.listen(10)
print "listening..."
try:
while True:
conn, addr = server_socket.accept()
... | Add Functionality for HTTP requests | Add Functionality for HTTP requests
| Python | mit | nbeck90/network_tools |
448f1201a36de8ef41dadbb63cbea874dd7d5878 | wechatpy/utils.py | wechatpy/utils.py | from __future__ import absolute_import, unicode_literals
import hashlib
import six
class ObjectDict(dict):
def __getattr__(self, key):
if key in self:
return self[key]
return None
def __setattr__(self, key, value):
self[key] = value
def check_signature(token, signature,... | from __future__ import absolute_import, unicode_literals
import hashlib
import six
class ObjectDict(dict):
def __getattr__(self, key):
if key in self:
return self[key]
return None
def __setattr__(self, key, value):
self[key] = value
def check_signature(token, signature,... | Fix test error on Python 3 | Fix test error on Python 3
| Python | mit | cloverstd/wechatpy,wechatpy/wechatpy,EaseCloud/wechatpy,mruse/wechatpy,cysnake4713/wechatpy,cysnake4713/wechatpy,zhaoqz/wechatpy,navcat/wechatpy,zaihui/wechatpy,Luckyseal/wechatpy,messense/wechatpy,chenjiancan/wechatpy,chenjiancan/wechatpy,Luckyseal/wechatpy,tdautc19841202/wechatpy,navcat/wechatpy,Dufy/wechatpy,jxtech/... |
915c59f1e8e1919555d6b3c8de5fbc34cd56e414 | tingbot/platform_specific/__init__.py | tingbot/platform_specific/__init__.py | import platform, os
def is_running_on_tingbot():
"""
Return True if running as a tingbot.
"""
# TB_RUN_ON_LCD is an environment variable set by tbprocessd when running tingbot apps.
return 'TB_RUN_ON_LCD' in os.environ
def no_op(*args, **kwargs):
pass
def no_op_returning(return_value):
de... | import sys, os
def is_running_on_tingbot():
"""
Return True if running as a tingbot.
"""
# TB_RUN_ON_LCD is an environment variable set by tbprocessd when running tingbot apps.
return 'TB_RUN_ON_LCD' in os.environ
def no_op(*args, **kwargs):
pass
def no_op_returning(return_value):
def inn... | Use sys.platform to look at the current platform | Use sys.platform to look at the current platform
Avoids a uname system call
| Python | bsd-2-clause | furbrain/tingbot-python |
76d9ce8638ad7e5e124a9f647f174c2a3adbc426 | src/zeit/cms/generation/evolve14.py | src/zeit/cms/generation/evolve14.py | from lovely.remotetask.interfaces import ITaskService
import zeit.cms.generation
import zeit.cms.generation.install
import zope.component
def update(root):
site_manager = zope.component.getSiteManager()
for name, _ in site_manager.getUtilitiesFor(ITaskService):
done = site_manager.unregisterUtility(pr... | from lovely.remotetask.interfaces import ITaskService
import zeit.cms.generation
import zeit.cms.generation.install
import zope.component
def update(root):
site_manager = zope.component.getSiteManager()
for name, service in site_manager.getUtilitiesFor(ITaskService):
done = site_manager.unregisterUtil... | Remove services and jobs from ZODB, too. | ZON-3514: Remove services and jobs from ZODB, too.
| Python | bsd-3-clause | ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms |
e9cca0d736cd388d4834e81ab6bf38ded6625b3d | pynmea2/types/proprietary/grm.py | pynmea2/types/proprietary/grm.py | # Garmin
from ... import nmea
class GRM(nmea.ProprietarySentence):
sentence_types = {}
def __new__(_cls, manufacturer, data):
name = manufacturer + data[0]
cls = _cls.sentence_types.get(name, _cls)
return super(GRM, cls).__new__(cls)
def __init__(self, manufacturer, d... | # Garmin
from decimal import Decimal
from ... import nmea
class GRM(nmea.ProprietarySentence):
sentence_types = {}
def __new__(_cls, manufacturer, data):
name = manufacturer + data[0]
cls = _cls.sentence_types.get(name, _cls)
return super(GRM, cls).__new__(cls)
def... | Add decimal types to Garmin PGRME fields. | Add decimal types to Garmin PGRME fields.
| Python | mit | silentquasar/pynmea2,Knio/pynmea2 |
1ce0d9898fc31f08bbf5765b3a687eaa8067a465 | flaskext/flask_scss.py | flaskext/flask_scss.py | from .scss import Scss
| from .scss import Scss
from warnings import warn
warn(DeprecationWarning('Deprecated import method. '
'Please use:\n '
'from flask.ext.scss import Scss'), stacklevel=2)
| Raise a DeprecationWarning when using pre-Flask-0.8 import scheme | Raise a DeprecationWarning when using pre-Flask-0.8 import scheme
| Python | mit | bcarlin/flask-scss |
40642464aa4d21cb1710f9197bc3456467ed22a8 | b2b_demo/views/basket.py | b2b_demo/views/basket.py | # This file is part of Shoop Gifter Demo.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from django import forms
from shoop.core.models import Address
from shoop.front.views.ba... | # This file is part of Shoop Gifter Demo.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from django import forms
from shoop.front.views.basket import DefaultBasketView
from sh... | Use MutableAddress instead of Address | Use MutableAddress instead of Address
| Python | agpl-3.0 | shoopio/shoop-gifter-demo,shoopio/shoop-gifter-demo,shoopio/shoop-gifter-demo |
5fc467745ffc637e73cdf4dfb4a37b55c581434a | stanford/bin/send-email.py | stanford/bin/send-email.py | #!/usr/bin/env python
from email.mime.text import MIMEText
from subprocess import call
import sys
def send(recipient, sender, sender_name, subject, body):
with open('configuration/stanford/bin/email_params.txt', 'rt') as fin:
with open('email.txt', 'wt') as fout:
for line in fin:
... | #!/usr/bin/env python
from email.mime.text import MIMEText
import os
from subprocess import call
import sys
def send(recipient, sender, sender_name, subject, body):
email_params_file = 'configuration-secure/jenkins/cut-release-branch/email_params.txt'
email_params_file = os.environ.get('CONFIGURATION_EMAIL_PAR... | Use the existing version of params from secrets | Use the existing version of params from secrets
This way we don't need to add them manually!
| Python | agpl-3.0 | Stanford-Online/configuration,Stanford-Online/configuration,Stanford-Online/configuration,Stanford-Online/configuration,Stanford-Online/configuration |
828844ddb6a19ea15c920043f41ba09eb815c597 | django_rq/templatetags/django_rq.py | django_rq/templatetags/django_rq.py | from django import template
from django.utils import timezone
register = template.Library()
@register.filter
def to_localtime(time):
'''
A function to convert naive datetime to
localtime base on settings
'''
utc_time = time.replace(tzinfo=timezone.utc)
to_zone = timezone.get_default_... | from django import template
from django.utils import timezone
register = template.Library()
@register.filter
def to_localtime(time):
'''
A function to convert naive datetime to
localtime base on settings
'''
if not time:
return None
utc_time = time.replace(tzinfo=timezo... | Fix issue displaying deferred queue | Fix issue displaying deferred queue
| Python | mit | ui/django-rq,ui/django-rq,1024inc/django-rq,1024inc/django-rq |
bb9fc566677e92d5ad6bf08af62b610c6cdddbff | pipeline/compute_rpp/compute_rpp.py | pipeline/compute_rpp/compute_rpp.py | import sys
import os
import numpy as np
from skcycling.utils import load_power_from_fit
from skcycling.power_profile import Rpp
# The first input argument corresponding to the data path
data_path = sys.argv[1]
# The second input argument is the storage directory
storage_path = sys.argv[2]
# We can create a list of ... | import sys
import os
import numpy as np
from skcycling.utils import load_power_from_fit
from skcycling.power_profile import Rpp
# The first input argument corresponding to the data path
data_path = sys.argv[1]
# The second input argument is the storage directory
storage_path = sys.argv[2]
# We can create a list of ... | Add some verbose to know if we process things | Add some verbose to know if we process things
| Python | mit | clemaitre58/power-profile,clemaitre58/power-profile,glemaitre/power-profile,glemaitre/power-profile |
5e412494e09d845dcb08529bd9c436f52cdda91b | studygroups/migrations/0034_create_facilitators_group.py | studygroups/migrations/0034_create_facilitators_group.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def create_facilitators_group(apps, schema_editor):
Group = apps.get_model("auth", "Group")
group = Group(name="facilitators")
group.save()
class Migration(migrations.Migration):
dependencies = ... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def create_facilitators_group(apps, schema_editor):
Group = apps.get_model("auth", "Group")
Group.objects.get_or_create(name="facilitators")
class Migration(migrations.Migration):
dependencies = [
... | Change data migration to work even if facilitator group already exists | Change data migration to work even if facilitator group already exists
| Python | mit | p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles |
a5f2df3a540ac99dea73bc7d1d3c29f70fb13c60 | tympeg/streamsaver.py | tympeg/streamsaver.py | import subprocess
from os import path, mkdir
from tympeg.util import renameFile
import platform
import signal
import sys
class StreamSaver:
def __init__(self, input_stream, output_file_path_ts, verbosity=24):
self.file_writer = None
self.analyzeduration = 5000000 # ffmpeg default value (millisec... | import subprocess
from os import path, mkdir
from tympeg.util import renameFile
class StreamSaver:
def __init__(self, input_stream, output_file_path_ts, verbosity=24):
self.file_writer = None
self.analyzeduration = 5000000 # ffmpeg default value (milliseconds must be integer)
self.probes... | Clean up imports after expirements with signals for quitting | Clean up imports after expirements with signals for quitting
| Python | mit | taishengy/tympeg |
74bb8764fbeb65cb4a5b67597f3af4e8c2773794 | dataportal/replay/core.py | dataportal/replay/core.py | """Module for Enaml widgets that are generally useful"""
from enaml.widgets.api import PushButton, Timer
from atom.api import Typed, observe, Event
from enaml.core.declarative import d_
from enaml.layout.api import (grid, align)
class ProgrammaticButton(PushButton):
clicked = d_(Event(bool), writable=True)
tog... | """Module for Enaml widgets that are generally useful"""
from enaml.widgets.api import PushButton, Timer
from atom.api import Typed, observe, Event
from enaml.core.declarative import d_
from enaml.layout.api import (grid, align)
class ProgrammaticButton(PushButton):
clicked = d_(Event(bool), writable=True)
tog... | Add helper function to save state | ENH: Add helper function to save state
Sanitizes the Atom.__getstate() function for any blacklisted
Atom members that are unimportant for state saving or
non-JSON-serializable
| Python | bsd-3-clause | ericdill/datamuxer,NSLS-II/dataportal,danielballan/datamuxer,NSLS-II/dataportal,ericdill/databroker,ericdill/databroker,ericdill/datamuxer,danielballan/datamuxer,danielballan/dataportal,tacaswell/dataportal,tacaswell/dataportal,NSLS-II/datamuxer,danielballan/dataportal |
330cdc00e7b0f7cf18d208ea67499f22c82c9ad5 | lowfat/tests_models.py | lowfat/tests_models.py | from django.test import TestCase
from .models import fix_url
class FixURLTest(TestCase):
def test_none(self):
url = None
expected_url = None
self.assertEqual(fix_url(url), expected_url)
def test_blank(self):
url = ""
expected_url = ""
self.assertEqual(fix_url... | from django.test import TestCase
from .models import Claimant, fix_url
class FixURLTest(TestCase):
def test_none(self):
url = None
expected_url = None
self.assertEqual(fix_url(url), expected_url)
def test_blank(self):
url = ""
expected_url = ""
self.assertEqu... | Add test for Claimant slug field | Add test for Claimant slug field
| Python | bsd-3-clause | softwaresaved/fat,softwaresaved/fat,softwaresaved/fat,softwaresaved/fat |
db30c55c9949db63ffdee604f58130d33ce7c922 | cumulusci/core/keychain/__init__.py | cumulusci/core/keychain/__init__.py | # IMPORT ORDER MATTERS!
# inherit from BaseConfig
from cumulusci.core.keychain.BaseProjectKeychain import BaseProjectKeychain
from cumulusci.core.keychain.BaseProjectKeychain import DEFAULT_CONNECTED_APP
# inherit from BaseProjectKeychain
from cumulusci.core.keychain.BaseEncryptedProjectKeychain import (
BaseEncr... | # IMPORT ORDER MATTERS!
# inherit from BaseConfig
from cumulusci.core.keychain.BaseProjectKeychain import BaseProjectKeychain
from cumulusci.core.keychain.BaseProjectKeychain import DEFAULT_CONNECTED_APP
# inherit from BaseProjectKeychain
from cumulusci.core.keychain.BaseEncryptedProjectKeychain import (
BaseEncr... | Use __all__ to shut up Flake8 | Use __all__ to shut up Flake8
| Python | bsd-3-clause | SalesforceFoundation/CumulusCI,SalesforceFoundation/CumulusCI |
963164d60bf9295233cf8050c6499a500f7c4ce7 | benchmarks/bench_skan.py | benchmarks/bench_skan.py | import os
from contextlib import contextmanager
from collections import OrderedDict
from time import process_time
import numpy as np
from skan import csr
rundir = os.path.dirname(__file__)
@contextmanager
def timer():
time = []
t0 = process_time()
yield time
t1 = process_time()
time.append(t1 ... | import os
from contextlib import contextmanager
from collections import OrderedDict
from time import process_time
import numpy as np
from skan import csr
rundir = os.path.dirname(__file__)
@contextmanager
def timer():
time = []
t0 = process_time()
yield time
t1 = process_time()
time.append(t1 ... | Use benchmark directory to load skeleton | Use benchmark directory to load skeleton
| Python | bsd-3-clause | jni/skan |
ddbf22b6e4d19c2b0c47543d6f4d7fe8fc704483 | errors.py | errors.py | """Errors specific to TwistedSNMP"""
noError = 0
tooBig = 1 # Response message would have been too large
noSuchName = 2 #There is no such variable name in this MIB
badValue = 3 # The value given has the wrong type or length
class OIDNameError( NameError ):
"""An OID was specified which is not defined in namespace"""
... | """Errors specific to TwistedSNMP"""
noError = 0
tooBig = 1 # Response message would have been too large
noSuchName = 2 #There is no such variable name in this MIB
badValue = 3 # The value given has the wrong type or length
class OIDNameError( NameError ):
"""An OID was specified which is not defined in namespace"""
... | Make __str__ = to repr | Make __str__ = to repr
| Python | bsd-3-clause | mmattice/TwistedSNMP |
73fad83b4c1d295611de23b300b67d80a39c9a13 | bot/api/call/call.py | bot/api/call/call.py | from bot.api.call.params import ApiCallParams
from bot.api.domain import ApiObject
from bot.api.telegram import TelegramBotApiException
from bot.multithreading.work import Work
class ApiCall:
def __init__(self, api_func: callable, name: str):
self.api_func = api_func
self.name = name
def call... | from bot.api.call.params import ApiCallParams
from bot.api.domain import ApiObject
from bot.api.exceptions import ApiExceptionFactory
from bot.api.telegram import TelegramBotApiException
from bot.multithreading.work import Work
class ApiCall:
def __init__(self, api_func: callable, name: str):
self.api_fun... | Convert TelegramBotApiException to a ApiException in ApiCall | Convert TelegramBotApiException to a ApiException in ApiCall
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot |
fa2e48566bf532a2c72f9863444f3c7cff23a1c4 | github/commands/open_file_on_remote.py | github/commands/open_file_on_remote.py | from sublime_plugin import TextCommand
from ...common.file_and_repo import FileAndRepo
from ..github import open_file_in_browser
class GsOpenFileOnRemoteCommand(TextCommand, FileAndRepo):
"""
Open a new browser window to the web-version of the currently opened
(or specified) file. If `preselect` is `Tru... | from sublime_plugin import TextCommand
from ...core.base_command import BaseCommand
from ..github import open_file_in_browser
class GsOpenFileOnRemoteCommand(TextCommand, BaseCommand):
"""
Open a new browser window to the web-version of the currently opened
(or specified) file. If `preselect` is `True`,... | Fix regression where unable to open file on remote. | Fix regression where unable to open file on remote.
| Python | mit | divmain/GitSavvy,ddevlin/GitSavvy,ddevlin/GitSavvy,ypersyntelykos/GitSavvy,stoivo/GitSavvy,theiviaxx/GitSavvy,ralic/GitSavvy,dreki/GitSavvy,ralic/GitSavvy,jmanuel1/GitSavvy,divmain/GitSavvy,stoivo/GitSavvy,dreki/GitSavvy,dvcrn/GitSavvy,asfaltboy/GitSavvy,stoivo/GitSavvy,theiviaxx/GitSavvy,asfaltboy/GitSavvy,ddevlin/Git... |
ea875b1cecd154400381969c7c1b165dccd77db8 | httpony/application.py | httpony/application.py | from __future__ import print_function
from httpie.cli import parser
from httpie.context import Environment
from httpie.output import streams
from requests.models import Request
from werkzeug.wrappers import Response
from werkzeug.wrappers import Request as WerkzeugRequest
from httpony import __version__
def make_ap... | from __future__ import print_function
from httpie.cli import parser
from httpie.context import Environment
from httpie.output import streams
from requests.models import Request
from werkzeug.wrappers import Response
from werkzeug.wrappers import Request as WerkzeugRequest
from httpony import __version__
def make_ap... | Delete CONTENT_LENGTH and CONTENT_TYPE if empty. | Delete CONTENT_LENGTH and CONTENT_TYPE if empty.
For some reason, the WSGI server puts these things in the
environment even when they were not in the request.
Their presence messes up the output in those cases.
| Python | bsd-2-clause | mblayman/httpony |
1f105b7ecd6770ac0704329bda3f149c05878da3 | tests/test_utilities/test_in2csv.py | tests/test_utilities/test_in2csv.py | #!/usr/bin/env python
import unittest
import StringIO
from csvkit.utilities.in2csv import In2CSV
from csvkit.utilities.csvstat import CSVStat
class TestIn2CSV(unittest.TestCase):
def test_convert_xls(self):
args = ['-f', 'xls', 'examples/test.xls']
output_file = StringIO.StringIO()
... | #!/usr/bin/env python
import unittest
import StringIO
from csvkit.utilities.in2csv import In2CSV
class TestIn2CSV(unittest.TestCase):
def test_convert_xls(self):
args = ['-f', 'xls', 'examples/test.xls']
output_file = StringIO.StringIO()
utility = In2CSV(args, output_file)
... | Remove extraneous import in test. | Remove extraneous import in test.
| Python | mit | themiurgo/csvkit,barentsen/csvkit,matterker/csvkit,dannguyen/csvkit,tlevine/csvkit,wjr1985/csvkit,doganmeh/csvkit,bradparks/csvkit__query_join_filter_CSV_cli,cypreess/csvkit,KarrieK/csvkit,archaeogeek/csvkit,Jobava/csvkit,jpalvarezf/csvkit,unpingco/csvkit,nriyer/csvkit,arowla/csvkit,haginara/csvkit,Tabea-K/csvkit,snugg... |
6f265e37361b1447cf55c5d79cfe3ba6b6047b57 | tests/examples/helloworld/flows.py | tests/examples/helloworld/flows.py | from viewflow import flow, lock, views as flow_views
from viewflow.base import this, Flow
from viewflow.site import viewsite
from .models import HelloWorldProcess
from .tasks import send_hello_world_request
class HelloWorldFlow(Flow):
"""
Hello world
This process demonstrates hello world approval reque... | from viewflow import flow, lock, views as flow_views
from viewflow.base import this, Flow
from viewflow.site import viewsite
from .models import HelloWorldProcess
from .tasks import send_hello_world_request
class HelloWorldFlow(Flow):
"""
Hello world
This process demonstrates hello world approval reque... | Fix hello world sample flow | Fix hello world sample flow
| Python | agpl-3.0 | ribeiro-ucl/viewflow,ribeiro-ucl/viewflow,ribeiro-ucl/viewflow,codingjoe/viewflow,viewflow/viewflow,codingjoe/viewflow,codingjoe/viewflow,pombredanne/viewflow,pombredanne/viewflow,viewflow/viewflow,viewflow/viewflow |
f832c047acf95e4a9f426eb2e3a174db025325a4 | test/runalltest.py | test/runalltest.py | import sys, os
import unittest
try: # use the 'installed' mpi4py
import mpi4py
except ImportError: # or the no yet installed mpi4py
from distutils.util import get_platform
plat_specifier = ".%s-%s" % (get_platform(), sys.version[0:3])
os.path.split(__file__)[0]
path = os.path.join(os.path.split(__f... | import sys, os
import unittest
try: # use the 'installed' mpi4py
import mpi4py
except ImportError: # or the no yet installed mpi4py
from distutils.util import get_platform
plat_specifier = ".%s-%s" % (get_platform(), sys.version[0:3])
os.path.split(__file__)[0]
path = os.path.join(os.path.split(__f... | Print test names when running full testsuite | Print test names when running full testsuite | Python | bsd-2-clause | pressel/mpi4py,mpi4py/mpi4py,mpi4py/mpi4py,pressel/mpi4py,pressel/mpi4py,pressel/mpi4py,mpi4py/mpi4py |
2212d1b943987652f4a6a575e3e88dc3e174ce7c | eigen/3.2/conanfile.py | eigen/3.2/conanfile.py | from conans import ConanFile
import os
class EigenConan(ConanFile):
name = "eigen"
version = "3.2"
settings = "os", "compiler", "build_type", "arch"
options = {"shared": [True, False]}
default_options = "shared=True"
exports = "eigen/*"
url="https://github.com/jslee02/conan-dart/tree/master... | from conans import ConanFile
import os
class EigenConan(ConanFile):
name = "eigen"
version = "3.2"
settings = "os", "compiler", "build_type", "arch"
options = {"shared": [True, False]}
default_options = "shared=True"
exports = "eigen/*"
url="https://github.com/jslee02/conan-dart/tree/master... | Add --insecure option to hg clone to avoid self-assigned certificate issue | Add --insecure option to hg clone to avoid self-assigned certificate issue
| Python | bsd-2-clause | jslee02/conan-dart,jslee02/conan-dart,jslee02/conan-dart |
bd1346a318f8f8d553a3fbf0a353ef6d68102566 | twitter/twitter_globals.py | twitter/twitter_globals.py | '''
This module is automatically generated using `update.py`
.. data:: POST_ACTIONS
List of twitter method names that require the use of POST
'''
POST_ACTIONS = [
# Status Methods
'update', 'retweet',
# Direct Message Methods
'new',
# Account Methods
'update_profile_image', ... | '''
This module is automatically generated using `update.py`
.. data:: POST_ACTIONS
List of twitter method names that require the use of POST
'''
POST_ACTIONS = [
# Status Methods
'update', 'retweet',
# Direct Message Methods
'new',
# Account Methods
'update_profile_image', ... | Use POST for all methods requiring it in specs | Use POST for all methods requiring it in specs
Added all missing methods from https://dev.twitter.com/docs/api/1.1
Also included some of the streaming methods which work with both GET
and POST but accept arguments like "track" which can quickly require
POST.
(Closes #187 #145 #188)
| Python | mit | adonoho/twitter,Adai0808/twitter,jessamynsmith/twitter,hugovk/twitter,sixohsix/twitter,tytek2012/twitter,miragshin/twitter |
2ae93662f9f978dfae98096701b8e2e2a135f5a5 | rejected/__init__.py | rejected/__init__.py | """
Rejected is a Python RabbitMQ Consumer Framework and Controller Daemon
"""
__author__ = 'Gavin M. Roy <gavinmroy@gmail.com>'
__since__ = "2009-09-10"
__version__ = "3.4.2"
from consumer import Consumer
from consumer import PublishingConsumer
from consumer import SmartConsumer
from consumer import SmartPublishingC... | """
Rejected is a Python RabbitMQ Consumer Framework and Controller Daemon
"""
__author__ = 'Gavin M. Roy <gavinmroy@gmail.com>'
__since__ = "2009-09-10"
__version__ = "3.4.2"
from consumer import Consumer
from consumer import PublishingConsumer
from consumer import SmartConsumer
from consumer import SmartPublishingC... | Add an additional null handler | Add an additional null handler
| Python | bsd-3-clause | gmr/rejected,gmr/rejected |
b75153ad49280ce793a995fca4a34d0688d63cb4 | tests/unit/checkout/mixins_tests.py | tests/unit/checkout/mixins_tests.py | import mock
from django.test import TestCase
from oscar.apps.checkout.mixins import OrderPlacementMixin
class TestOrderPlacementMixin(TestCase):
def test_returns_none_when_no_shipping_address_passed_to_creation_method(self):
address = OrderPlacementMixin().create_shipping_address(
user=mock... | import mock
from django.test import TestCase
from oscar.apps.checkout.mixins import CheckoutSessionMixin, OrderPlacementMixin
from oscar.apps.checkout.exceptions import FailedPreCondition
from oscar.test import factories
from oscar.test.utils import RequestFactory
class TestOrderPlacementMixin(TestCase):
def t... | Add tests for CheckoutSessionMixin.check_basket_is_valid method. | Add tests for CheckoutSessionMixin.check_basket_is_valid method.
| Python | bsd-3-clause | django-oscar/django-oscar,solarissmoke/django-oscar,django-oscar/django-oscar,sasha0/django-oscar,solarissmoke/django-oscar,sasha0/django-oscar,solarissmoke/django-oscar,sasha0/django-oscar,sonofatailor/django-oscar,django-oscar/django-oscar,sonofatailor/django-oscar,sasha0/django-oscar,sonofatailor/django-oscar,sonofa... |
e066eae6bb0f9d555a53f9ee2901c77ffebd3647 | tracer/cachemanager/cachemanager.py | tracer/cachemanager/cachemanager.py | import pickle
import claripy
import logging
from ..simprocedures import receive
l = logging.getLogger("tracer.cachemanager.CacheManager")
class CacheManager(object):
def __init__(self):
self.tracer = None
def set_tracer(self, tracer):
self.tracer = tracer
def cacher(self, simstate):
... | import pickle
import claripy
import logging
from ..simprocedures import receive
l = logging.getLogger("tracer.cachemanager.CacheManager")
class CacheManager(object):
def __init__(self):
self.tracer = None
def set_tracer(self, tracer):
self.tracer = tracer
def cacher(self, simstate):
... | Fix a bug in the cache manager | Fix a bug in the cache manager
It is possible that the previous state is None
| Python | bsd-2-clause | schieb/angr,schieb/angr,angr/angr,angr/angr,tyb0807/angr,iamahuman/angr,f-prettyland/angr,tyb0807/angr,iamahuman/angr,iamahuman/angr,tyb0807/angr,angr/angr,schieb/angr,angr/tracer,f-prettyland/angr,f-prettyland/angr |
6bf971e4248d480594bf10b8f446bf30a5b16072 | scripts/cuba_enum_generator.py | scripts/cuba_enum_generator.py | from scripts.old_single_meta_class_generator import CUBA_DATA_CONTAINER_EXCLUDE
class CUBAEnumGenerator(object):
"""Generator class for cuba.py enumeration.
"""
def generate(self, cuba_dict, simphony_metadata_dict, output):
"""Generates the cuba file from the yaml-extracted dictionary
of ... | from scripts import utils
class CUBAEnumGenerator(object):
"""Generator class for cuba.py enumeration.
"""
def generate(self, cuba_dict, simphony_metadata_dict, output):
"""Generates the cuba file from the yaml-extracted dictionary
of cuba and simphony_metadata files. Writes the generated... | Put prefix to enum values. Removed old hack. | Put prefix to enum values. Removed old hack.
| Python | bsd-2-clause | simphony/simphony-common |
40b4e156a72dd09d752b6ba3adeec7e28ca127a8 | crawler/collector.py | crawler/collector.py | #!/usr/bin/env python3
# chameleon-crawler
#
# Copyright 2015 ghostwords.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from time import sleep
from .utils import ... | #!/usr/bin/env python3
# chameleon-crawler
#
# Copyright 2015 ghostwords.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from time import sleep
from .utils import ... | Convert JSON blob to relational db structure. | Convert JSON blob to relational db structure.
| Python | mpl-2.0 | ghostwords/chameleon-crawler,ghostwords/chameleon-crawler,ghostwords/chameleon-crawler |
fc9cd61f97924a1e3daf053319e9b49a73b58c80 | dploy/__init__.py | dploy/__init__.py | """
dploy script is an attempt at creating a clone of GNU stow that will work on
Windows as well as *nix
"""
import sys
assert sys.version_info >= (3, 3), "Requires Python 3.3 or Greater"
import dploy.main as main
def stow(sources, dest):
"""
sub command stow
"""
main.Stow(sources, dest) # pylint: ... | """
dploy script is an attempt at creating a clone of GNU stow that will work on
Windows as well as *nix
"""
import sys
assert sys.version_info >= (3, 3), "Requires Python 3.3 or Greater"
import dploy.main as main
def stow(sources, dest, is_silent=True, is_dry_run=False):
"""
sub command stow
"""
ma... | Add is_silent & is_dry_run arguments to module API | Add is_silent & is_dry_run arguments to module API
This way all the features of the command line commands is also in the module API
| Python | mit | arecarn/dploy |
a5fa87d1dac36ae8a1e0939aaf7835aa39d5c153 | jsonapi.py | jsonapi.py | from flask import Blueprint
# Set up api Blueprint
api = Blueprint('api', __name__)
# API Post Route
@api.route('/create', methods=['GET', 'POST'])
def api_create():
return "Create JSON Blueprint!"
| from flask import Blueprint, jsonify, request
import MySQLdb, dbc
# Set up api Blueprint
api = Blueprint('api', __name__)
# API Post Route
@api.route('/create', methods=['GET', 'POST'])
def api_create():
# Get URL and password from POST Request
URL = request.form.get('url')
password = request.form.get('pa... | Add jsonify to api returns | Add jsonify to api returns | Python | apache-2.0 | kylefrost/frst.xyz,kylefrost/frst.xyz |
3347aaf8ad8fc1e016f1bf4159a91227cf8bc450 | billjobs/tests/tests_user_admin_api.py | billjobs/tests/tests_user_admin_api.py | from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APIClient, APIRequestFactory, \
force_authenticate
from billjobs.views import UserAdmin, UserAdminDetail
class UserAdminAPI(TestCase):
""" Test User Admin API REST ... | from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APIClient, APIRequestFactory, \
force_authenticate
from billjobs.views import UserAdmin, UserAdminDetail
class UserAdminAPI(TestCase):
""" Test User Admin API REST ... | Test anonymous user do not access user list endpoint | Test anonymous user do not access user list endpoint
| Python | mit | ioO/billjobs |
bef6e3b13c2e524f606d6ef4157df93933548c22 | 11_first-try-except.py | 11_first-try-except.py | number = raw_input('Enter a number to find a square : ')
try :
actualNumber = int(number)**2
print 'Square of the number is', actualNumber
except :
print 'Instead of typing number you entered -', number
| number = raw_input('Enter a number to find a square : ')
try :
# In order to accept floating numbers, we are converting the varibale to float.
actualNumber = float(number)**2
print 'Square of the number is', actualNumber
except :
print 'Instead of typing number you entered -', number
| Convert variable from int to float, in order to accept floating value as well | Convert variable from int to float, in order to accept floating value as well
| Python | mit | rahulbohra/Python-Basic |
1bbb7d793b479e299f751e84a85f8bc9f40fc633 | microbower/__init__.py | microbower/__init__.py |
from subprocess import check_call
import urllib
import json
import os
import os.path
def install():
with open('.bowerrc') as f:
bowerrc = json.load(f)
with open('bower.json') as f:
bower_json = json.load(f)
registry = 'https://bower.herokuapp.com'
topdir = os.path.abspath(os.curdir)
... |
from subprocess import check_call
import urllib
import json
import os
import os.path
def install():
if not (os.path.isfile('.bowerrc') and os.path.isfile('bower.json')):
return
with open('.bowerrc') as f:
bowerrc = json.load(f)
with open('bower.json') as f:
bower_json = json.load(... | Check for the asset directory once at the beginning | Check for the asset directory once at the beginning
| Python | isc | zenhack/microbower |
85384cb811c8e4cfdcaa1c207ac2274f352b86e9 | tensorflow_tutorials/__init__.py | tensorflow_tutorials/__init__.py | """
[Tutorials] for [TensorFlow].
[Tutorials]: https://www.tensorflow.org/versions/r0.8/tutorials/index.html
[TensorFLow]: https://www.tensorflow.org/
"""
from .version import __version__
from .mnist import mnist
__all__ = [
'mnist'
]
| """
[Tutorials] for [TensorFlow].
[Source on GitHub][source].
[source]: https://github.com/rxedu/tensorflow-tutorials
[Tutorials]: https://www.tensorflow.org/versions/r0.8/tutorials/index.html
[TensorFLow]: https://www.tensorflow.org/
"""
from .version import __version__
from .mnist import mnist
__all__ = [
'mni... | Add source link to docstring | Add source link to docstring
| Python | mit | rxedu/tensorflow-tutorials |
c23f134cb8385919c8fe07136f978223ed229978 | micawber/cache.py | micawber/cache.py | from __future__ import with_statement
import os
import pickle
from contextlib import closing
try:
from redis import Redis
except ImportError:
Redis = None
class Cache(object):
def __init__(self):
self._cache = {}
def get(self, k):
return self._cache.get(k)
def set(self, k, v):
... | from __future__ import with_statement
import os
import pickle
from contextlib import closing
try:
from redis import Redis
except ImportError:
Redis = None
class Cache(object):
def __init__(self):
self._cache = {}
def get(self, k):
return self._cache.get(k)
def set(self, k, v):
... | Fix PicleCache error on Python3 | Fix PicleCache error on Python3
| Python | mit | coleifer/micawber,coleifer/micawber |
81d2882d1558ed52fc70927d745474aa46ac1f3b | jarbas/dashboard/admin.py | jarbas/dashboard/admin.py | from django.contrib import admin
from jarbas.core.models import Reimbursement
class SuspiciousListFilter(admin.SimpleListFilter):
title = 'Is suspicious'
parameter_name = 'is_suspicions'
def lookups(self, request, model_admin):
return (
('yes', 'Yes'),
('no', 'No'),
... | from django.contrib import admin
from jarbas.core.models import Reimbursement
class SuspiciousListFilter(admin.SimpleListFilter):
title = 'Is suspicious'
parameter_name = 'is_suspicions'
def lookups(self, request, model_admin):
return (
('yes', 'Yes'),
('no', 'No'),
... | Mark all fields as read only in the dashboard | Mark all fields as read only in the dashboard
| Python | mit | datasciencebr/jarbas,datasciencebr/jarbas,marcusrehm/serenata-de-amor,marcusrehm/serenata-de-amor,datasciencebr/jarbas,marcusrehm/serenata-de-amor,datasciencebr/serenata-de-amor,datasciencebr/serenata-de-amor,datasciencebr/jarbas,marcusrehm/serenata-de-amor |
7d4d1afc5a42edb88f5cb8eb1347b79fdc131272 | src/actions/client.py | src/actions/client.py | from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from twisted.application.internet import MulticastServer
from BeautifulSoup import BeautifulSoup, SoupStrainer
import requests
fileserver = ''
urls = []
def get_file_urls(self, url):
f = requests.get("http://" + url)
... | from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from twisted.application.internet import MulticastServer
from BeautifulSoup import BeautifulSoup, SoupStrainer
import requests
fileserver = ''
urls = []
def get_file_urls(self, url):
f = requests.get("http://" + url)
... | Stop reactor and find files | Stop reactor and find files
| Python | mit | derwolfe/teiler,derwolfe/teiler |
c11d0ec668a0755a9c5db2cb4dd372d8ab3e8a0d | .circleci/get_repos.py | .circleci/get_repos.py | from __future__ import print_function
import os
import sys
import subprocess as sp
import pytest
import yaml
import requests
import argparse
import re
from ggd import utils
#---------------------------------------------------------------------
## Clone repos
#---------------------------------------------------------... | from __future__ import print_function
import os
import sys
import subprocess as sp
import pytest
import yaml
import requests
import argparse
import re
from ggd import utils
#---------------------------------------------------------------------
## Clone repos
#---------------------------------------------------------... | Update with new metadata file system (removing use of ggd repo cloning) | Update with new metadata file system (removing use of ggd repo cloning)
| Python | mit | gogetdata/ggd-cli,gogetdata/ggd-cli |
1c727e878402ffacf14c2978860d7d555c5f4069 | zoe_lib/predefined_apps/__init__.py | zoe_lib/predefined_apps/__init__.py | # Copyright (c) 2016, Daniele Venzano
#
# 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 w... | # Copyright (c) 2016, Daniele Venzano
#
# 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 w... | Fix import error due to wrong import line | Fix import error due to wrong import line
| Python | apache-2.0 | DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe |
1c5af88a0689aadab4069f9f2ad16164791624b3 | Discord/utilities/errors.py | Discord/utilities/errors.py |
from discord.ext.commands.errors import CommandError
class NotServerOwner(CommandError):
'''Not Server Owner'''
pass
class VoiceNotConnected(CommandError):
'''Voice Not Connected'''
pass
class PermittedVoiceNotConnected(VoiceNotConnected):
'''Permitted, but Voice Not Connected'''
pass
class NotPermittedVoice... |
from discord.ext.commands.errors import CommandError
class NotServerOwner(CommandError):
'''Not Server Owner'''
pass
class VoiceNotConnected(CommandError):
'''Voice Not Connected'''
pass
class PermittedVoiceNotConnected(VoiceNotConnected):
'''Permitted, but Voice Not Connected'''
pass
class NotPermittedVoice... | Remove no longer used Missing Capability error | [Discord] Remove no longer used Missing Capability error
| Python | mit | Harmon758/Harmonbot,Harmon758/Harmonbot |
fb5c2e5df4f700fb19663bbe96e7aa2710e627ca | osprey/execute_dump.py | osprey/execute_dump.py | from __future__ import print_function, absolute_import, division
import csv
import json
from six.moves import cStringIO
from .config import Config
from .trials import Trial
def execute(args, parser):
config = Config(args.config, verbose=False)
session = config.trials()
columns = Trial.__mapper__.columns... | from __future__ import print_function, absolute_import, division
import csv
import json
from six.moves import cStringIO
from .config import Config
from .trials import Trial
def execute(args, parser):
config = Config(args.config, verbose=False)
session = config.trials()
columns = Trial.__mapper__.columns... | Store hyperparameters with the other settings | Store hyperparameters with the other settings
Instead of storing them in their own 'parameters' directory. | Python | apache-2.0 | msmbuilder/osprey,msultan/osprey,pandegroup/osprey,msultan/osprey,msmbuilder/osprey,pandegroup/osprey |
0b13092a7854fe2d967d057221420a57b7a37b16 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""This module exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an inte... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""Exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to sty... | Change module docstring to make Travis CI build pass | Change module docstring to make Travis CI build pass
| Python | mit | jackbrewer/SublimeLinter-contrib-stylint |
9037c6c67add92304b6cfdbfb3a79ac1b3e9e64e | test/checker/test_checker_binary.py | test/checker/test_checker_binary.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import unicode_literals
import itertools
import pytest
import six
from six import MAXSIZE
from typepy import Binary, StrictLevel, Typecode
nan = float("nan")
inf = float("inf")
class Test_Binary_is_type(ob... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import unicode_literals
import itertools
import pytest
from six import MAXSIZE
from typepy import Binary, StrictLevel, Typecode
nan = float("nan")
inf = float("inf")
class Test_Binary_is_type(object):
... | Fix test cases for Python2 | Fix test cases for Python2
| Python | mit | thombashi/typepy |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.