commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
ffd551c85d53c6c4ce1ad4b42006c49a8dfec806 | update based on remote timestamp for soil data sets from the uc davis soils website | codeforamerica/westsac-urban-land-locator,codeforamerica/westsac-urban-land-locator,codeforamerica/westsac-urban-land-locator,codeforamerica/westsac-urban-land-locator | farmsList/imports.py | farmsList/imports.py | '''
This is where we want to go through and check for any updates to the remote data sets that we're using.
If a remote data set has been updated, we will fetch it and populate the updates to our database.
'''
import os
import urllib2
from datetime import datetime
from HTMLParser import HTMLParser
from sqlalchemy im... | '''
This is where we want to go through and check for any updates to the remote data sets that we're using.
If a remote data set has been updated, we will fetch it and populate the updates to our database.
'''
import os
import urllib2
from datetime import datetime
from HTMLParser import HTMLParser
from sqlalchemy im... | bsd-3-clause | Python |
3d6cc53a3fa5f272086612fa487589acc9b13737 | Append app path to Python path in WSGI | FedeRez/webldap,FedeRez/webldap,FedeRez/webldap | federez_ldap/wsgi.py | federez_ldap/wsgi.py | """
WSGI config for federez_ldap project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATI... | """
WSGI config for federez_ldap project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATI... | mit | Python |
bba38e01cdf2c8a60c04631727a44fcd3700235b | remove inexistant import | acsone/mozaik,mozaik-association/mozaik,mozaik-association/mozaik,acsone/mozaik | ficep/__openerp__.py | ficep/__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
# All Rights Reserved
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of ... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
# All Rights Reserved
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of ... | agpl-3.0 | Python |
acb12b9ece8cde7e6d6f3796aa41e624ca2358c4 | add missing regex-group->string conversion | dials/dials,dials/dials,dials/dials,dials/dials,dials/dials | precommitbx/setup.py | precommitbx/setup.py | from __future__ import absolute_import, division, print_function
import re
from setuptools import find_packages, setup
with open("_precommitbx/__init__.py") as fh:
init_file = fh.read()
version_match = re.search(r"^__version__ = \"([0-9.]+)\"", init_file, re.M)
pc_version_match = re.search(
r"^__p... | from __future__ import absolute_import, division, print_function
import re
from setuptools import find_packages, setup
with open("_precommitbx/__init__.py") as fh:
init_file = fh.read()
version_match = re.search(r"^__version__ = \"([0-9.]+)\"", init_file, re.M)
pc_min_version = re.search(
r"^__pre... | bsd-3-clause | Python |
daaeb002d7a4a2845052dd3078512e66189c5a88 | Update BaseTest class (removing registry). | ulule/django-linguist | linguist/tests/base.py | linguist/tests/base.py | # -*- coding: utf-8 -*-
from django.test import TestCase
from ..models import Translation
from . import settings
from .translations import FooModel
class BaseTestCase(TestCase):
"""
Base test class mixin.
"""
@property
def languages(self):
return [language[0] for language in settings.LA... | # -*- coding: utf-8 -*-
from django.test import TestCase
from ..registry import LinguistRegistry as Registry
from ..models import Translation
from . import settings
from .translations import FooModel, FooTranslation
class BaseTestCase(TestCase):
"""
Base test class mixin.
"""
@property
def lang... | mit | Python |
0bbccb1ee6296fe0178dcc7e90676e53bbe07f93 | revert version | markstory/lint-review,markstory/lint-review,markstory/lint-review | lintreview/__init__.py | lintreview/__init__.py | __version__ = '2.0.0-beta4'
| __version__ = '2.0.0'
| mit | Python |
36bb9b984ecfc6a75599a124299f67135c7e9444 | Update ipc_lista1.6.py | any1m1c/ipc20161 | lista1/ipc_lista1.6.py | lista1/ipc_lista1.6.py | #ipc_lista1.6
#Professor: Jucimar Junior
#Any Mendes Carvalho
| #ipc_lista1.6
#Professor: Jucimar Junior
#Any Mendes
| apache-2.0 | Python |
1074b81bc19f5dd942c142753abba833146eede8 | stop printing installed middlewares | adaptive-learning/proso-apps,adaptive-learning/proso-apps,adaptive-learning/proso-apps | proso_common/apps.py | proso_common/apps.py | from django.apps import AppConfig as OAppConfig
from django.conf import settings
import importlib
MIDDLEWARE_CLASSES = [
'proso.django.request.RequestMiddleware',
'proso.django.config.ConfigMiddleware',
'proso.django.cache.RequestCacheMiddleware',
'proso.django.log.RequestLogMiddleware',
'proso_co... | from django.apps import AppConfig as OAppConfig
from django.conf import settings
import importlib
MIDDLEWARE_CLASSES = [
'proso.django.request.RequestMiddleware',
'proso.django.config.ConfigMiddleware',
'proso.django.cache.RequestCacheMiddleware',
'proso.django.log.RequestLogMiddleware',
'proso_co... | mit | Python |
054762aed512789105c4ae4be16332f533ce40d7 | Use new USER_FILES_ROOT setting in filebrowser | vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium | filebrowser/views.py | filebrowser/views.py | # App for browsing the server.
import os
import time
from stat import *
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response
from django.template import RequestConte... | # App for browsing the server.
import os
import time
from stat import *
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response
from django.template import RequestConte... | apache-2.0 | Python |
deeb321c14f3f237a62ba14f0f9138a01163394a | Remove development_status to project_timesheet_time_control. | OCA/project,OCA/project | project_timesheet_time_control/__manifest__.py | project_timesheet_time_control/__manifest__.py | # Copyright 2016 Tecnativa - Antonio Espinosa
# Copyright 2016 Tecnativa - Sergio Teruel
# Copyright 2016-2018 Tecnativa - Pedro M. Baeza
# Copyright 2018 Tecnativa - Ernesto Tejeda
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Project timesheet time control",
"version": "14.0.1.0... | # Copyright 2016 Tecnativa - Antonio Espinosa
# Copyright 2016 Tecnativa - Sergio Teruel
# Copyright 2016-2018 Tecnativa - Pedro M. Baeza
# Copyright 2018 Tecnativa - Ernesto Tejeda
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Project timesheet time control",
"version": "14.0.1.0... | agpl-3.0 | Python |
213a7a36bd599279d060edc053a86b602c9731b1 | Fix test issue with mocking import for Python 3 | blue-yonder/turbodbc,blue-yonder/turbodbc,blue-yonder/turbodbc,blue-yonder/turbodbc | python/turbodbc_test/test_has_numpy_support.py | python/turbodbc_test/test_has_numpy_support.py | import six
from mock import patch
from turbodbc.cursor import _has_numpy_support
# Python 2/3 compatibility
_IMPORT_FUNCTION_NAME = "{}.__import__".format(six.moves.builtins.__name__)
def test_has_numpy_support_fails():
with patch(_IMPORT_FUNCTION_NAME, side_effect=ImportError):
assert _has_numpy_supp... | from mock import patch
from turbodbc.cursor import _has_numpy_support
def test_has_numpy_support_fails():
with patch('__builtin__.__import__', side_effect=ImportError):
assert _has_numpy_support() == False
def test_has_numpy_support_succeeds():
assert _has_numpy_support() == True | mit | Python |
e4ed36dfc26e8357919ea96c4af90a8c2e98fb58 | use of Middleware in class method | b3j0f/middleware | b3j0f/middleware/cls.py | b3j0f/middleware/cls.py | # -*- coding: utf-8 -*-
# --------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2016 Jonathan Labéjof <jonathan.labejof@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation fi... | # -*- coding: utf-8 -*-
# --------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2016 Jonathan Labéjof <jonathan.labejof@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation fi... | mit | Python |
e2f7e134240d3715310bb8e0dee3f8cb077a40bd | Update config.py | MrMcCrary/backgroundbot | backgroundbot/config.py | backgroundbot/config.py | ver = 1.0
sub = 'earthporn'
save_images = False
sleeptime = 1800
postlimit = 20
username = 'USERNAME'
password = 'PASSWORD'
client_id = 'CLIENT ID'
client_secret = 'CLIENT SECRET'
| ver = 1.0
sub = 'earthporn'
save_images = True
sleeptime = 1800
postlimit = 20
username = 'USERNAME'
password = 'PASSWORD'
client_id = 'CLIENT ID'
client_secret = 'CLIENT SECRET'
| mit | Python |
2d436457f95c7382b3720419552bd22bb189b00e | Add debugging | charles-cooper/raiden,tomashaber/raiden,hackaugusto/raiden,tomashaber/raiden,tomashaber/raiden,tomashaber/raiden,charles-cooper/raiden,hackaugusto/raiden,tomashaber/raiden | raiden/network/stunsock.py | raiden/network/stunsock.py | # -*- coding: utf-8 -*-
import socket
from contextlib import contextmanager
import stun
from ethereum import slogging as logging
log = logging.getLogger(__name__)
class STUNUnavailableException(Exception):
pass
@contextmanager
def stun_socket(
source_ip='0.0.0.0',
source_port=4200,
stun_host=None... | # -*- coding: utf-8 -*-
import socket
from contextlib import contextmanager
import stun
from ethereum import slogging as logging
log = logging.getLogger(__name__)
class STUNUnavailableException(Exception):
pass
@contextmanager
def stun_socket(
source_ip='0.0.0.0',
source_port=4200,
stun_host=None... | mit | Python |
254702c1b5a76701a1437d6dc3d732ec27ebaa81 | Make `refresh` return self for chaining actions | slash-testing/backslash-python,vmalloc/backslash-python | backslash/api_object.py | backslash/api_object.py |
class APIObject(object):
def __init__(self, client, json_data):
super(APIObject, self).__init__()
self.client = client
self._data = json_data
def __eq__(self, other):
if not isinstance(other, APIObject):
return NotImplemented
return self.client is other.cli... |
class APIObject(object):
def __init__(self, client, json_data):
super(APIObject, self).__init__()
self.client = client
self._data = json_data
def __eq__(self, other):
if not isinstance(other, APIObject):
return NotImplemented
return self.client is other.cli... | bsd-3-clause | Python |
56c3d781f3d518bb62ae039aeb078cb934d31840 | test stream linking #17 | jwalczyk/test_repo,jwalczyk/test_repo | example/python_read.py | example/python_read.py | # from sys module import a member called 'argv'
from sys import argv
#unpack
# test 3
script, filename = argv
fp = open(filename)
print "Reading file %r " % fp
print fp.read()
fp.close()
# gui stream test
| # from sys module import a member called 'argv'
from sys import argv
#unpack
# test 3
script, filename = argv
fp = open(filename)
print "Reading file %r " % fp
print fp.read()
fp.close()
| apache-2.0 | Python |
3846e389e1f7696a574c2d284cb43cdf85d760da | improve formatting | e3krisztian/bead,krisztianfekete/lib,e3krisztian/bead,krisztianfekete/lib | bead_cli/web/cluster.py | bead_cli/web/cluster.py | from typing import Dict, Iterable
from bead.tech.timestamp import EPOCH_STR
from .metabead import MetaBead
from .bead_state import BeadState
from . import graphviz
class Cluster:
"""
Versions of beads having the same name.
.head: Latest bead, that is not phantom, or the first phantom bead, if all are p... | from typing import Dict, Iterable
from bead.tech.timestamp import EPOCH_STR
from .metabead import MetaBead
from .bead_state import BeadState
from . import graphviz
class Cluster:
"""
Versions of beads having the same name.
.head: Latest bead, that is not phantom, or the first phantom bead, if all are p... | unlicense | Python |
3ac79412884e7d6f5d88951419d0f81232c5be32 | Update custom_dot.py | ad-m/python-anticaptcha | examples/custom_dot.py | examples/custom_dot.py | from collections import OrderedDict
from os import environ
from python_anticaptcha import AnticaptchaClient
from python_anticaptcha.fields import TextInput, Select, Radio
from python_anticaptcha.tasks import CustomCaptchaTask
api_key = environ['KEY']
URL = "https://s.jawne.info.pl/dot_img"
EXPECTED_RESULT = ('7', 'r... | from collections import OrderedDict
from os import environ
from python_anticaptcha import AnticaptchaClient
from python_anticaptcha.fields import TextInput, Select, Radio
from python_anticaptcha.tasks import CustomCaptchaTask
api_key = environ['KEY']
URL = "https://s.jawne.info.pl/dot_img"
EXPECTED_RESULT = ('7', 'r... | mit | Python |
1f4653d961dc2902800efefa325d92ab895385c1 | use new Point() and remove_group() | jegger/kivy,darkopevec/kivy,bliz937/kivy,edubrunaldi/kivy,cbenhagen/kivy,Cheaterman/kivy,Shyam10/kivy,autosportlabs/kivy,denys-duchier/kivy,darkopevec/kivy,viralpandey/kivy,eHealthAfrica/kivy,Davideddu/kivy-forkedtouch,Farkal/kivy,niavlys/kivy,janssen/kivy,Shyam10/kivy,bionoid/kivy,arcticshores/kivy,andnovar/kivy,autos... | examples/touchdebug.py | examples/touchdebug.py | from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.graphics import Color, Rectangle, Point
from random import random
from math import sqrt
def calculate_points(x1, y1, x2, y2, steps=2):
dx = x2 - x1
dy = y2 - y1
dist = sqrt(dx * dx + dy * dy)
if dist ... | from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.graphics import Color, Rectangle
class Touchdebug(Widget):
def on_touch_down(self, touch):
win = self.get_parent_window()
ud = touch.userdata
with self.canvas:
ud['color'] = Co... | mit | Python |
1be7545147c8def5600d496ecd3fa1f4650aa0bc | Send None if no APIC member | MikeiLL/appension,MikeiLL/appension,MikeiLL/appension,Rosuav/appension,Rosuav/appension,Rosuav/appension,MikeiLL/appension,Rosuav/appension | id3info.py | id3info.py | '''
Extract MP3 metadata from MP3 file ID3 tags
'''
usage = '''
python id3info.py
'''
from mutagen.mp3 import MP3
import glob
import time
import psycopg2
def dbactions(track, cur):
cur.execute("INSERT INTO tracks \
(artist, \
title, \
filename, \
artwork \
) \
VALUES (%s, %s, %s)",
(u', '.join(t... | '''
Extract MP3 metadata from MP3 file ID3 tags
'''
usage = '''
python id3info.py
'''
from mutagen.mp3 import MP3
import glob
import time
import psycopg2
def dbactions(track, cur):
cur.execute("INSERT INTO tracks \
(artist, \
title, \
filename, \
artwork \
) \
VALUES (%s, %s, %s)",
(u', '.join(t... | artistic-2.0 | Python |
dd7d33da22f2645e2284df2d6cdd6c4c431392f3 | Bump version to 0.1.0 | sbuss/bitmerchant,mflaxman/bitmerchant | bitmerchant/_version.py | bitmerchant/_version.py | __version__ = "0.1.0"
| __version__ = "0.0.1"
| mit | Python |
5b242d1774597bb1d776d41cf4a6fa1bfb665636 | fix exception inheritance | kevenli/scrapydd,kevenli/scrapydd,kevenli/scrapydd,kevenli/scrapydd | scrapydd/exceptions.py | scrapydd/exceptions.py | from tornado.web import HTTPError
class ProjectNotFound(HTTPError):
def __init__(self):
super(ProjectNotFound, self, ).__init__(404, 'Project not found.')
class SpiderNotFound(HTTPError):
def __init__(self):
super(SpiderNotFound, self).__init__(404, 'Spider not found.')
class ... | from tornado.web import HTTPError
class ProjectNotFound(HTTPError):
def __init__(self):
super(self, ProjectNotFound).__init__(404, 'Project not found.')
class SpiderNotFound(HTTPError):
def __init__(self):
super(self, ProjectNotFound).__init__(404, 'Spider not found.')
class N... | apache-2.0 | Python |
fa517842ab80b3bbfaa137a67cea57ce6bfb30c3 | Use Django's JSON encoder | funkybob/django-marionette | marionette/__init__.py | marionette/__init__.py |
from cgi import parse_header
import json
from django.http import HttpResponse, Http404
from django.views.decorators.http import require_POST
from django.core.serializers.json import DjangoJSONEncoder
RPC_MARKER = '_rpc'
class Resource(object):
def __init__(self, request, *args, **kwargs):
self.reques... |
from cgi import parse_header
import json
from django.http import HttpResponse, Http404
from django.views.decorators.http import require_POST
RPC_MARKER = '_rpc'
class Resource(object):
def __init__(self, request, *args, **kwargs):
self.request = request
self.args = args
self.kwargs = k... | mit | Python |
dca7ca2c7554df688553a754181b2db270e83003 | Test code before committing, Team. | JackieChiles/Cinch,JackieChiles/Cinch,JackieChiles/Cinch | web/message.py | web/message.py | #!/usr/bin/python3
"""Message object for relaying data between web server and engines."""
class Message:
def __init__(self, data, source=None, dest_list=None,
source_key=None, dest_key=None):
"""Create Message with data and routing information.
source and/or dest_list can be passe... | #!/usr/bin/python3
"""Message object for relaying data between web server and engines."""
class Message:
def __init__(self, data, source=None, dest_list=None,
source_key=None, dest_key=None):
"""Create Message with data and routing information.
source and/or dest_list can be passe... | mit | Python |
8ee40b1cd12f5c39a239b911a2a04b293553f1f6 | Set __version__ to 0.9.1 for release. | rochacbruno/flasgger,flasgger/flasgger,flasgger/flasgger,rochacbruno/flasgger,rochacbruno/flasgger,flasgger/flasgger,flasgger/flasgger | flasgger/__init__.py | flasgger/__init__.py |
__version__ = '0.9.1'
__author__ = 'Bruno Rocha'
__email__ = 'rochacbruno@gmail.com'
from jsonschema import ValidationError # noqa
from .base import Swagger, Flasgger, NO_SANITIZER, BR_SANITIZER, MK_SANITIZER, LazyJSONEncoder # noqa
from .utils import swag_from, validate, apispec_to_template, LazyString # noqa
fr... |
__version__ = '0.9.1.dev0'
__author__ = 'Bruno Rocha'
__email__ = 'rochacbruno@gmail.com'
from jsonschema import ValidationError # noqa
from .base import Swagger, Flasgger, NO_SANITIZER, BR_SANITIZER, MK_SANITIZER, LazyJSONEncoder # noqa
from .utils import swag_from, validate, apispec_to_template, LazyString # no... | mit | Python |
18618d58715bd223dd93456e3f00f8a02aef2b2a | fix bug (#280) | datacommonsorg/website,datacommonsorg/website,datacommonsorg/website,datacommonsorg/website,datacommonsorg/website | server/configmodule.py | server/configmodule.py | """Module contains Flask config for production and dev environment.
"""
import os
import datetime
class Config:
TEST = False
WEBDRIVER = False
CACHE_TYPE = 'simple' # Flask-Caching related configs
GAE_VERSION = (
os.environ.get('GAE_VERSION') or
datetime.datetime.today().strftime("%m... | """Module contains Flask config for production and dev environment.
"""
import os
import datetime
class Config:
TEST = False
CACHE_TYPE = 'simple' # Flask-Caching related configs
GAE_VERSION = (
os.environ.get('GAE_VERSION') or
datetime.datetime.today().strftime("%m-%d-%H-%M"))
class P... | apache-2.0 | Python |
0e3d95bef337e4e9519875234653a00c2cad4408 | Fix Rfam CLI definitions | RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline | rnacentral_pipeline/cli/rfam.py | rnacentral_pipeline/cli/rfam.py | # -*- coding: utf-8 -*-
"""
Copyright [2009-2018] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by... | # -*- coding: utf-8 -*-
"""
Copyright [2009-2018] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by... | apache-2.0 | Python |
76f12318bc814bd78c78a002c08c0834807528a1 | Update sync.py | gangadhar-kadam/hrfrappe,gangadhar-kadam/hrfrappe | frappe/model/sync.py | frappe/model/sync.py | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
"""
Sync's doctype and docfields from txt files to database
perms will get synced only if none exist
"""
import frappe
import os, sys
from frappe.modules.import_file import i... | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
"""
Sync's doctype and docfields from txt files to database
perms will get synced only if none exist
"""
import frappe
import os, sys
from frappe.modules.import_file import i... | mit | Python |
0da72f62800eca0c18265c8b45de19d2d31bbaea | Ajuste no encoding | jfunez/scielo-manager,fabiobatalha/SciELO-Manager,jfunez/scielo-manager,gustavofonseca/scielo-manager,fabiobatalha/SciELO-Manager,gustavofonseca/scielo-manager,scieloorg/scielo-manager,jamilatta/scielo-manager,fabiobatalha/SciELO-Manager,jfunez/scielo-manager,jamilatta/scielo-manager,gustavofonseca/scielo-manager,sciel... | scielomanager/utils/csv2user.py | scielomanager/utils/csv2user.py | #!/usr/bin/python
# -*- encoding:utf8 -*-
import sys
import os
import csv
from django.core.management import setup_environ
try:
from scielomanager import settings
except ImportError:
BASE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
from sys import path
path.append(BASE_PATH)
... | #!/usr/bin/python
#coding: utf-8
import sys
import os
import csv
from django.core.management import setup_environ
try:
from scielomanager import settings
except ImportError:
BASE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
from sys import path
path.append(BASE_PATH)
impor... | bsd-2-clause | Python |
22e2ec83951473777b90b808eaa18caf7069cfe8 | Update for django 1.9.0 | thibault/django-zipview | zipview/views.py | zipview/views.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import zipfile
from io import BytesIO
from django.views.generic import View
from django.http import HttpResponse
from django.core.files.base import ContentFile
from django.utils.six import b
class BaseZipView(View):
"""A base view to zip ... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import zipfile
from io import BytesIO
from django.views.generic import View
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
class BaseZipView(View):
"""A base view to zip and stream several files... | mit | Python |
d471663880d6ab9aec0a053fdaaffacc538ecf31 | fix Python3 compatibility (#247) | james-powis/puppetboard,james-powis/puppetboard,voxpupuli/puppetboard,johnzimm/xx-puppetboard,tparkercbn/puppetboard,tparkercbn/puppetboard,grandich/puppetboard,james-powis/puppetboard,grandich/puppetboard,johnzimm/puppetboard,johnzimm/xx-puppetboard,voxpupuli/puppetboard,tparkercbn/puppetboard,stoyansbg/puppetboard,mt... | puppetboard/utils.py | puppetboard/utils.py | from __future__ import absolute_import
from __future__ import unicode_literals
import json
import logging
from math import ceil
from requests.exceptions import HTTPError, ConnectionError
from pypuppetdb.errors import EmptyResponseError
from flask import abort
# Python 3 compatibility
try:
xrange
except NameErr... | from __future__ import absolute_import
from __future__ import unicode_literals
import json
import logging
from math import ceil
from requests.exceptions import HTTPError, ConnectionError
from pypuppetdb.errors import EmptyResponseError
from flask import abort
log = logging.getLogger(__name__)
def jsonprint(value)... | apache-2.0 | Python |
81ac46b840b36ce1ad0066651da47a91ed95a427 | Debug sys.path | johnseekins/graphite-web,SEJeff/graphite-web,synedge/graphite-web,graphite-server/graphite-web,phreakocious/graphite-web,jssjr/graphite-web,phreakocious/graphite-web,DanCech/graphite-web,bruce-lyft/graphite-web,piotr1212/graphite-web,JeanFred/graphite-web,cbowman0/graphite-web,DanCech/graphite-web,bpaquet/graphite-web,... | webapp/graphite/manage.py | webapp/graphite/manage.py | #!/usr/bin/env python
import os
import sys
print(sys.path)
from django.core.management import execute_from_command_line
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv... | #!/usr/bin/env python
import os
import sys
from django.core.management import execute_from_command_line
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| apache-2.0 | Python |
3fb14cd136bc99778f6494a6cbfa20cc6bfc3fd9 | Revert "test" | plus1s/shadowsocks-py-mu,plus1s/shadowsocks-py-mu | shadowsocks/servers.py | shadowsocks/servers.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2015 mengskysama
# Copyright 2016 Howard Liu
#
# 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... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2015 mengskysama
# Copyright 2016 Howard Liu
#
# 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... | apache-2.0 | Python |
ecffe382a6dd56feecb40b971292654e9a3a665c | Bump version to 1.2.5 | laughingman7743/PyAthena | pyathena/__init__.py | pyathena/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import datetime
from pyathena.error import * # noqa
__version__ = '1.2.5'
# Globals https://www.python.org/dev/peps/pep-0249/#globals
apilevel = '2.0'
threadsafety = 3
paramstyle = 'pyformat'
class DBAPITypeObj... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import datetime
from pyathena.error import * # noqa
__version__ = '1.2.4'
# Globals https://www.python.org/dev/peps/pep-0249/#globals
apilevel = '2.0'
threadsafety = 3
paramstyle = 'pyformat'
class DBAPITypeObj... | mit | Python |
35e0d3e5f275c79a80aa843700f621da59fefd6b | Use sys.executable as the default python executable | BenjaminHamon/MyWebsite,BenjaminHamon/MyWebsite | scripts/environment.py | scripts/environment.py | import json
import logging
import os
import sys
log_format = "[{levelname}][{name}] {message}"
def configure_logging(log_level):
logging.basicConfig(level = log_level, format = log_format, style = "{")
logging.addLevelName(logging.DEBUG, "Debug")
logging.addLevelName(logging.INFO, "Info")
logging.addLevelName(l... | import json
import logging
import os
log_format = "[{levelname}][{name}] {message}"
def configure_logging(log_level):
logging.basicConfig(level = log_level, format = log_format, style = "{")
logging.addLevelName(logging.DEBUG, "Debug")
logging.addLevelName(logging.INFO, "Info")
logging.addLevelName(logging.WARN... | mit | Python |
80e2c193a50b248a65f2f26aba71f75b7b6a411c | Use the right rng in CD updates | mclaughlin6464/pylearn2,fyffyt/pylearn2,chrish42/pylearn,sandeepkbhat/pylearn2,lisa-lab/pylearn2,chrish42/pylearn,CIFASIS/pylearn2,se4u/pylearn2,daemonmaker/pylearn2,JesseLivezey/plankton,woozzu/pylearn2,daemonmaker/pylearn2,alexjc/pylearn2,lunyang/pylearn2,skearnes/pylearn2,theoryno3/pylearn2,sandeepkbhat/pylearn2,Jes... | scripts/example_rbm.py | scripts/example_rbm.py | import numpy
import theano
import matplotlib.pyplot as plt
from theano import tensor
from framework.rbm import GaussianBinaryRBM, PersistentCDSampler
from framework.optimizer import SGDOptimizer
from framework.rbm_tools import compute_log_z, compute_nll
if __name__ == "__main__":
data = numpy.random.normal(size=(... | import numpy
import theano
import matplotlib.pyplot as plt
from theano import tensor
from framework.rbm import GaussianBinaryRBM, PersistentCDSampler
from framework.optimizer import SGDOptimizer
from framework.rbm_tools import compute_log_z, compute_nll
if __name__ == "__main__":
data = numpy.random.normal(size=(... | bsd-3-clause | Python |
1038ee0539c3fc141462ec36a801f2ae8f244a9c | Add some extra output to coinc. | richardkiss/pycoin,richardkiss/pycoin | pycoin/cmds/coinc.py | pycoin/cmds/coinc.py | #!/usr/bin/env python
import argparse
from pycoin.networks.registry import full_network_name_for_netcode, network_codes
from pycoin.networks.registry import network_for_netcode
from pycoin.networks.default import get_current_netcode
from pycoin.serialize import b2h
def create_parser():
codes = network_codes()
... | #!/usr/bin/env python
import argparse
from pycoin.networks.registry import full_network_name_for_netcode, network_codes
from pycoin.networks.registry import network_for_netcode
from pycoin.networks.default import get_current_netcode
from pycoin.serialize import b2h
def create_parser():
codes = network_codes()
... | mit | Python |
b64bb7e9ab0f662879e087f075da2e7008ac072e | add docstring. | jwilk/pydiatra,jwilk/pydiatra | pydiatra/__main__.py | pydiatra/__main__.py | # encoding=UTF-8
# Copyright © 2016-2017 Jakub Wilk <jwilk@jwilk.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# in the Software without restriction, including without limitation the rights
# to use,... | # encoding=UTF-8
# Copyright © 2016-2017 Jakub Wilk <jwilk@jwilk.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# in the Software without restriction, including without limitation the rights
# to use,... | mit | Python |
3b44f56c32cb79e78d2b7f067b5af5c302af8a0f | Fix #5 : Implement Elevator with-statement compatibility | oleiade/py-elevator | pyelevator/client.py | pyelevator/client.py | from .base import Client
class RangeIter(object):
def __init__(self, range_datas):
self._container = range_datas if self._valid_range(range_datas) else None
def _valid_range(self, range_datas):
if range_datas and (not isinstance(range_datas, (list, tuple)) or
any(not isinstance(pa... | from .base import Client
class RangeIter(object):
def __init__(self, range_datas):
self._container = range_datas if self._valid_range(range_datas) else None
def _valid_range(self, range_datas):
if range_datas and (not isinstance(range_datas, (list, tuple)) or
any(not isinstance(pa... | mit | Python |
5f5af47841ad3f79b111b4c0d5eb76ac007e4285 | Fix display Logo | epfl-lts2/pygsp,epfl-lts2/pygsp | pygsp/graphs/logo.py | pygsp/graphs/logo.py | # -*- coding: utf-8 -*-
from . import Graph
from pygsp.pointclouds import PointCloud
import numpy as np
class Logo(Graph):
r"""
Create a graph with the GSP Logo.
Examples
--------
>>> from pygsp import graphs
>>> G = graphs.Logo()
"""
def __init__(self, **kwargs):
logo = P... | # -*- coding: utf-8 -*-
from . import Graph
from pygsp.pointclouds import PointCloud
import numpy as np
class Logo(Graph):
r"""
Create a graph with the GSP Logo.
Examples
--------
>>> from pygsp import graphs
>>> G = graphs.Logo()
"""
def __init__(self, **kwargs):
logo = P... | bsd-3-clause | Python |
cbc3553b509a8f6e08692bb04240774d027c0454 | Update to 2.0.15 | arraylabs/pymyq | pymyq/__version__.py | pymyq/__version__.py | """Define a version constant."""
__version__ = '2.0.15'
| """Define a version constant."""
__version__ = '2.0.14'
| mit | Python |
e6267591470003beaa3c116896e173423701be04 | fix imports | paolodragone/PyMzn | pymzn/mzn/process.py | pymzn/mzn/process.py | """process.py
This package provides utilities for running synchronous external processes.
"""
import os
import subprocess
from time import monotonic as _time
__all__ = ['run_process']
class CompletedProcessWrapper:
def __init__(self, proc, start_time, end_time):
self._proc = proc
self.start_... | """process.py
This package provides utilities for running synchronous external processes.
"""
import os
from time import monotonic as _time
from subprocess import Popen, PIPE, TimeoutExpired, CalledProcessError
__all__ = ['run_process']
class CompletedProcessWrapper:
def __init__(self, proc, start_time, end... | mit | Python |
01aa219b0058cbfbdb96e890f510fa275f3ef790 | Use or operator in python to tidy up completion building. | OmniSharp/omnisharp-vim,OmniSharp/omnisharp-vim,OmniSharp/omnisharp-vim | python/Completion.py | python/Completion.py | import vim, syncrequest, types
class Completion:
def get_completions(self, column, partialWord):
parameters = {}
parameters['column'] = vim.eval(column)
parameters['wordToComplete'] = vim.eval(partialWord)
parameters['WantDocumentationForEveryCompletionResult'] = \
bool(... | import vim, syncrequest, types
class Completion:
def get_completions(self, column, partialWord):
parameters = {}
parameters['column'] = vim.eval(column)
parameters['wordToComplete'] = vim.eval(partialWord)
parameters['WantDocumentationForEveryCompletionResult'] = \
bool(... | mit | Python |
5badb0ed6a13e756e16bdf1c1cd9ff7992cddae7 | allow for empty string passed to query_conditional | drousis/pywebdata,pywebdata/pywebdata | pywebdata/parsers.py | pywebdata/parsers.py | import re
import operator
from collections import defaultdict
#borrowed from standard library distutils.versionpredicate
compmap = {
"<": operator.lt,
"<=": operator.le,
"=": operator.eq,
">": operator.gt,
">=": operator.ge,
"!=": operator.ne
}
condition_splitter = re.compile(r'\s*(\D\w*)\... | import re
import operator
from collections import defaultdict
#borrowed from standard library distutils.versionpredicate
compmap = {
"<": operator.lt,
"<=": operator.le,
"=": operator.eq,
">": operator.gt,
">=": operator.ge,
"!=": operator.ne
}
labels = ['name', 'operator', 'value']
condit... | mit | Python |
9010757f84ccfbbeae743a8ba1a287d858ac9efb | Fix the python test. | felixduvallet/ros-travis-integration,felixduvallet/ros-travis-integration,felixduvallet/ros-travis-integration | ros_pkg_with_tests/scripts/test/test_double.py | ros_pkg_with_tests/scripts/test/test_double.py | #!/usr/bin/env python
import unittest
import rospy
import rostest
from scripts.double import double
class TestCase(unittest.TestCase):
def test_four(self):
ret = double(4)
self.assertEqual(8, ret)
def test_two(self):
ret = double(2)
self.assertEqual(4, ret)
def test_goo... | #!/usr/bin/env python
import unittest
import rospy
import rostest
from scripts.double import double
class TestCase(unittest.TestCase):
def test_four(self):
ret = double(2)
self.assertEqual(8, ret)
def test_two(self):
ret = double(2)
self.assertEqual(4, ret)
def test_goo... | bsd-3-clause | Python |
0de16f700c0a07d3d11b5f9b747047e4af8d6cb3 | Update generators.py | 100stacks/100stacks.github.io,100stacks/100stacks.github.io,100stacks/100stacks.github.io | blog/bits/generators.py | blog/bits/generators.py | # Python Generators - How, Why, and When to use them
# https://www.youtube.com/watch?v=bD05uGo_sVI
## Simple List
def square_numbers(nums):
result = []
for i in nums:
result.append(i*i)
return result
sample = [1,2,3,4,5]
#print(square_numbers(sample)) # outputs [1, 4, 9, 16, 25]
# Now using Gene... | # Python Generators - How, Why, and When to use them
# https://www.youtube.com/watch?v=bD05uGo_sVI
## Simple List
def square_numbers(nums):
result = []
for i in nums:
result.append(i*i)
return result
sample = [1,2,3,4,5]
#print(square_numbers(sample)) # outputs [1, 4, 9, 16, 25]
# Now using Gene... | unlicense | Python |
ad5fe39ba5d5d500dd65d588fd0fd187d9c73a2c | Fix imports in rbm_example.py. | hyqneuron/pylearn2-maxsom,fulmicoton/pylearn2,JesseLivezey/plankton,fulmicoton/pylearn2,Refefer/pylearn2,pkainz/pylearn2,pkainz/pylearn2,lisa-lab/pylearn2,hantek/pylearn2,CIFASIS/pylearn2,bartvm/pylearn2,nouiz/pylearn2,fyffyt/pylearn2,nouiz/pylearn2,w1kke/pylearn2,skearnes/pylearn2,Refefer/pylearn2,alexjc/pylearn2,alex... | scripts/rbm_example.py | scripts/rbm_example.py | import numpy
import theano
import matplotlib.pyplot as plt
from theano import tensor
from framework.rbm import GaussianBinaryRBM, PersistentCDSampler
from framework.optimizer import RBMOptimizer
from framework.rbm_tools import compute_log_z, compute_nll
if __name__ == "__main__":
data = numpy.random.normal(size=(... | import numpy
import theano
import matplotlib.pyplot as plt
from theano import tensor
from rbm import GaussianBinaryRBM, PersistentCDSampler
from optimizer import RBMOptimizer
from rbm_tools import compute_log_z, compute_nll
if __name__ == "__main__":
data = numpy.random.normal(size=(500, 20))
conf = {
... | bsd-3-clause | Python |
3438d2685154f02fc65b567c8a47afefccecf888 | Add primary key to scan_records | notapresent/rbm2m,notapresent/rbm2m | rbm2m/models/scan.py | rbm2m/models/scan.py | # -*- coding: utf-8 -*-
import datetime
from sqlalchemy import (Column, Integer, String, DateTime, ForeignKey, Table)
from sqlalchemy.orm import relationship, backref
from .base import Base
scan_records = Table(
'scan_records',
Base.metadata,
Column('scan_id', Integer, ForeignKey('scans.id'), primary_key... | # -*- coding: utf-8 -*-
import datetime
from sqlalchemy import (Column, Integer, String, DateTime, ForeignKey, Table)
from sqlalchemy.orm import relationship, backref
from .base import Base
scan_records = Table(
'scan_records',
Base.metadata,
Column('scan_id', Integer, ForeignKey('scans.id')),
Column... | apache-2.0 | Python |
76dd8c7b000a97b4c6b808d69294e5f1d3eee3e4 | Add explicit xml export options (indent, new line and encoding) | rdmorganiser/rdmo,rdmorganiser/rdmo,rdmorganiser/rdmo | rdmo/core/exports.py | rdmo/core/exports.py | from xml.dom.minidom import parseString
from django.http import HttpResponse
class XMLResponse(HttpResponse):
def __init__(self, xml, name=None):
super().__init__(prettify_xml(xml), content_type='application/xml')
if name:
self['Content-Disposition'] = 'filename="{}.xml"'.format(name... | from xml.dom.minidom import parseString
from django.http import HttpResponse
class XMLResponse(HttpResponse):
def __init__(self, xml, name=None):
super().__init__(prettify_xml(xml), content_type='application/xml')
if name:
self['Content-Disposition'] = 'filename="{}.xml"'.format(name... | apache-2.0 | Python |
aaaaa80f482750d0326ac4bfd1fbf424d6de5ad1 | Add whitespace | mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation | falcom/api/__init__.py | falcom/api/__init__.py | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from .reject_list import VolumeDataFromBarcode
| # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from .reject_list import VolumeDataFromBarcode
| bsd-3-clause | Python |
bbe6bb73fdf74d640b57ebabbc516eee6dd845ed | Use ~/.sheepdog. Closes #6. | adamgreig/sheepdog | sheepdog/deployment.py | sheepdog/deployment.py | # Sheepdog
# Copyright 2013 Adam Greig
#
# Released under the MIT license. See LICENSE file for details.
"""
Code for deploying code to servers and executing jobs on GridEngine.
Right now this is a little unwieldly and uses SSH as a subprocess.
"""
# All I want for Christmas is Python 3 support in Paramiko.
# Until ... | # Sheepdog
# Copyright 2013 Adam Greig
#
# Released under the MIT license. See LICENSE file for details.
"""
Code for deploying code to servers and executing jobs on GridEngine.
Right now this is a little unwieldly and uses SSH as a subprocess.
"""
# All I want for Christmas is Python 3 support in Paramiko.
# Until ... | mit | Python |
3be1fb684be9bcdae544ec7dac7dcb0b3af3854f | Bump version number to reflect current dev status. | mlavin/django-selectable,mlavin/django-selectable,affan2/django-selectable,affan2/django-selectable,mlavin/django-selectable,affan2/django-selectable | selectable/__init__.py | selectable/__init__.py | "Auto-complete selection widgets using Django and jQuery UI."
__version__ = '0.8.0dev' | "Auto-complete selection widgets using Django and jQuery UI."
__version__ = '0.7.0' | bsd-2-clause | Python |
895e0c2ad3354cf78aecff5738a71c0df5ccf31c | throw error on delete of new model | csira/wallace,csira/wallace | wallace/db/pg/model.py | wallace/db/pg/model.py | from wallace.db.base import RelationalModel
from wallace.db.base import DoesNotExist, ValidationError
class PostgresModel(RelationalModel):
table = None
@classmethod
def find_one(cls, **kwargs):
data = cls.table.fetchall(limit=2, **kwargs)
if not data:
raise DoesNotExist
... | from wallace.db.base import RelationalModel
from wallace.db.base import DoesNotExist, ValidationError
class PostgresModel(RelationalModel):
table = None
@classmethod
def find_one(cls, **kwargs):
data = cls.table.fetchall(limit=2, **kwargs)
if not data:
raise DoesNotExist
... | bsd-3-clause | Python |
bd77c1b4e2c877c7de4a1357fbfc2458e8373a14 | Remove issuer_name="PyPI" default kwarg (#5887) | pypa/warehouse,pypa/warehouse,pypa/warehouse,pypa/warehouse | warehouse/utils/otp.py | warehouse/utils/otp.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 the Li... | # 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 the Li... | apache-2.0 | Python |
e0d01c3523b92673d21e9b92dcd71cca5795aeea | use urandom instead of /dev/random | jhaals/python-filebutler | filebutler/password.py | filebutler/password.py | #!/usr/bin/env python
# Copyright (c) 2011-2012, Johan Haals <johan.haals@gmail.com>
# All rights reserved.
import hmac
import hashlib
class Password:
# TODO
# Support for multiple hash algorithms
def __init__(self, secret_key):
self.secret_key = secret_key
def random(self, chars):
... | #!/usr/bin/env python
# Copyright (c) 2011-2012, Johan Haals <johan.haals@gmail.com>
# All rights reserved.
import hmac
import hashlib
class Password:
# TODO
# Support for multiple hash algorithms
def __init__(self, secret_key):
self.secret_key = secret_key
def random(self, chars):
... | bsd-3-clause | Python |
7331f6e267229549355e9abba393e1b39be148ea | Fix a spelling mistake in exception.py | bcornec/python-redfish,uggla/python-redfish,bcornec/python-redfish,bcornec/python-redfish,uggla/python-redfish,uggla/python-redfish | redfish/exception.py | redfish/exception.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
from builtins import str
from . import config
standard_library.install_aliases()
class RedfishException(Exce... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
from builtins import str
from . import config
standard_library.install_aliases()
class RedfishException(Exce... | apache-2.0 | Python |
a1a4474a16ae846c2d15399f54ce0f5574a2d4d6 | improve manifest | JayVora-SerpentCS/sale-reporting,yvaucher/sale-reporting,credativUK/sale-reporting,acsone/sale-reporting,JayVora-SerpentCS/sale-reporting,massot/sale-reporting | sale_order_proforma_webkit/__openerp__.py | sale_order_proforma_webkit/__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2014 Camptocamp SA (http://www.camptocamp.com)
# @author Romain Deheele, Vincent Renaville
#
# This program is free software: you can redistribute it and/or modify
# it under the terms o... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2014 Camptocamp SA (http://www.camptocamp.com)
# @author Romain Deheele, Vincent Renaville
#
# This program is free software: you can redistribute it and/or modify
# it under the terms o... | agpl-3.0 | Python |
db8abbc46e3dfccc330b5ba7dd99e3e6a4c16160 | Use request.path to compare start link. | incuna/django-rewrite-external-links,incuna/django-rewrite-external-links | rewrite_external_links/middleware.py | rewrite_external_links/middleware.py | import re
from django.conf import settings
from django.core.urlresolvers import reverse
from django.template.defaultfilters import urlencode
from django.utils.html_parser import HTMLParser
SAFE_EXTERNAL_LINK_PATTERNS = getattr(settings, 'SAFE_EXTERNAL_LINK_PATTERNS', ())
safe_urls = ''
if SAFE_EXTERNAL_LINK_PATTERNS... | import re
from django.conf import settings
from django.core.urlresolvers import reverse
from django.template.defaultfilters import urlencode
from django.utils.html_parser import HTMLParser
SAFE_EXTERNAL_LINK_PATTERNS = getattr(settings, 'SAFE_EXTERNAL_LINK_PATTERNS', ())
safe_urls = ''
if SAFE_EXTERNAL_LINK_PATTERNS... | bsd-2-clause | Python |
750bca9dde6fdf15458bc3bfb9eb6af4549ba29c | tweak document id url regex | emory-libraries/findingaids,mprefer/findingaids,emory-libraries/findingaids,mprefer/findingaids | findingaids/fa/urls.py | findingaids/fa/urls.py | from django.conf.urls.defaults import *
urlpatterns = patterns('findingaids.fa.views',
(r'^titles/?$', 'browse_titles'),
(r'^titles/(?P<letter>[A-Z])$', 'titles_by_letter'),
(r'^documents/(?P<id>[A-Za-z0-9-.]+)$', 'view_fa'),
(... | from django.conf.urls.defaults import *
urlpatterns = patterns('findingaids.fa.views',
(r'^titles/?$', 'browse_titles'),
(r'^titles/(?P<letter>[A-Z])$', 'titles_by_letter'),
(r'^documents/(?P<id>[a-z0-9-.]+)$', 'view_fa'),
(r'^... | apache-2.0 | Python |
44dc3ad69882d8c56d7ef1f8862e2d3ca4aefe14 | Set the default logging level early | mineo/lala,mineo/lala | lala/main.py | lala/main.py | import ConfigParser
import logging
import os
from lala import config
from lala.factory import LalaFactory
from twisted.application import service, internet
from twisted.python import log
from twisted.python.usage import Options
CONFIG_DEFAULTS = {
"channels": "",
"plugins": "",
"nickserv_password": None,... | import ConfigParser
import logging
import os
from lala import config
from lala.factory import LalaFactory
from twisted.application import service, internet
from twisted.python import log
from twisted.python.usage import Options
CONFIG_DEFAULTS = {
"channels": "",
"plugins": "",
"nickserv_password": None,... | mit | Python |
aef60d17607a0819e24a2a61304bd5ca38289d50 | Use the new tools/clean_output_directory.py script for clobbering builders. | eunchong/build,eunchong/build,eunchong/build,eunchong/build | scripts/slave/dart/dart_util.py | scripts/slave/dart/dart_util.py | #!/usr/bin/python
# Copyright (c) 2012 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.
"""Utils for the dart project.
"""
import optparse
import subprocess
import sys
def clobber():
cmd = [sys.executable,
'./t... | #!/usr/bin/python
# Copyright (c) 2012 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.
"""Utils for the dart project.
"""
import optparse
import os
import sys
from common import chromium_utils
def clobber():
print('Cl... | bsd-3-clause | Python |
410e8100f7891a84a4d287cd8e763a486fc45eb7 | Add create_tables, drop_tables helpers | kvikshaug/btc.kvikshaug.no,kvikshaug/btc.kvikshaug.no,kvikshaug/btc.kvikshaug.no,kvikshaug/btc.kvikshaug.no | web/app/database.py | web/app/database.py | import sqlalchemy.ext.declarative
import sqlalchemy.orm
from conf import settings
engine = sqlalchemy.create_engine(settings['DB_URL'])
db_session = sqlalchemy.orm.scoped_session(
sqlalchemy.orm.sessionmaker(
autocommit=False,
autoflush=False,
bind=engine,
)
)
Base = sqlalchemy.ext.d... | import sqlalchemy.ext.declarative
import sqlalchemy.orm
from conf import settings
engine = sqlalchemy.create_engine(settings['DB_URL'])
db_session = sqlalchemy.orm.scoped_session(
sqlalchemy.orm.sessionmaker(
autocommit=False,
autoflush=False,
bind=engine,
)
)
Base = sqlalchemy.ext.d... | unlicense | Python |
bc7937b7c6c9be24fbb86a9b56241a11ee586612 | Simplify ScheduledDisposable | ReactiveX/RxPY,ReactiveX/RxPY | rx/disposable/scheduleddisposable.py | rx/disposable/scheduleddisposable.py | from threading import RLock
from typing import Any
from rx.core import abc
from .singleassignmentdisposable import SingleAssignmentDisposable
class ScheduledDisposable(abc.DisposableBase):
"""Represents a disposable resource whose disposal invocation will
be scheduled on the specified Scheduler"""
def _... | from threading import RLock
from typing import Any
from rx.core import abc
class ScheduledDisposable(abc.DisposableBase):
"""Represents a disposable resource whose disposal invocation will
be scheduled on the specified Scheduler"""
def __init__(
self, scheduler: abc.SchedulerBase, disposable: ab... | mit | Python |
230c2f31c449056020c18e386875f9fd7bec2988 | Fix tip link in __init__.py docs | Khan/wtforms | wtforms/__init__.py | wtforms/__init__.py | """
WTForms
=======
WTForms is a forms handling library for web applications in python. For
documentation and help please visit the `WTForms website`_.
The `WTForms tip`_ is installable via `easy_install` with ``easy_install
WTForms==dev``.
.. _WTForms website: http://wtforms.simplecodes.com/
.. _WTForms tip: http:/... | """
WTForms
=======
WTForms is a forms handling library for web applications in python. For
documentation and help please visit the `WTForms website`_.
The `WTForms tip`_ is installable via `easy_install` with ``easy_install
WTForms==dev``.
.. _WTForms website: http://wtforms.simplecodes.com/
.. _WTForms tip: http:/... | bsd-3-clause | Python |
458b8e87216123a1292ca68103bc562c081ba144 | fix imports | ActiDoo/gamification-engine,ActiDoo/gamification-engine,ActiDoo/gamification-engine,ActiDoo/gamification-engine | gengine/app/cache.py | gengine/app/cache.py | from gengine.base.cache import create_cache
caches = {}
cache_general = None
cache_goal_evaluation = None
cache_achievement_eval = None
cache_achievements_users_levels = None
cache_achievements_by_user_for_today = None
cache_goal_statements = None
cache_translations = None
def init_caches():
global cache_general... | from gengine.base.cache import create_cache
caches = {}
def init_caches():
global cache_general
cache_general = create_cache("general")
global cache_achievement_eval
cache_achievement_eval = create_cache("achievement_eval")
global cache_achievements_by_user_for_today
cache_achievements_by_us... | mit | Python |
8fa34b8efbddd018551d1c4698cff93153e40e59 | Rename local variables to have more descriptive names -- should be a positive change even if the original paper uses 'c' and 'q', but this should also be reflected in the documentation | MaLL-UFSCar/bayessets | bayessets/bayessets.py | bayessets/bayessets.py | import numpy as np
from scipy.sparse import csr_matrix
class BernoulliBayesianSet:
def __init__(self, dataset, alpha, beta):
self.dataset = csr_matrix(dataset)
self.alpha = alpha
self.beta = beta
self.alpha_plus_beta = self.alpha + self.beta
self.log_alpha = np.log(self.alp... | import numpy as np
from scipy.sparse import csr_matrix
class BernoulliBayesianSet:
def __init__(self, dataset, alpha, beta):
self.X = csr_matrix(dataset)
self.alpha = alpha
self.beta = beta
self.alpha_plus_beta = self.alpha + self.beta
self.log_alpha = np.log(self.alpha)
... | mit | Python |
a05f3fbca8f4ec3c64ecadd08730e755880f94fb | Update fletching.py | jwelch92/fletching | fletching/fletching.py | fletching/fletching.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# https://github.com/HappenApps/Quiver/wiki/Quiver-Data-Format
import json
from pathlib import Path
from pprint import pprint as pp
import sys
fletchmod = sys.modules[__name__]
def load_from_path(path, ext, obj):
ret = {}
lib_dir = Path(path)
data = [x for... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import json
from pathlib import Path
from pprint import pprint as pp
import sys
fletchmod = sys.modules[__name__]
def load_from_path(path, ext, obj):
ret = {}
lib_dir = Path(path)
data = [x for x in lib_dir.iterdir() if x.is_dir() and x.suffix == ext]
... | mit | Python |
4cc4bfe389662ee3b6d7c87ae770854c79c71318 | sort countries | openregister/openregister.widgets,openregister/openregister-widgets,openregister/openregister-widgets,openregister/widgets-demo,openregister/openregister.widgets,openregister/openregister-widgets,openregister/openregister-widgets,openregister/widgets-demo,openregister/openregister.widgets,openregister/openregister.widg... | widgets/frontend/views.py | widgets/frontend/views.py | from flask import (
Blueprint,
render_template,
current_app
)
import requests
frontend = Blueprint('frontend', __name__, template_folder='templates')
@frontend.route('/')
def index():
return render_template('index.html')
@frontend.route('/country-picker')
def country_picker():
country_register... | from flask import (
Blueprint,
render_template,
current_app
)
import requests
frontend = Blueprint('frontend', __name__, template_folder='templates')
@frontend.route('/')
def index():
return render_template('index.html')
@frontend.route('/country-picker')
def country_picker():
country_register... | mit | Python |
d895a495b62a0dd71b21d308e0a84ff308949095 | remove extraneous code from _client | llimllib/slackrtm | slackclient/_client.py | slackclient/_client.py | #!/usr/bin/python
# mostly a proxy object to abstract how some of this works
import json
from slackclient._server import Server
class SlackClient(object):
def __init__(self, token):
self.token = token
self.server = Server(self.token, False)
def rtm_connect(self):
try:
sel... | #!/usr/bin/python
# mostly a proxy object to abstract how some of this works
import json
from slackclient._server import Server
class SlackClient(object):
def __init__(self, token):
self.token = token
self.server = Server(self.token, False)
def rtm_connect(self):
try:
sel... | mit | Python |
2bca3e060008df61df2731d87380ad0efb2c8899 | update to v0.2.0 | phac-nml/bio_hansel | bio_hansel/__init__.py | bio_hansel/__init__.py | # -*- coding: utf-8 -*-
__version__ = '0.2.0'
program_name = 'bio_hansel'
program_summary = 'Subtype Salmonella enterica genomes using 33bp k-mer typing schemes.'
program_desc = program_summary + '''
Includes schemes for Heidelberg and Enteritidis subtyping.
Developed by Geneviève Labbé, James Robertson, Peter Kruczki... | # -*- coding: utf-8 -*-
__version__ = '0.1.0'
program_name = 'bio_hansel'
program_summary = 'Subtype Salmonella enterica genomes using 33bp k-mer typing schemes.'
program_desc = program_summary + '''
Includes schemes for Heidelberg and Enteritidis subtyping.
Developed by Geneviève Labbé, James Robertson, Peter Kruczki... | apache-2.0 | Python |
7c2f32d9eec84715e93b7981c22bcbcca8b3452f | Fix bug in relative location. | rfugger/villagescc,rfugger/villagescc,rfugger/villagescc,rfugger/villagescc | cc/geo/templatetags/location.py | cc/geo/templatetags/location.py | from django import template
register = template.Library()
@register.simple_tag
def relative_location(loc, user_loc):
"Returns a short useful description of `loc` for someone at `user_loc`."
# In same city if city names are identical and points are within 40km:
# Just give neighborhood.
if (loc.city.lo... | from django import template
register = template.Library()
@register.simple_tag
def relative_location(loc, user_loc):
"Returns a short useful description of `loc` for someone at `user_loc`."
# In same city if city names are identical and points are within 40km.
if (loc.city.lower() == user_loc.city.lower()... | agpl-3.0 | Python |
3dcb57bf86971fd0321b16ca7bd6a6cf41beef88 | Update file_insert.py | wizardofozzie/pybitcointools | bitcoin/file_insert.py | bitcoin/file_insert.py | import io, struct, os, sys
from binascii import crc32, unhexlify, hexlify
from bitcoin import *
from bitcoin.pyspecials import safe_hexlify, safe_unhexlify
def mk_multisig_scriptpubkey(fo):
# takes file_object fo and returns scriptpubkey as hex
data = fo.read(65*3)
if not data:
return None
scri... | import io, struct, os, sys
from binascii import crc32, unhexlify, hexlify
from bitcoin import *
from bitcoin.pyspecials import safe_hexlify, safe_unhexlify
global OP_CHECKSIG, OP_CHECKMULTISIG, OP_PUSHDATA1, OP_DUP, OP_HASH160, OP_EQUALVERIFY
OP_CHECKSIG = b'\xac'
OP_CHECKMULTISIG = b'\xae'
OP_PUSHDATA1 = ... | mit | Python |
e9f0bb1d3e320565f97e7c82d74554633c7a7620 | increase tolerance in deriv array test | relf/smt,SMTorg/smt,bouhlelma/smt,SMTorg/smt,bouhlelma/smt,relf/smt | smt/tests/test_array_outputs.py | smt/tests/test_array_outputs.py |
import numpy as np
import unittest
from smt.utils.sm_test_case import SMTestCase
from smt.utils.silence import Silence
from smt.surrogate_models import QP, KRG
from smt.examples.rans_crm_wing.rans_crm_wing import (
get_rans_crm_wing,
plot_rans_crm_wing,
)
def setup_sm(sm_name, settings={}):
xt, yt, xli... |
import numpy as np
import unittest
from smt.utils.sm_test_case import SMTestCase
from smt.utils.silence import Silence
from smt.surrogate_models import QP, KRG
from smt.examples.rans_crm_wing.rans_crm_wing import (
get_rans_crm_wing,
plot_rans_crm_wing,
)
def setup_sm(sm_name, settings={}):
xt, yt, xli... | bsd-3-clause | Python |
9dccac92d05973baf07bc85912ec0676263399b8 | use standard python modules to retrieve the metadata; remove the tmp file | sassoftware/mirrorball,sassoftware/mirrorball | repomd/repository.py | repomd/repository.py | #
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/... | #
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/... | apache-2.0 | Python |
c94375b875a5cfb56a5a7fff8fee718362534d53 | Fix document | ktnyt/chainer,chainer/chainer,delta2323/chainer,chainer/chainer,keisuke-umezawa/chainer,jnishi/chainer,pfnet/chainer,cupy/cupy,niboshi/chainer,hvy/chainer,jnishi/chainer,ysekky/chainer,chainer/chainer,wkentaro/chainer,tkerola/chainer,hvy/chainer,aonotas/chainer,ktnyt/chainer,cupy/cupy,okuta/chainer,wkentaro/chainer,nib... | chainer/links/loss/black_out.py | chainer/links/loss/black_out.py | import numpy
import chainer
from chainer import cuda
from chainer.functions.loss import black_out
from chainer import link
from chainer.utils import walker_alias
class BlackOut(link.Link):
"""BlackOut loss layer.
.. seealso:: :func:`~chainer.functions.black_out` for more detail.
Args:
in_size ... | import numpy
import chainer
from chainer import cuda
from chainer.functions.loss import black_out
from chainer import link
from chainer.utils import walker_alias
class BlackOut(link.Link):
"""BlackOut loss layer.
.. seealso:: :func:`~chainer.functions.black_out` for more detail.
Attributes:
W ... | mit | Python |
a4aec0f602d10d6b4d48a8167458ac6b801f06db | Update repository_rules.bzl (#730) | googleapis/gax-java,vam-google/gax-java,googleapis/gax-java,vam-google/gax-java | repository_rules.bzl | repository_rules.bzl | # Copyright 2019 Google LLC
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# ... | # Copyright 2019 Google LLC
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# ... | bsd-3-clause | Python |
f749ca77b6ca812f1ba1a4e1967af6126f951071 | improve exceptions | bndl/bndl,bndl/bndl | bndl/rmi/invocation.py | bndl/rmi/invocation.py | import asyncio
import logging
import traceback
from bndl.util.aio import run_coroutine_threadsafe
from bndl.rmi.messages import Request
logger = logging.getLogger(__name__)
class InvocationException(Exception):
'''
Exception indicating a RMI failed. This exception is 'raised from' a 'reconstructed'
exc... | import asyncio
import logging
import traceback
from bndl.util.aio import run_coroutine_threadsafe
from bndl.rmi.messages import Request
logger = logging.getLogger(__name__)
class InvocationException(Exception):
'''
Exception indicating a RMI failed. This exception is 'raised from' a 'reconstructed'
exc... | apache-2.0 | Python |
97c7d8d1a71c01fbaaa97494d4044a0c2357483b | change display modes ordering | rsalmei/clearly | clearly/client/display_modes.py | clearly/client/display_modes.py | from enum import Enum
from typing import Union
_VALUES = {}
class EnumSpecDescription(Enum):
def __new__(cls, description, *spec):
obj = object.__new__(cls)
obj._value_ = len(_VALUES) + 1
_VALUES[obj._value_] = obj
obj.__description = description
obj.__spec = spec
... | from enum import Enum
from typing import Union
_VALUES = {}
class EnumSpecDescription(Enum):
def __new__(cls, description, *spec):
obj = object.__new__(cls)
obj._value_ = len(_VALUES) + 1
_VALUES[obj._value_] = obj
obj.__description = description
obj.__spec = spec
... | mit | Python |
ee9318f44b8f09691023d922bb9eabbe0f45167c | remove add button from bika_storageinventories and add it in room | hocinebendou/bika.gsoc,hocinebendou/bika.gsoc,hocinebendou/bika.gsoc | bika/lims/browser/storageunit.py | bika/lims/browser/storageunit.py | from bika.sanbi.controlpanel.bika_storageinventories import StorageInventoriesView
from bika.sanbi.controlpanel.bika_storagemanagements import StorageManagementsView
from bika.sanbi import bikaMessageFactory as _
class StorageUnitInventoryView(StorageInventoriesView):
def __init__(self, context, request):
... | from bika.sanbi.controlpanel.bika_storageinventories import StorageInventoriesView
from bika.sanbi.controlpanel.bika_storagemanagements import StorageManagementsView
class StorageUnitInventoryView(StorageInventoriesView):
def __init__(self, context, request):
super(StorageUnitInventoryView, self).__init__... | mit | Python |
fd5ba834abe919b531ae56042416a6f9397acd98 | Add some dredd hooks | SCUEvals/scuevals-api,SCUEvals/scuevals-api | tests/dredd/hooks.py | tests/dredd/hooks.py | import dredd_hooks as hooks
from flask_jwt_extended import create_access_token
from scuevals_api import create_app, db
from scuevals_api.cmd import init_db
from scuevals_api.models import Role
from tests import seed_db
from tests.fixtures import factories
stash = {}
@hooks.before_all
def before_all(trans):
app ... | import dredd_hooks as hooks
from flask_jwt_extended import create_access_token
from scuevals_api import create_app, db
from scuevals_api.cmd import init_db
from scuevals_api.models import Role
from tests import seed_db
from tests.fixtures.factories import StudentFactory
@hooks.before_all
def before_all(trans):
a... | agpl-3.0 | Python |
a6ce85fa26235769b84003cf3cd73999b343bee6 | Make temp dirs for each scenario. | coddingtonbear/jirafs,coddingtonbear/jirafs | tests/environment.py | tests/environment.py | import os
import shutil
import tempfile
def before_scenario(context, *args, **kwargs):
context.starting_dir = os.getcwd()
context.temp_dir = tempfile.mkdtemp()
os.chdir(context.temp_dir)
def after_scenario(context, *args, **kwargs):
os.chdir(context.starting_dir)
shutil.rmtree(context.temp_dir)
| import os
import shutil
import tempfile
def before_all(context):
context.starting_dir = os.getcwd()
context.temp_dir = tempfile.mkdtemp()
os.chdir(context.temp_dir)
def after_all(context):
os.chdir(context.starting_dir)
shutil.rmtree(context.temp_dir)
| mit | Python |
80f9e7cde4c8d9d549417655bb6e3f0a69dafd01 | Update P01_fantasy_game_inventory: working solution | JoseALermaIII/python-tutorials,JoseALermaIII/python-tutorials | books/AutomateTheBoringStuffWithPython/Chapter05/PracticeProjects/P01_fantasy_game_inventory.py | books/AutomateTheBoringStuffWithPython/Chapter05/PracticeProjects/P01_fantasy_game_inventory.py | # This program models a player's inventory from a fantasy game
#
# You are creating a fantasy video game. The data structure to model the player’s
# inventory will be a dictionary where the keys are string values describing the item
# in the inventory and the value is an integer value detailing how many of that item
# ... | # This program models a player's inventory from a fantasy game
# You are creating a fantasy video game. The data structure to model the player’s
# inventory will be a dictionary where the keys are string values describing the item
# in the inventory and the value is an integer value detailing how many of that item
# th... | mit | Python |
c4bac4921fbce167198f4ce925e61d7abaad8867 | write untested human player | IanDCarroll/xox | source/player_chair.py | source/player_chair.py | class Player(object):
def move(self, board):
board[1][1] = 1
return board
class Human(Player):
def move(self, board):
row = raw_input("Which row do you choose? ")
col = raw_input("Which column do you choose? ")
board[row][col] = 1
return board
| class Player(object):
def move(self, board):
board[1][1] = 1
return board
| mit | Python |
d91b9fe330f61b2790d3c4a84190caa2b798d80e | Fix build errors with Python <3.6 | tbielawa/bitmath,tbielawa/bitmath | bitmath/integrations/__init__.py | bitmath/integrations/__init__.py | # -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright © 2014-2016 Tim Bielawa <timbielawa@gmail.com>
# See GitHub Contributors Graph for more information
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to ... | # -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright © 2014-2016 Tim Bielawa <timbielawa@gmail.com>
# See GitHub Contributors Graph for more information
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to ... | mit | Python |
e868974324c7917be7a3d6c443011912e06a106b | Change how we calculate first of next month in payouts. | onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle | bluebottle/bb_payouts/signals.py | bluebottle/bb_payouts/signals.py | from decimal import Decimal
from datetime import timedelta
from bluebottle.bb_projects.models import ProjectPhase
from bluebottle.utils.model_dispatcher import get_project_payout_model
from bluebottle.utils.utils import StatusDefinition
from django.utils import timezone
def create_payout_finished_project(sender, ins... | from decimal import Decimal
from datetime import timedelta
from bluebottle.bb_projects.models import ProjectPhase
from bluebottle.utils.model_dispatcher import get_project_payout_model
from bluebottle.utils.utils import StatusDefinition
from django.utils import timezone
def create_payout_finished_project(sender, ins... | bsd-3-clause | Python |
a625ef717d15fb4cb1302474f12e89ea87da3f91 | write ugly mock algorithm for computer player | IanDCarroll/xox | source/player_chair.py | source/player_chair.py | class Player(object):
def move(self, board):
board[1][1] = 1
return board
class Human(Player):
def move(self, board):
row = raw_input("Which row do you choose? ")
col = raw_input("Which column do you choose? ")
board[row][col] = 10
return board
class Computer(Pl... | class Player(object):
def move(self, board):
board[1][1] = 1
return board
class Human(Player):
def move(self, board):
row = raw_input("Which row do you choose? ")
col = raw_input("Which column do you choose? ")
board[row][col] = 10
return board
| mit | Python |
a42a125bdf567b94ff15d436c0623ce7bc6ea48a | Comment test analyze function | abraia/abraia-python | tests/test_client.py | tests/test_client.py | import os
import pytest
from abraia import Client, APIError
client = Client()
userid = client.check()
filename = 'tiger.jpg'
def test_list_files():
"""Test an API call to list stored files and folders"""
files, folders = client.list()
assert isinstance(files, list)
assert isinstance(folders, list)
... | import os
import pytest
from abraia import Client, APIError
client = Client()
userid = client.check()
filename = 'tiger.jpg'
def test_list_files():
"""Test an API call to list stored files and folders"""
files, folders = client.list()
assert isinstance(files, list)
assert isinstance(folders, list)
... | mit | Python |
f66deba2f1674ba02b71996d75fcf5934f9d1518 | Convert config tests to pytest. | okin/nikola,getnikola/nikola,getnikola/nikola,okin/nikola,okin/nikola,okin/nikola,getnikola/nikola,getnikola/nikola | tests/test_config.py | tests/test_config.py | # -*- coding: utf-8 -*-
import os
import re
from nikola import __main__ as nikola
import pytest
@pytest.fixture
def metadata_option():
return "ADDITIONAL_METADATA"
@pytest.fixture(scope="module")
def test_dir():
script_root = os.path.dirname(__file__)
return os.path.join(script_root, "data", "test_con... | # -*- coding: utf-8 -*-
import os
import re
from nikola import __main__ as nikola
from .base import BaseTestCase
class ConfigTest(BaseTestCase):
"""Provides tests for the configuration-file handling."""
@classmethod
def setUpClass(self):
self.metadata_option = "ADDITIONAL_METADATA"
scrip... | mit | Python |
53fde402b8a7ecbbf0dfee4774fa745aca6bb20f | improve test | obestwalter/i3configger | tests/test_config.py | tests/test_config.py | import json
from pathlib import Path
import i3configger.paths
from i3configger import paths
def test_no_config(tmpdir, monkeypatch):
"""Given empty sources directory a new config is created from defaults"""
tmpdir = Path(tmpdir)
monkeypatch.setattr(paths, 'get_i3_config_path', lambda: tmpdir)
assert ... | import json
from pathlib import Path
import i3configger.paths
from i3configger import paths
def test_no_config(tmpdir, monkeypatch):
"""Given empty sources directory a new config is created from defaults"""
monkeypatch.setattr(paths, 'get_i3_config_path', lambda: Path(tmpdir))
path = i3configger.paths.ge... | mit | Python |
53034365a5878212315823c9f81a198b917b8547 | Fix incorrectly named import in test | inodb/revmut | tests/test_finder.py | tests/test_finder.py | from cStringIO import StringIO
import sys
import os
from nose.tools import ok_, assert_equals
import numpy as np
from os.path import join as ospj
FILE_PATH = os.path.realpath(__file__)
TEST_DIR_PATH = os.path.dirname(FILE_PATH)
DATA_PATH = os.path.abspath(ospj(TEST_DIR_PATH, "test_data"))
TMP_DIR_PATH = ospj(TEST_DIR_... | from cStringIO import StringIO
import sys
import os
from nose.tools import ok_, assert_equals
import numpy as np
from os.path import join as ospj
FILE_PATH = os.path.realpath(__file__)
TEST_DIR_PATH = os.path.dirname(FILE_PATH)
DATA_PATH = os.path.abspath(ospj(TEST_DIR_PATH, "test_data"))
TMP_DIR_PATH = ospj(TEST_DIR_... | mit | Python |
cec4cda230814149463d2067d97f07c0ef3d44a3 | Add a small test to check inheritance iterators work for nested imports | althonos/pronto | tests/test_issues.py | tests/test_issues.py | import unittest
import io
import re
import sys
import contextlib
import os
import shutil
import gzip
import os.path
import warnings
import textwrap
from unittest import mock
from . import utils
import pronto
class TestIssues(unittest.TestCase):
CONSISTENCY_SPAN = 10
@classmethod
def setUpClass(cls):
... | import unittest
import io
import re
import sys
import contextlib
import os
import shutil
import gzip
import os.path
import warnings
import textwrap
from unittest import mock
from . import utils
import pronto
class TestIssues(unittest.TestCase):
CONSISTENCY_SPAN = 10
@classmethod
def setUpClass(cls):
... | mit | Python |
38e5892e18636f9026d9dc9e7b5d46c974919adc | fix in help of init | sdg-mit/gitless,sdg-mit/gitless | gitless/cli/gl_init.py | gitless/cli/gl_init.py | # -*- coding: utf-8 -*-
# Gitless - a version control system built on top of Git.
# Licensed under GNU GPL v2.
"""gl init - Create an empty repo or make a clone."""
from __future__ import unicode_literals
import os
from gitless import core
from . import pprint
def parser(subparsers, _):
"""Adds the init parse... | # -*- coding: utf-8 -*-
# Gitless - a version control system built on top of Git.
# Licensed under GNU GPL v2.
"""gl init - Create an empty repo or make a clone."""
from __future__ import unicode_literals
import os
from gitless import core
from . import pprint
def parser(subparsers, _):
"""Adds the init parse... | mit | Python |
f79fcf89886ea63c63392b884e36ee2a11499906 | convert test_params | scrapinghub/disco,ErikDubbelboer/disco,seabirdzh/disco,mwilliams3/disco,pooya/disco,scrapinghub/disco,discoproject/disco,seabirdzh/disco,pombredanne/disco,ktkt2009/disco,pombredanne/disco,seabirdzh/disco,pombredanne/disco,mwilliams3/disco,discoproject/disco,oldmantaiter/disco,simudream/disco,ktkt2009/disco,pavlobaron/d... | tests/test_params.py | tests/test_params.py | from datetime import datetime
from disco.test import TestCase, TestJob
from disco.worker.classic.worker import Params
def fun1(a, b):
return a + b
def fun2(x):
if x > 10:
return 1
return 0
class ParamsJob(TestJob):
params = Params(x=5, f1=fun1, f2=fun2, now=datetime.now())
sort = False
... | from disco.test import DiscoJobTestFixture, DiscoTestCase
from disco.core import Params
from datetime import datetime
def fun1(a, b):
return a + b
def fun2(x):
if x > 10:
return 1
return 0
class ParamsTestCase(DiscoJobTestFixture, DiscoTestCase):
inputs = range(10)
params = Params(x=5, f... | bsd-3-clause | Python |
d16752b107749544121b6d3deca30d23d3aa4f5f | remove import statements for tests | syci/partner-contact,syci/partner-contact | partner_multi_relation/__init__.py | partner_multi_relation/__init__.py | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from . import models
| # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from . import models
from . import tests
| agpl-3.0 | Python |
fca79c17df792e99eb30a5437d88bd203684641b | Validate we round-trip UTF-8 properly | Zirpon/tchannel,chenwenbin928/tchannel,Zirpon/tchannel,RyanTech/tchannel,RyanTech/tchannel,savaki/tchannel,hustxiaoc/tchannel,bunnyblue/tchannel,hustxiaoc/tchannel,Zirpon/tchannel,benfleis/tchannel,bunnyblue/tchannel,chenwenbin928/tchannel,savaki/tchannel,bunnyblue/tchannel,vanloswang/tchannel,vanloswang/tchannel,sasa2... | tests/test_parser.py | tests/test_parser.py | # coding: utf-8
from __future__ import absolute_import
try:
from cStringIO import StringIO
except ImportError:
from io import BytesIO as StringIO
import struct
import pytest
from tchannel.parser import read_number
from tchannel.parser import read_key_value
from tchannel.parser import write_number
from tchann... | from __future__ import absolute_import
try:
from cStringIO import StringIO
except ImportError:
from io import BytesIO as StringIO
import struct
import pytest
from tchannel.parser import read_number
from tchannel.parser import read_key_value
from tchannel.parser import write_number
from tchannel.parser import... | mit | Python |
e7d0325c7e85992e0aaed333e8b7065027f6486e | Use real-world example for testing player creation | leaffan/pynhldb | tests/test_player.py | tests/test_player.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from db.player import Player
def test_constructor():
plr = Player(
8467353, "Antropov", "Nik", "C", alternate_first_names=['Nikolai'])
assert plr.player_id == 8467353
assert plr.first_name == "Nik"
assert plr.last_name == "Antropov"
assert plr... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from db.player import Player
def test_constructor():
plr = Player(99, "Gretzky", "Wayne", "C", alternate_last_names=['Bruce'])
assert plr.player_id == 99
assert plr.first_name == "Wayne"
assert plr.last_name == "Gretzky"
assert plr.name == "Wayne Gret... | mit | Python |
2ff07e8e7477a0f1c965e449c39681e4d547c271 | use memory backend for pubsub creation unit tests | kuldat/anypubsub,smarzola/anypubsub | tests/test_pubsub.py | tests/test_pubsub.py | from mock import patch
import unittest
class TestPubSub(unittest.TestCase):
def test_create_pubsub(self):
from anypubsub import create_pubsub
from anypubsub.backends.memory import MemoryPubSub
pubsub = create_pubsub('memory')
assert isinstance(pubsub, MemoryPubSub)
def test_cr... | from mock import patch
import unittest
class TestPubSub(unittest.TestCase):
def test_create_pubsub(self):
from anypubsub import create_pubsub
from anypubsub.backends.redis import RedisPubSub
pubsub = create_pubsub('redis')
assert isinstance(pubsub, RedisPubSub)
def test_create... | mit | Python |
942be12704c17ab613d1f3e7cad2480f0767b204 | fix logging for create_mapping_on_deploy | 4dn-dcic/fourfront,4dn-dcic/fourfront,hms-dbmi/fourfront,hms-dbmi/fourfront,4dn-dcic/fourfront,hms-dbmi/fourfront,hms-dbmi/fourfront,4dn-dcic/fourfront,hms-dbmi/fourfront | src/encoded/commands/create_mapping_on_deploy.py | src/encoded/commands/create_mapping_on_deploy.py | import argparse
import structlog
import loggin
from pyramid.paster import get_app
from snovault.elasticsearch.create_mapping import run as run_create_mapping
from dcicutils.beanstalk_utils import whodaman
log = structlog.getLogger(__name__)
EPILOG = __doc__
def main():
parser = argparse.ArgumentParser(
... | import argparse
import logging
from pyramid.paster import get_app
from snovault.elasticsearch.create_mapping import run as run_create_mapping
from dcicutils.beanstalk_utils import whodaman
logger = logging.getLogger(__name__)
EPILOG = __doc__
def main():
parser = argparse.ArgumentParser(
description="Cr... | mit | Python |
de10139bdb17098f3d2483d9de8b3635d9171d60 | Fix the ZSCII unicode tests by converting the correct ASCII code. | sussman/zvm,sussman/zvm | tests/zscii_tests.py | tests/zscii_tests.py | #
# Unit tests for the zscii class.
#
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
from unittest import TestCase
from zvm import zstring
from zvm import zmemory
def make_zmemory():
# We use Graham Nelson's 'curses' game for our unittests.
story... | #
# Unit tests for the zscii class.
#
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
from unittest import TestCase
from zvm import zstring
from zvm import zmemory
def make_zmemory():
# We use Graham Nelson's 'curses' game for our unittests.
story... | bsd-3-clause | Python |
e617167d529de15b8784308cdfc7ef1caeed1136 | update tests | PyCQA/pep8 | testsuite/python3.py | testsuite/python3.py | #!/usr/bin/env python3
from typing import ClassVar, List
# Annotated function (Issue #29)
def foo(x: int) -> int:
return x + 1
# Annotated variables #575
CONST: int = 42
class Class:
cls_var: ClassVar[str]
for_var: ClassVar[str]
while_var: ClassVar[str]
def_var: ClassVar[str]
if_var: Class... | #!/usr/bin/env python3
from typing import ClassVar, List
# Annotated function (Issue #29)
def foo(x: int) -> int:
return x + 1
# Annotated variables #575
CONST: int = 42
class Class:
cls_var: ClassVar[str]
for_var: ClassVar[str]
while_var: ClassVar[str]
def_var: ClassVar[str]
if_var: Class... | mit | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.