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 |
|---|---|---|---|---|---|---|---|---|---|
4b6bb7b7d258a9f130b7d10f390f44dec855cc19 | admin/src/gui/NewScoville.py | admin/src/gui/NewScoville.py | #!/usr/bin/python
#-*- coding: utf-8 -*-
###########################################################
# Copyright 2011 Daniel 'grindhold' Brendle and Team
#
# This file is part of Scoville.
#
# Scoville is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as... | #!/usr/bin/python
#-*- coding: utf-8 -*-
###########################################################
# Copyright 2011 Daniel 'grindhold' Brendle and Team
#
# This file is part of Scoville.
#
# Scoville is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as... | Revert "added constructor (testcommit for new git interface)" | Revert "added constructor (testcommit for new git interface)"
This reverts commit d5c0252b75e97103d61c3203e2a8d04a061c8a2f.
| Python | agpl-3.0 | skarphed/skarphed,skarphed/skarphed |
589598a9fc3871fe534e4dde60b61c9a0a56e224 | legistar/ext/pupa/orgs.py | legistar/ext/pupa/orgs.py | import pupa.scrape
from legistar.utils.itemgenerator import make_item
from legistar.ext.pupa.base import Adapter, Converter
class OrgsAdapter(Adapter):
'''Converts legistar data into a pupa.scrape.Person instance.
Note the make_item methods are popping values out the dict,
because the associated keys are... | import pupa.scrape
from legistar.utils.itemgenerator import make_item
from legistar.ext.pupa.base import Adapter, Converter
class OrgsAdapter(Adapter):
'''Converts legistar data into a pupa.scrape.Person instance.
Note the make_item methods are popping values out the dict,
because the associated keys are... | Remove cruft copied from Memberships adapter | Remove cruft copied from Memberships adapter
| Python | bsd-3-clause | opencivicdata/python-legistar-scraper,datamade/python-legistar-scraper |
42d06a15dd30e770dfccfccbd20fbf9bba52494d | platforms/m3/programming/goc_gdp_test.py | platforms/m3/programming/goc_gdp_test.py | #!/usr/bin/env python2
import code
try:
import Image
except ImportError:
from PIL import Image
import gdp
gdp.gdp_init()
gcl_name = gdp.GDP_NAME("edu.umich.eecs.m3.test01")
gcl_handle = gdp.GDP_GCL(gcl_name, gdp.GDP_MODE_RA)
#j = Image.open('/tmp/capture1060.jpeg')
#d = {"data": j.tostring()}
#gcl_handle.append(... | #!/usr/bin/env python2
import code
try:
import Image
except ImportError:
from PIL import Image
import gdp
gdp.gdp_init()
gcl_name = gdp.GDP_NAME("edu.umich.eecs.m3.test01")
gcl_handle = gdp.GDP_GCL(gcl_name, gdp.GDP_MODE_RA)
#j = Image.open('/tmp/capture1060.jpeg')
#d = {"data": j.tostring()}
#gcl_handle.append(... | Update gdp test to open random images | Update gdp test to open random images
| Python | apache-2.0 | lab11/M-ulator,lab11/M-ulator,lab11/M-ulator,lab11/M-ulator,lab11/M-ulator,lab11/M-ulator,lab11/M-ulator |
e29039cf5b1cd0b40b8227ef73c2d5327450c162 | app/core/servicemanager.py | app/core/servicemanager.py | """
Contains components that manage services, their sequences and interdependence (later)
"""
import threading
import logging
logger = logging.getLogger(__name__)
class ServiceManager(threading.Thread):
"""
Sequentially starts services using service.service_start(). When a new
service is activated, vie... | """
Contains components that manage services, their sequences and interdependence.
"""
import importlib
import logging
from collections import namedtuple
from app.core.toposort import toposort
logger = logging.getLogger(__name__)
Module = namedtuple('Module', ["name", "deps", "meta"])
def list_modules(module):
... | Use toposort for sequencing services. | Use toposort for sequencing services.
| Python | mit | supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer |
fc1505865f919764aa066e5e43dcde1bc7e760b2 | frappe/patches/v13_0/rename_desk_page_to_workspace.py | frappe/patches/v13_0/rename_desk_page_to_workspace.py | import frappe
from frappe.model.rename_doc import rename_doc
def execute():
if frappe.db.exists("DocType", "Desk Page"):
if frappe.db.exists('DocType', 'Workspace'):
# this patch was not added initially, so this page might still exist
frappe.delete_doc('DocType', 'Desk Page')
else:
rename_doc('DocType', ... | import frappe
from frappe.model.rename_doc import rename_doc
def execute():
if frappe.db.exists("DocType", "Desk Page"):
if frappe.db.exists('DocType', 'Workspace'):
# this patch was not added initially, so this page might still exist
frappe.delete_doc('DocType', 'Desk Page')
else:
rename_doc('DocType', ... | Rename Desk Link only if it exists | fix(Patch): Rename Desk Link only if it exists
| Python | mit | frappe/frappe,StrellaGroup/frappe,StrellaGroup/frappe,saurabh6790/frappe,StrellaGroup/frappe,mhbu50/frappe,almeidapaulopt/frappe,yashodhank/frappe,saurabh6790/frappe,mhbu50/frappe,frappe/frappe,yashodhank/frappe,almeidapaulopt/frappe,mhbu50/frappe,saurabh6790/frappe,almeidapaulopt/frappe,almeidapaulopt/frappe,yashodhan... |
828fec30b5b1deddcca79eae8fd1029bd5bd7b54 | py/desispec/io/__init__.py | py/desispec/io/__init__.py | #
# See top-level LICENSE.rst file for Copyright information
#
# -*- coding: utf-8 -*-
"""
desispec.io
===========
Tools for data and metadata I/O.
"""
# help with 2to3 support
from __future__ import absolute_import, division
from .meta import findfile, get_exposures, get_files, rawdata_root, specprod_root
from .fra... | #
# See top-level LICENSE.rst file for Copyright information
#
# -*- coding: utf-8 -*-
"""
desispec.io
===========
Tools for data and metadata I/O.
"""
# help with 2to3 support
from __future__ import absolute_import, division
from .meta import (findfile, get_exposures, get_files, rawdata_root,
specprod_root, va... | Add validate_night to public API | Add validate_night to public API
| Python | bsd-3-clause | desihub/desispec,gdhungana/desispec,timahutchinson/desispec,gdhungana/desispec,desihub/desispec,timahutchinson/desispec |
a15513ee5fc45cb974129a9097ab0a7dbb9769fc | apps/metricsmanager/api.py | apps/metricsmanager/api.py | from rest_framework.views import APIView
from rest_framework.reverse import reverse
from rest_framework.response import Response
from rest_framework import generics
from rest_framework import generics, status
from django.core.exceptions import ValidationError
from .models import *
from .serializers import *
from .formu... | from rest_framework.views import APIView
from rest_framework.reverse import reverse
from rest_framework.response import Response
from rest_framework import generics, status
from django.core.exceptions import ValidationError
from .models import *
from .serializers import *
from .formula import validate_formula
class Me... | Change formula validation error to consistent form | Change formula validation error to consistent form
| Python | agpl-3.0 | almey/policycompass-services,mmilaprat/policycompass-services,mmilaprat/policycompass-services,policycompass/policycompass-services,almey/policycompass-services,almey/policycompass-services,policycompass/policycompass-services,policycompass/policycompass-services,mmilaprat/policycompass-services |
caf4c29bada9d5b819d028469424ec195ffbc144 | tests/test_redefine_colors.py | tests/test_redefine_colors.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Test redefinition of colors."""
import colorise
import pytest
@pytest.mark.skip_on_windows
def test_redefine_colors_error():
with pytest.raises(colorise.error.NotSupportedError):
colorise.redefine_colors({})
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Test redefinition of colors."""
import colorise
import pytest
@pytest.mark.skip_on_windows
def test_redefine_colors_error():
assert not colorise.can_redefine_colors()
with pytest.raises(colorise.error.NotSupportedError):
colorise.redefine_colors({})
| Test color redefinition on nix | Test color redefinition on nix
| Python | bsd-3-clause | MisanthropicBit/colorise |
6d2f9bfbe1011c04e014016171d98fef1d12e840 | tests/test_samtools_python.py | tests/test_samtools_python.py | import pysam
def test_idxstats_parse():
bam_filename = "./pysam_data/ex2.bam"
lines = pysam.idxstats(bam_filename)
for line in lines:
_seqname, _seqlen, nmapped, _nunmapped = line.split()
def test_bedcov():
bam_filename = "./pysam_data/ex1.bam"
bed_filename = "./pysam_data/ex1.bed"
lin... | import pysam
def test_idxstats_parse_old_style_output():
bam_filename = "./pysam_data/ex2.bam"
lines = pysam.idxstats(bam_filename, old_style_output=True)
for line in lines:
_seqname, _seqlen, nmapped, _nunmapped = line.split()
def test_bedcov_old_style_output():
bam_filename = "./pysam_data/... | Add test for both new and old style output | Add test for both new and old style output
| Python | mit | pysam-developers/pysam,kyleabeauchamp/pysam,pysam-developers/pysam,TyberiusPrime/pysam,bioinformed/pysam,TyberiusPrime/pysam,bioinformed/pysam,TyberiusPrime/pysam,pysam-developers/pysam,bioinformed/pysam,kyleabeauchamp/pysam,TyberiusPrime/pysam,kyleabeauchamp/pysam,kyleabeauchamp/pysam,kyleabeauchamp/pysam,pysam-develo... |
1ff19fcd0bcbb396b7cb676c5dddf8d3c8652419 | live/components/misc.py | live/components/misc.py | from live.helpers import Timer
def timed(fun, time, next_fun=None):
"""A component that runs another component for a fixed length of time. Can optionally be given a follow-up component for chaining.
:param callable fun: The component to be run:
:param number time: The amount of time to run the component
... | from live.helpers import Timer
def timed(fun, time, next_fun=None):
"""A component that runs another component for a fixed length of time. Can optionally be given a follow-up component for chaining.
:param callable fun: The component to be run:
:param number time: The amount of time to run the component
... | Update timed_callback to support collision callbacks. | Update timed_callback to support collision callbacks.
| Python | lgpl-2.1 | GalanCM/BGELive |
28ac2b259d89c168f1e822fe087c66f2f618321a | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
scripts = ['sed_fit', 'sed_plot', 'sed_filter_output', 'sed_fitinfo2data', 'sed_fitinfo2ascii']
setup(name='sedfitter',
version='0.1.1',
description='SED Fitter in python',
author='Thomas Robitaille',
author_email='trobitaille@cfa.harvard... | #!/usr/bin/env python
from distutils.core import setup
scripts = ['sed_fit', 'sed_plot', 'sed_filter_output', 'sed_fitinfo2data', 'sed_fitinfo2ascii']
setup(name='sedfitter',
version='0.1.1',
description='SED Fitter in python',
author='Thomas Robitaille',
author_email='trobitaille@cfa.harvard... | Add sedfitter.source to list of sub-packages to install (otherwise results in ImportError) | Add sedfitter.source to list of sub-packages to install (otherwise results in ImportError) | Python | bsd-2-clause | astrofrog/sedfitter |
d2cc077bfce9bef654a8ef742996e5aca8858fc7 | setup.py | setup.py | from distutils.core import setup
setup(name='Pyranha',
description='Elegant IRC client',
version='0.1',
author='John Reese',
author_email='john@noswap.com',
url='https://github.com/jreese/pyranha',
classifiers=['License :: OSI Approved :: MIT License',
'Topic :: C... | from distutils.core import setup
setup(name='Pyranha',
description='Elegant IRC client',
version='0.1',
author='John Reese',
author_email='john@noswap.com',
url='https://github.com/jreese/pyranha',
classifiers=['License :: OSI Approved :: MIT License',
'Topic :: C... | Install default dotfiles with package | Install default dotfiles with package
| Python | mit | jreese/pyranha |
f56d8b35aa7d1d2c06d5c98ef49696e829459042 | log_request_id/tests.py | log_request_id/tests.py | import logging
from django.test import TestCase, RequestFactory
from log_request_id.middleware import RequestIDMiddleware
from testproject.views import test_view
class RequestIDLoggingTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.handler = logging.getLogger('testprojec... | import logging
from django.test import TestCase, RequestFactory
from log_request_id.middleware import RequestIDMiddleware
from testproject.views import test_view
class RequestIDLoggingTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.handler = logging.getLogger('testprojec... | Add test for externally-generated request IDs | Add test for externally-generated request IDs
| Python | bsd-2-clause | dabapps/django-log-request-id |
1002f40dc0ca118308144d3a51b696815501519f | account_direct_debit/wizard/payment_order_create.py | account_direct_debit/wizard/payment_order_create.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2013 Therp BV (<http://therp.nl>).
#
# All other contributions are (C) by their respective contributors
#
# All Rights Reserved
#
# This program is free software: you can redistribute it ... | # -*- coding: utf-8 -*-
# © 2013 Therp BV (<http://therp.nl>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import models, api
class PaymentOrderCreate(models.TransientModel):
_inherit = 'payment.order.create'
@api.multi
def extend_payment_order_domain(self, payment_o... | Fix move lines domain for direct debits | [FIX] account_direct_debit: Fix move lines domain for direct debits
| Python | agpl-3.0 | acsone/bank-payment,diagramsoftware/bank-payment,CompassionCH/bank-payment,CompassionCH/bank-payment,open-synergy/bank-payment,hbrunn/bank-payment |
989ff44354d624906d72f20aac933a9243214cf8 | corehq/dbaccessors/couchapps/cases_by_server_date/by_owner_server_modified_on.py | corehq/dbaccessors/couchapps/cases_by_server_date/by_owner_server_modified_on.py | from __future__ import absolute_import
from __future__ import unicode_literals
from casexml.apps.case.models import CommCareCase
from dimagi.utils.parsing import json_format_datetime
def get_case_ids_modified_with_owner_since(domain, owner_id, reference_date):
"""
Gets all cases with a specified owner ID that... | from __future__ import absolute_import
from __future__ import unicode_literals
from casexml.apps.case.models import CommCareCase
from dimagi.utils.parsing import json_format_datetime
def get_case_ids_modified_with_owner_since(domain, owner_id, reference_date, until_date=None):
"""
Gets all cases with a specif... | Make get_case_ids_modified_with_owner_since accept an end date as well | Make get_case_ids_modified_with_owner_since accept an end date as well
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
16d65c211b00871ac7384baa3934d88410e2c977 | tests/test_planetary_test_data_2.py | tests/test_planetary_test_data_2.py | # -*- coding: utf-8 -*-
from planetary_test_data import PlanetaryTestDataProducts
import os
def test_planetary_test_data_object():
"""Tests simple PlanetaryTestDataProducts attributes."""
data = PlanetaryTestDataProducts()
assert data.tags == ['core']
assert data.all_products is None
# handle run... | # -*- coding: utf-8 -*-
from planetary_test_data import PlanetaryTestDataProducts
import os
def test_planetary_test_data_object():
"""Tests simple PlanetaryTestDataProducts attributes."""
data = PlanetaryTestDataProducts()
assert data.tags == ['core']
assert data.all_products is None
# handle run... | Update test to account for more core products | Update test to account for more core products
| Python | bsd-3-clause | pbvarga1/planetary_test_data,planetarypy/planetary_test_data |
1ee414611fa6e01516d545bb284695a62bd69f0a | rtrss/daemon.py | rtrss/daemon.py | import sys
import os
import logging
import atexit
from rtrss.basedaemon import BaseDaemon
_logger = logging.getLogger(__name__)
class WorkerDaemon(BaseDaemon):
def run(self):
_logger.info('Daemon started ith pid %d', os.getpid())
from rtrss.worker import app_init, worker_action
w... | import os
import logging
from rtrss.basedaemon import BaseDaemon
_logger = logging.getLogger(__name__)
class WorkerDaemon(BaseDaemon):
def run(self):
_logger.info('Daemon started ith pid %d', os.getpid())
from rtrss.worker import worker_action
worker_action('run')
_logger.info... | Change debug action to production | Change debug action to production
| Python | apache-2.0 | notapresent/rtrss,notapresent/rtrss,notapresent/rtrss,notapresent/rtrss |
7ab9f281bf891e00d97278e3dba73eaeffe3799a | kaggle/titanic/categorical_and_scaler_prediction.py | kaggle/titanic/categorical_and_scaler_prediction.py | import pandas
def main():
train_all = pandas.DataFrame.from_csv('train.csv')
train = train_all[['Survived', 'Sex', 'Fare']]
print(train)
if __name__ == '__main__':
main()
| import pandas
from sklearn.naive_bayes import MultinomialNB
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import LabelEncoder
def main():
train_all = pandas.DataFrame.from_csv('train.csv')
train = train_all[['Survived', 'Sex', 'Fare']][:20]
gender_label = LabelEncoder()... | Make predictions with gender and ticket price | Make predictions with gender and ticket price
| Python | mit | noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit |
9a4d608471b31550038d8ce43f6515bbb330e68a | tests.py | tests.py | import tcpstat | #!/usr/bin/python
# -*- coding: utf-8 -*-
# The MIT License (MIT)
# Copyright (c) 2014 Ivan Cai
# 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 limit... | Fix build failed on scrutinizer-ci | Fix build failed on scrutinizer-ci
| Python | mit | caizixian/tcpstat,caizixian/tcpstat |
72125d84bf91201e15a93acb60fbc8f59af9aae8 | plugins/PerObjectSettingsTool/PerObjectSettingsTool.py | plugins/PerObjectSettingsTool/PerObjectSettingsTool.py | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Tool import Tool
from UM.Scene.Selection import Selection
from UM.Application import Application
from . import PerObjectSettingsModel
class PerObjectSettingsTool(Tool):
def __init__(self):
super()._... | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Tool import Tool
from UM.Scene.Selection import Selection
from UM.Application import Application
from UM.Qt.ListModel import ListModel
from . import PerObjectSettingsModel
class PerObjectSettingsTool(Tool):
... | Fix problem with casting to QVariant | Fix problem with casting to QVariant
This is a magical fix that Nallath and I found for a problem that shouldn't exist in the first place and sometimes doesn't exist at all and in the same time is a superposition of existing and not existing and it's all very complicated and an extremely weird hack. Casting this objec... | Python | agpl-3.0 | hmflash/Cura,senttech/Cura,senttech/Cura,ynotstartups/Wanhao,ynotstartups/Wanhao,fieldOfView/Cura,fieldOfView/Cura,totalretribution/Cura,totalretribution/Cura,Curahelper/Cura,Curahelper/Cura,hmflash/Cura |
acdf380a5463ae8bd9c6dc76ce02069371b6f5fd | backend/restapp/restapp/urls.py | backend/restapp/restapp/urls.py | """restapp URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | """restapp URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | Add simple serializers for books and authors | Add simple serializers for books and authors
| Python | mit | TomaszGabrysiak/django-rest-angular-seed,TomaszGabrysiak/django-rest-angular-seed,TomaszGabrysiak/django-rest-angular-seed |
90265098d21fa900a4a2d86719efc95c352812f4 | mopidy_somafm/__init__.py | mopidy_somafm/__init__.py | from __future__ import unicode_literals
import os
from mopidy import config, ext
__version__ = '0.3.0'
class Extension(ext.Extension):
dist_name = 'Mopidy-SomaFM'
ext_name = 'somafm'
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file__), 'e... | from __future__ import unicode_literals
import os
from mopidy import config, ext
__version__ = '0.3.0'
class Extension(ext.Extension):
dist_name = 'Mopidy-SomaFM'
ext_name = 'somafm'
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file__), 'e... | Use new extension setup() API | Use new extension setup() API
| Python | mit | AlexandrePTJ/mopidy-somafm |
a7908d39e24384881c30042e1b4c7e93e85eb38e | test/TestTaskIncludes.py | test/TestTaskIncludes.py | import os
import unittest
from ansiblelint import Runner, RulesCollection
class TestTaskIncludes(unittest.TestCase):
def setUp(self):
rulesdir = os.path.join('lib', 'ansiblelint', 'rules')
self.rules = RulesCollection.create_from_directory(rulesdir)
def test_block_included_tasks(self):
... | import os
import unittest
from ansiblelint import Runner, RulesCollection
class TestTaskIncludes(unittest.TestCase):
def setUp(self):
rulesdir = os.path.join('lib', 'ansiblelint', 'rules')
self.rules = RulesCollection.create_from_directory(rulesdir)
def test_block_included_tasks(self):
... | Add test that exercises block includes | Add test that exercises block includes
| Python | mit | MatrixCrawler/ansible-lint,dataxu/ansible-lint,willthames/ansible-lint |
0ba063edc4aec690efca5c5ba9faf64042bb7707 | demo/demo/urls.py | demo/demo/urls.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import patterns, url
from .views import HomePageView, FormHorizontalView, FormInlineView, PaginationView, FormWithFilesView, \
DefaultFormView, MiscView, DefaultFormsetView, DefaultFormByFieldView
urlpatterns = [
url(r'^$',... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from .views import HomePageView, FormHorizontalView, FormInlineView, PaginationView, FormWithFilesView, \
DefaultFormView, MiscView, DefaultFormsetView, DefaultFormByFieldView
urlpatterns = [
url(r'^$', HomePageV... | Remove obsolete import (removed in Django 1.10) | Remove obsolete import (removed in Django 1.10)
| Python | bsd-3-clause | dyve/django-bootstrap3,dyve/django-bootstrap3,zostera/django-bootstrap4,zostera/django-bootstrap4 |
5e9fda28089a11863dcc4610f5953dbe942165db | numpy/_array_api/_constants.py | numpy/_array_api/_constants.py | from ._array_object import ndarray
from ._dtypes import float64
import numpy as np
e = ndarray._new(np.array(np.e, dtype=float64))
inf = ndarray._new(np.array(np.inf, dtype=float64))
nan = ndarray._new(np.array(np.nan, dtype=float64))
pi = ndarray._new(np.array(np.pi, dtype=float64))
| import numpy as np
e = np.e
inf = np.inf
nan = np.nan
pi = np.pi
| Make the array API constants Python floats | Make the array API constants Python floats
| Python | mit | cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy |
faa67c81ad2ebb8ba8cb407982cbced72d1fa899 | tests/test_config_tree.py | tests/test_config_tree.py | import pytest
from pyhocon.config_tree import ConfigTree
from pyhocon.exceptions import ConfigMissingException, ConfigWrongTypeException
class TestConfigParser(object):
def test_config_tree_quoted_string(self):
config_tree = ConfigTree()
config_tree.put("a.b.c", "value")
assert config_tre... | import pytest
from pyhocon.config_tree import ConfigTree
from pyhocon.exceptions import ConfigMissingException, ConfigWrongTypeException
class TestConfigParser(object):
def test_config_tree_quoted_string(self):
config_tree = ConfigTree()
config_tree.put("a.b.c", "value")
assert config_tre... | Add failing tests for iteration and logging config | Add failing tests for iteration and logging config
| Python | apache-2.0 | acx2015/pyhocon,chimpler/pyhocon,vamega/pyhocon,peoplepattern/pyhocon |
07dcdb9de47ac88a2e0f3ecec257397a0272f112 | extended_choices/__init__.py | extended_choices/__init__.py | """Little helper application to improve django choices (for fields)"""
from __future__ import unicode_literals
from .choices import Choices
__author__ = 'Stephane "Twidi" Ange;'
__contact__ = "s.angel@twidi.com"
__homepage__ = "https://pypi.python.org/pypi/django-extended-choices"
__version__ = "1.1"
| """Little helper application to improve django choices (for fields)"""
from __future__ import unicode_literals
from .choices import Choices, OrderedChoices
__author__ = 'Stephane "Twidi" Ange;'
__contact__ = "s.angel@twidi.com"
__homepage__ = "https://pypi.python.org/pypi/django-extended-choices"
__version__ = "1.1"... | Make OrderedChoices available at the package root | Make OrderedChoices available at the package root
| Python | bsd-3-clause | twidi/django-extended-choices |
d07a7ad25f69a18c57c50d6c32df212e1f987bd4 | www/tests/test_collections.py | www/tests/test_collections.py | import collections
_d=collections.defaultdict(int)
_d['a']+=1
_d['a']+=2
_d['b']+=4
assert _d['a'] == 3
assert _d['b'] == 4
s = 'mississippi'
for k in s:
_d[k] += 1
_values=list(_d.values())
_values.sort()
assert _values == [1, 2, 3, 4, 4, 4]
_keys=list(_d.keys())
_keys.sort()
assert _keys == ['a', 'b', 'i', ... | import collections
_d=collections.defaultdict(int)
_d['a']+=1
_d['a']+=2
_d['b']+=4
assert _d['a'] == 3
assert _d['b'] == 4
s = 'mississippi'
for k in s:
_d[k] += 1
_values=list(_d.values())
_values.sort()
assert _values == [1, 2, 3, 4, 4, 4]
_keys=list(_d.keys())
_keys.sort()
assert _keys == ['a', 'b', 'i', ... | Add a test on namedtuple | Add a test on namedtuple
| Python | bsd-3-clause | kikocorreoso/brython,Mozhuowen/brython,Hasimir/brython,Isendir/brython,Isendir/brython,amrdraz/brython,jonathanverner/brython,kevinmel2000/brython,brython-dev/brython,Mozhuowen/brython,jonathanverner/brython,Hasimir/brython,rubyinhell/brython,Hasimir/brython,molebot/brython,Isendir/brython,JohnDenker/brython,olemis/bry... |
888584a49e697551c4f680cc8651be2fe80fc65d | configgen/generators/ppsspp/ppssppGenerator.py | configgen/generators/ppsspp/ppssppGenerator.py | #!/usr/bin/env python
import Command
#~ import reicastControllers
import recalboxFiles
from generators.Generator import Generator
import ppssppControllers
import shutil
import os.path
import ConfigParser
class PPSSPPGenerator(Generator):
# Main entry of the module
# Configure fba and return a command
def ... | #!/usr/bin/env python
import Command
#~ import reicastControllers
import recalboxFiles
from generators.Generator import Generator
import ppssppControllers
import shutil
import os.path
import ConfigParser
class PPSSPPGenerator(Generator):
# Main entry of the module
# Configure fba and return a command
def ... | Remove a bad typo from reicast | Remove a bad typo from reicast
| Python | mit | nadenislamarre/recalbox-configgen,recalbox/recalbox-configgen,digitalLumberjack/recalbox-configgen |
cbdfc1b1cb4162256538576cabe2b6832aa83bca | django_mysqlpool/__init__.py | django_mysqlpool/__init__.py | from functools import wraps
from django.db import connection
def auto_close_db(f):
"Ensures the database connection is closed when the function returns."
@wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
finally:
connection.close()
return wr... | from functools import wraps
def auto_close_db(f):
"Ensures the database connection is closed when the function returns."
from django.db import connection
@wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
finally:
connection.close()
retur... | Fix circular import when used with other add-ons that import django.db | Fix circular import when used with other add-ons that import django.db
eg sorl_thumbnail:
Traceback (most recent call last):
File "/home/rpatterson/src/work/retrans/src/ReTransDjango/bin/manage", line 40, in <module>
sys.exit(manage.main())
File "/home/rpatterson/src/work/retrans/src/ReTransDjango/retrans/mana... | Python | mit | smartfile/django-mysqlpool |
0f7816676eceb42f13786408f1d1a09527919a1e | Modules/Biophotonics/python/iMC/msi/io/spectrometerreader.py | Modules/Biophotonics/python/iMC/msi/io/spectrometerreader.py | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 7 12:04:18 2015
@author: wirkert
"""
import numpy as np
from msi.io.reader import Reader
from msi.msi import Msi
class SpectrometerReader(Reader):
def __init__(self):
pass
def read(self, file_to_read):
# our spectrometer like to follow german... | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 7 12:04:18 2015
@author: wirkert
"""
import numpy as np
from msi.io.reader import Reader
from msi.msi import Msi
class SpectrometerReader(Reader):
def __init__(self):
pass
def read(self, file_to_read):
# our spectrometer like to follow german... | Change SpectrometerReader a little so it can handle more data formats. | Change SpectrometerReader a little so it can handle more data formats.
| Python | bsd-3-clause | MITK/MITK,iwegner/MITK,RabadanLab/MITKats,RabadanLab/MITKats,iwegner/MITK,fmilano/mitk,fmilano/mitk,RabadanLab/MITKats,RabadanLab/MITKats,fmilano/mitk,fmilano/mitk,MITK/MITK,RabadanLab/MITKats,RabadanLab/MITKats,fmilano/mitk,fmilano/mitk,iwegner/MITK,fmilano/mitk,MITK/MITK,iwegner/MITK,iwegner/MITK,MITK/MITK,MITK/MITK,... |
33a3ebacabda376826f0470129e8583e4974fd9d | examples/markdown/build.py | examples/markdown/build.py | # build.py
#!/usr/bin/env python3
import os
import jinja2
# Markdown to HTML library
# https://pypi.org/project/Markdown/
import markdown
from staticjinja import Site
markdowner = markdown.Markdown(output_format="html5")
def md_context(template):
with open(template.filename) as f:
markdown_content = f.re... | # build.py
#!/usr/bin/env python3
import os
# Markdown to HTML library
# https://pypi.org/project/Markdown/
import markdown
from staticjinja import Site
markdowner = markdown.Markdown(output_format="html5")
def md_context(template):
with open(template.filename) as f:
markdown_content = f.read()
r... | Remove unneeded jinja2 import in markdown example | Remove unneeded jinja2 import in markdown example
| Python | mit | Ceasar/staticjinja,Ceasar/staticjinja |
c9735ce9ea330737cf47474ef420303c56a32873 | apps/demos/admin.py | apps/demos/admin.py | from django.contrib import admin
from .models import Submission
class SubmissionAdmin(admin.ModelAdmin):
list_display = ( 'title', 'creator', 'featured', 'hidden', 'tags', 'modified', )
admin.site.register(Submission, SubmissionAdmin)
| from django.contrib import admin
from .models import Submission
class SubmissionAdmin(admin.ModelAdmin):
list_display = ( 'title', 'creator', 'featured', 'hidden', 'tags', 'modified', )
list_editable = ( 'featured', 'hidden' )
admin.site.register(Submission, SubmissionAdmin)
| Make featured and hidden flags editable from demo listing | Make featured and hidden flags editable from demo listing
| Python | mpl-2.0 | bluemini/kuma,openjck/kuma,hoosteeno/kuma,Elchi3/kuma,davehunt/kuma,anaran/kuma,robhudson/kuma,davidyezsetz/kuma,darkwing/kuma,anaran/kuma,chirilo/kuma,jezdez/kuma,yfdyh000/kuma,nhenezi/kuma,Elchi3/kuma,ronakkhunt/kuma,a2sheppy/kuma,groovecoder/kuma,SphinxKnight/kuma,escattone/kuma,jezdez/kuma,tximikel/kuma,a2sheppy/ku... |
8d471b5b7a8f57214afe79783f09afa97c5d2bfc | entropy/__init__.py | entropy/__init__.py | import entropy._entropy as _entropy
def entropy(data):
"""Compute the Shannon entropy of the given string.
Returns a floating point value indicating how many bits of entropy
there are per octet in the string."""
return _entropy.shannon_entropy(data)
if __name__ == '__main__':
print entropy('\n'.join(file(__file... | import entropy._entropy as _entropy
def entropy(data):
"""Compute the Shannon entropy of the given string.
Returns a floating point value indicating how many bits of entropy
there are per octet in the string."""
return _entropy.shannon_entropy(data)
def absolute_entropy(data):
"""Compute the "absolute" entropy ... | Add absolute and relative entropy functions. | Add absolute and relative entropy functions.
| Python | bsd-3-clause | chachalaca/py-entropy,billthebrute/py-entropy,chachalaca/py-entropy,billthebrute/py-entropy |
b43e06dd5a80814e15ce20f50d683f0daaa19a93 | addons/hr/models/hr_employee_base.py | addons/hr/models/hr_employee_base.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class HrEmployeeBase(models.AbstractModel):
_name = "hr.employee.base"
_description = "Basic Employee"
_order = 'name'
name = fields.Char()
active = fields.Boolean("... | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class HrEmployeeBase(models.AbstractModel):
_name = "hr.employee.base"
_description = "Basic Employee"
_order = 'name'
name = fields.Char()
active = fields.Boolean("... | Add the color field to public employee | [FIX] hr: Add the color field to public employee
The color field is necessary to be able to display some fields
(many2many_tags) and used in the kanban views
closes odoo/odoo#35216
Signed-off-by: Yannick Tivisse (yti) <yti@odoo.com>
closes odoo/odoo#35462
Signed-off-by: Romain Libert (rli) <d3a53ea3f0d6ebbbf1eb843... | Python | agpl-3.0 | ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo |
96e3d70a7bd824b8265e8e67adc3996c4522dd57 | historia.py | historia.py | from eve import Eve
app = Eve()
if __name__ == '__main__':
app.run()
| from eve import Eve
app = Eve()
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
| Use port 80 to serve the API | Use port 80 to serve the API
| Python | mit | waoliveros/historia |
be41ae0d987cd1408cb2db649a2eccd73bc272f3 | apps/innovate/views.py | apps/innovate/views.py | import random
import jingo
from users.models import Profile
from projects.models import Project
from events.models import Event
from feeds.models import Entry
def splash(request):
"""Display splash page. With featured project, event, person, blog post."""
def get_random(cls, **kwargs):
choices = cls... | import random
import jingo
from users.models import Profile
from projects.models import Project
from events.models import Event
from feeds.models import Entry
def splash(request):
"""Display splash page. With featured project, event, person, blog post."""
def get_random(cls, **kwargs):
choices = cls... | Add status codes to the 404/500 error handlers. | Add status codes to the 404/500 error handlers.
| Python | bsd-3-clause | mozilla/betafarm,mozilla/betafarm,mozilla/betafarm,mozilla/betafarm |
81a03d81ece17487f7b7296f524339a052d45a0d | src/gcf.py | src/gcf.py | def gcf(a, b):
while b:
a, b = b, a % b
return a
def xgcf(a, b):
s1, s2 = 1, 0
t1, t2 = 0, 1
while b:
q, r = divmod(a, b)
a, b = b, r
s2, s1 = s1 - q * s2, s2
t2, t1 = t1 - q * t2, t2
return a, s1, t1
| def gcf(a, b):
while b:
a, b = b, a % b
return a
def xgcf(a, b):
s1, s2 = 1, 0
t1, t2 = 0, 1
while b:
q, r = divmod(a, b)
a, b = b, r
s2, s1 = s1 - q * s2, s2
t2, t1 = t1 - q * t2, t2
# Bézout's identity says: s1 * a + t1 * b == gcd(a, b)
return a... | Add Bézout's identity into comments | Add Bézout's identity into comments
| Python | mit | all3fox/algos-py |
85809e34f1d8ad3d8736e141f3cb2e6045260938 | neuroimaging/externals/pynifti/nifti/__init__.py | neuroimaging/externals/pynifti/nifti/__init__.py |
from niftiimage import NiftiImage
| """
Nifti
=====
Python bindings for the nifticlibs. Access through the NiftiImage class.
See help for pyniftiio.nifti.NiftiImage
"""
from niftiimage import NiftiImage
| Add doc for pynifti package. | DOC: Add doc for pynifti package. | Python | bsd-3-clause | alexis-roche/nipy,alexis-roche/register,nipy/nireg,alexis-roche/register,nipy/nipy-labs,nipy/nipy-labs,alexis-roche/nipy,alexis-roche/niseg,arokem/nipy,arokem/nipy,alexis-roche/nipy,nipy/nireg,bthirion/nipy,alexis-roche/nireg,alexis-roche/niseg,bthirion/nipy,bthirion/nipy,bthirion/nipy,alexis-roche/nireg,arokem/nipy,al... |
04df5c189d6d1760c692d1985faf558058e56eb2 | flask_pagedown/__init__.py | flask_pagedown/__init__.py | from jinja2 import Markup
from flask import current_app, request
class _pagedown(object):
def include_pagedown(self):
if request.is_secure:
protocol = 'https'
else:
protocol = 'http'
return Markup('''
<script type="text/javascript" src="{0}://cdnjs.cloudflare.com/aja... | from jinja2 import Markup
from flask import current_app, request
class _pagedown(object):
def include_pagedown(self):
return Markup('''
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/pagedown/1.0/Markdown.Converter.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudfla... | Fix support for SSL for proxied sites, or otherwise uncertain situations | Fix support for SSL for proxied sites, or otherwise uncertain situations
My particular situation is deployed through ElasticBeanstalk, proxying
HTTPS to HTTP on the actual endpoints. This makes flask think that it is
only running with http, not https
| Python | mit | miguelgrinberg/Flask-PageDown,miguelgrinberg/Flask-PageDown |
365411abd73275a529dc5ca7ec403b994c513aae | registries/serializers.py | registries/serializers.py | from rest_framework import serializers
from registries.models import Organization
from gwells.models import ProvinceState
class DrillerListSerializer(serializers.ModelSerializer):
province_state = serializers.ReadOnlyField()
class Meta:
model = Organization
# Using all fields for now
... | from rest_framework import serializers
from registries.models import Organization
from gwells.models import ProvinceState
class DrillerListSerializer(serializers.ModelSerializer):
"""
Serializer for Driller model "list" view.
"""
province_state = serializers.ReadOnlyField(source="province_state.code"... | Add fields to driller list serializer | Add fields to driller list serializer
| Python | apache-2.0 | bcgov/gwells,rstens/gwells,bcgov/gwells,bcgov/gwells,rstens/gwells,rstens/gwells,rstens/gwells,bcgov/gwells |
fc9fdd2115b46c71c36ba7d86f14395ac4cf1e3e | genome_designer/scripts/generate_coverage_data.py | genome_designer/scripts/generate_coverage_data.py | """Script to generate coverage data.
"""
import os
import subprocess
from django.conf import settings
from main.models import get_dataset_with_type
from main.models import AlignmentGroup
from main.models import Dataset
from utils import generate_safe_filename_prefix_from_label
def analyze_coverage(sample_alignment... | """Script to generate coverage data.
"""
import os
import subprocess
from django.conf import settings
from main.models import get_dataset_with_type
from main.models import AlignmentGroup
from main.models import Dataset
from utils import generate_safe_filename_prefix_from_label
def analyze_coverage(sample_alignment... | Update coverage script to only output the first 4 cols which shows coverage. | Update coverage script to only output the first 4 cols which shows
coverage.
| Python | mit | woodymit/millstone,woodymit/millstone_accidental_source,woodymit/millstone_accidental_source,woodymit/millstone,woodymit/millstone_accidental_source,woodymit/millstone_accidental_source,woodymit/millstone,churchlab/millstone,woodymit/millstone,churchlab/millstone,churchlab/millstone,churchlab/millstone |
e7bda027780da26183f84f7af5c50cd37649c76b | functional_tests/remote.py | functional_tests/remote.py | # -*- coding: utf-8 -*-
from unipath import Path
import subprocess
THIS_FOLDER = Path(__file__).parent
def reset_database(host):
subprocess.check_call(['fab', 'reset_database', '--host={}'.format(host)],
cwd=THIS_FOLDER)
def create_user(host, user, email, password):
subprocess.check_call(['fab', 'cr... | # -*- coding: utf-8 -*-
from unipath import Path
import subprocess
THIS_FOLDER = Path(__file__).parent
def reset_database(host):
subprocess.check_call(['fab', 'reset_database', '--host={}'.format(host),
'--hide=everything,status'],
cwd=THIS_FOLDER)
def create_user(host, user, email, password):
... | Make running FTs against staging a bit less verbose | Make running FTs against staging a bit less verbose
| Python | mit | XeryusTC/projman,XeryusTC/projman,XeryusTC/projman |
4daefdb0a4def961572fc22d0fe01a394b11fad9 | tests/test_httpclient.py | tests/test_httpclient.py | try:
import unittest2 as unittest
except ImportError:
import unittest
import sys
sys.path.append('..')
from pyrabbit import http
class TestHTTPClient(unittest.TestCase):
"""
Except for the init test, these are largely functional tests that
require a RabbitMQ management API to be available on loc... | try:
import unittest2 as unittest
except ImportError:
import unittest
import sys
sys.path.append('..')
from pyrabbit import http
class TestHTTPClient(unittest.TestCase):
"""
Except for the init test, these are largely functional tests that
require a RabbitMQ management API to be available on loc... | Test creation of HTTP credentials | tests.http: Test creation of HTTP credentials
| Python | bsd-3-clause | ranjithlav/pyrabbit,bkjones/pyrabbit,NeCTAR-RC/pyrabbit,chaos95/pyrabbit,switchtower/pyrabbit |
dbbd29a1cdfcd3f11a968c0aeb38bd54ef7014e3 | gfusion/tests/test_main.py | gfusion/tests/test_main.py | """Tests for main.py"""
from ..main import _solve_weight_vector
import numpy as np
from nose.tools import assert_raises, assert_equal, assert_true
def test_solve_weight_vector():
# smoke test
n_nodes = 4
n_communities = 2
n_similarities = 3
delta = 0.3
similarities = np.random.random((n_simila... | """Tests for main.py"""
from ..main import _solve_weight_vector
import numpy as np
from numpy.testing import assert_array_almost_equal
from nose.tools import assert_raises, assert_equal, assert_true
def test_solve_weight_vector():
# smoke test
n_nodes = 4
n_communities = 2
n_similarities = 3
delta... | Add a more semantic test | Add a more semantic test
| Python | mit | mvdoc/gfusion |
eebae9eb9b941a4e595775434a05df29d55a34f2 | tools/conan/conanfile.py | tools/conan/conanfile.py | from conans import ConanFile, CMake, tools
class VarconfConan(ConanFile):
name = "varconf"
version = "1.0.3"
license = "GPL-2.0+"
author = "Erik Ogenvik <erik@ogenvik.org>"
homepage = "https://www.worldforge.org"
url = "https://github.com/worldforge/varconf"
description = "Configuration li... | from conans import ConanFile, CMake, tools
class VarconfConan(ConanFile):
name = "varconf"
version = "1.0.3"
license = "GPL-2.0+"
author = "Erik Ogenvik <erik@ogenvik.org>"
homepage = "https://www.worldforge.org"
url = "https://github.com/worldforge/varconf"
description = "Configuration li... | Build with PIC by default. | Build with PIC by default.
| Python | lgpl-2.1 | worldforge/varconf,worldforge/varconf,worldforge/varconf,worldforge/varconf |
5b2e74cdc50a6c3814879f470d8992267fa06a62 | heufybot/utils/__init__.py | heufybot/utils/__init__.py | # Taken from txircd:
# https://github.com/ElementalAlchemist/txircd/blob/8832098149b7c5f9b0708efe5c836c8160b0c7e6/txircd/utils.py#L9
def _enum(**enums):
return type('Enum', (), enums)
ModeType = _enum(LIST=0, PARAM_SET=1, PARAM_UNSET=2, NO_PARAM=3)
ModuleLoadType = _enum(LOAD=0, UNLOAD=1, ENABLE=2, DISABLE=3)
def... | # Taken from txircd:
# https://github.com/ElementalAlchemist/txircd/blob/8832098149b7c5f9b0708efe5c836c8160b0c7e6/txircd/utils.py#L9
def _enum(**enums):
return type('Enum', (), enums)
ModeType = _enum(LIST=0, PARAM_SET=1, PARAM_UNSET=2, NO_PARAM=3)
ModuleLoadType = _enum(LOAD=0, UNLOAD=1, ENABLE=2, DISABLE=3)
def... | Fix the handling of missing prefixes | Fix the handling of missing prefixes
Twisted defaults to an empty string, while IRCBase defaults to None.
| Python | mit | Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot |
55b7b07986590c4ab519fcda3c973c87ad23596b | flask_admin/model/typefmt.py | flask_admin/model/typefmt.py | from jinja2 import Markup
def null_formatter(value):
"""
Return `NULL` as the string for `None` value
:param value:
Value to check
"""
return Markup('<i>NULL</i>')
def empty_formatter(value):
"""
Return empty string for `None` value
:param value:
... | from jinja2 import Markup
def null_formatter(value):
"""
Return `NULL` as the string for `None` value
:param value:
Value to check
"""
return Markup('<i>NULL</i>')
def empty_formatter(value):
"""
Return empty string for `None` value
:param value:
... | Add extra type formatter for `list` type | Add extra type formatter for `list` type
| Python | bsd-3-clause | mrjoes/flask-admin,janusnic/flask-admin,Kha/flask-admin,wuxiangfeng/flask-admin,litnimax/flask-admin,HermasT/flask-admin,quokkaproject/flask-admin,Kha/flask-admin,flabe81/flask-admin,porduna/flask-admin,Junnplus/flask-admin,ibushong/test-repo,janusnic/flask-admin,jschneier/flask-admin,closeio/flask-admin,chase-seibert/... |
e9eb8e0c4e77525d31c904e7f401a0d388a3fbf6 | app/utils.py | app/utils.py | from flask import url_for
def register_template_utils(app):
"""Register Jinja 2 helpers (called from __init__.py)."""
@app.template_test()
def equalto(value, other):
return value == other
@app.template_global()
def is_hidden_field(field):
from wtforms.fields import HiddenField
... | from flask import url_for
def register_template_utils(app):
"""Register Jinja 2 helpers (called from __init__.py)."""
@app.template_test()
def equalto(value, other):
return value == other
@app.template_global()
def is_hidden_field(field):
from wtforms.fields import HiddenField
... | Fix index_for_role function to use index field in Role class. | Fix index_for_role function to use index field in Role class.
| Python | mit | hack4impact/women-veterans-rock,hack4impact/women-veterans-rock,hack4impact/women-veterans-rock |
ad757857b7878904c6d842e115074c4fac24bed7 | tweetar.py | tweetar.py | import twitter
import urllib2
NOAA_URL = "http://weather.noaa.gov/pub/data/observations/metar/stations/*station_id*.TXT"
def retrieve_and_post(conf):
post = False
pull_url = NOAA_URL.replace('*station_id*', conf['station'])
request = urllib2.Request(pull_url, None)
response = urllib2.urlopen(request)... | import twitter
import urllib2
NOAA_URL = "http://weather.noaa.gov/pub/data/observations/metar/stations/*station_id*.TXT"
def retrieve_and_post(conf):
post = False
pull_url = NOAA_URL.replace('*station_id*', conf['station'])
request = urllib2.Request(pull_url, None)
response = urllib2.urlopen(request)... | Use .get instead of getattr, dummy. | Use .get instead of getattr, dummy.
| Python | bsd-3-clause | adamfast/python-tweetar |
0461fad1a3d81aa2d937a1734f1ebb07b3e81d79 | undercloud_heat_plugins/server_update_allowed.py | undercloud_heat_plugins/server_update_allowed.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
# ... | #
# 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
# ... | Fix no-replace-server to accurately preview update | Fix no-replace-server to accurately preview update
This override of OS::Nova::Server needs to reflect the fact
that it never replaces on update or the update --dry-run output
ends up being wrong.
Closes-Bug: 1561076
Change-Id: I9256872b877fbe7f91befb52995c62de006210ef
| Python | apache-2.0 | openstack/tripleo-common,openstack/tripleo-common |
84a2aa1187cf7a9ec7593920d9ad0708b7d28f55 | sqlobject/tests/test_pickle.py | sqlobject/tests/test_pickle.py | import pickle
from sqlobject import *
from sqlobject.tests.dbtest import *
########################################
## Pickle instances
########################################
class TestPickle(SQLObject):
question = StringCol()
answer = IntCol()
test_question = 'The Ulimate Question of Life, the Universe an... | import pickle
from sqlobject import *
from sqlobject.tests.dbtest import *
########################################
## Pickle instances
########################################
class TestPickle(SQLObject):
question = StringCol()
answer = IntCol()
test_question = 'The Ulimate Question of Life, the Universe an... | Fix flake8 E113 unexpected indentation | Fix flake8 E113 unexpected indentation
| Python | lgpl-2.1 | drnlm/sqlobject,sqlobject/sqlobject,sqlobject/sqlobject,drnlm/sqlobject |
8c0f87858b1dc58d23006cd581cfa74d23096a44 | trex/serializers.py | trex/serializers.py | # -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from rest_framework.serializers import HyperlinkedModelSerializer
from trex.models.project import Project
class ProjectSerializer(HyperlinkedModelSerializer):
class Meta:
... | # -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from rest_framework.serializers import HyperlinkedModelSerializer
from trex.models.project import Project, Entry
class ProjectSerializer(HyperlinkedModelSerializer):
class... | Add a ProjectDetailSerializer and EntryDetailSerializer | Add a ProjectDetailSerializer and EntryDetailSerializer
| Python | mit | bjoernricks/trex,bjoernricks/trex |
2e9a6a2babb16f4ed9c3367b21ee28514d1988a8 | srm/__main__.py | srm/__main__.py | """
The default module run when imported from the command line and also the main entry point defined in
setup.py. Ex:
python3 -m srm
"""
import click
from . import __version__, status
@click.group()
@click.version_option(__version__)
def cli() -> None:
"""Main command-line entry method."""
cli.add_comma... | """
The default module run when imported from the command line and also the main entry point defined in
setup.py. Ex:
python3 -m srm
"""
import click
from . import __version__, status
@click.group()
@click.version_option(__version__)
def cli() -> None:
"""Main command-line entry method."""
cli.add_comma... | Set correct program name in 'help' output | Set correct program name in 'help' output
| Python | mit | cmcginty/simple-rom-manager,cmcginty/simple-rom-manager |
e54d753a3fb58032936cbf5e137bb5ef67e2813c | task_15.py | task_15.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Provides variables for string and integer conversion."""
NOT_THE_QUESTION = 'The answer to life, the universe, and everything? It\'s '
ANSWER = 42
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Provides variables for string and integer conversion."""
NOT_THE_QUESTION = 'The answer to life, the universe, and everything? It\'s '
ANSWER = 42
THANKS_FOR_THE_FISH = str(NOT_THE_QUESTION) + str(ANSWER)
| Change the string to concatenate it by using str() and then make new variable equal the first str() to the second str() | Change the string to concatenate it by using str() and then make new variable equal the first str() to the second str()
| Python | mpl-2.0 | gracehyemin/is210-week-03-warmup,gracehyemin/is210-week-03-warmup |
6c2dae9bad86bf3f40d892eba50853d704f696b7 | pombola/settings/tests.py | pombola/settings/tests.py | from .base import *
COUNTRY_APP = None
INSTALLED_APPS = INSTALLED_APPS + \
('pombola.hansard',
'pombola.projects',
'pombola.place_data',
'pombola.votematch',
'speeches',
'pombola.spinner' ) + \
... | from .base import *
COUNTRY_APP = None
INSTALLED_APPS = INSTALLED_APPS + \
('pombola.hansard',
'pombola.projects',
'pombola.place_data',
'pombola.votematch',
'speeches',
'pombola.spinner',
'pom... | Make sure that the interests_register tables are created | Make sure that the interests_register tables are created
Nose tries to run the interests_register tests, but they will
fail unless the interest_register app is added to INSTALLED_APPS,
because its tables won't be created in the test database.
| Python | agpl-3.0 | patricmutwiri/pombola,geoffkilpin/pombola,mysociety/pombola,hzj123/56th,geoffkilpin/pombola,mysociety/pombola,hzj123/56th,patricmutwiri/pombola,hzj123/56th,ken-muturi/pombola,ken-muturi/pombola,geoffkilpin/pombola,mysociety/pombola,ken-muturi/pombola,mysociety/pombola,hzj123/56th,geoffkilpin/pombola,patricmutwiri/pombo... |
a5ce35c44938d37aa9727d37c0cbe0232b8e92d3 | socializr/management/commands/socializr_update.py | socializr/management/commands/socializr_update.py | '''
Main command which is meant to be run daily to get the information
from various social networks into the local db.
'''
import traceback
from django.core.management.base import BaseCommand, CommandError
from django.core.exceptions import ImproperlyConfigured
from socializr.base import get_socializr_configs
clas... | '''
Main command which is meant to be run daily to get the information
from various social networks into the local db.
'''
import traceback
from django.core.management.base import BaseCommand, CommandError
from django.core.exceptions import ImproperlyConfigured
from socializr.base import get_socializr_configs
clas... | Remove output expect when there is an error. | Remove output expect when there is an error.
| Python | mit | CIGIHub/django-socializr,albertoconnor/django-socializr |
c8a41bbf11538dbc17de12e32ba5af5e93fd0b2c | src/utils/plugins.py | src/utils/plugins.py | from utils import models
class Plugin:
plugin_name = None
display_name = None
description = None
author = None
short_name = None
stage = None
manager_url = None
version = None
janeway_version = None
is_workflow_plugin = False
jump_url = None
handshake_url = None
... | from utils import models
class Plugin:
plugin_name = None
display_name = None
description = None
author = None
short_name = None
stage = None
manager_url = None
version = None
janeway_version = None
is_workflow_plugin = False
jump_url = None
handshake_url = None
... | Add get_self and change get_or_create to avoid mis-creation. | Add get_self and change get_or_create to avoid mis-creation.
| Python | agpl-3.0 | BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway |
e32d95c40dcfa4d3eb07572d5fd4f0fda710c64c | indra/sources/phosphoELM/api.py | indra/sources/phosphoELM/api.py | import csv
ppelm_s3_key = ''
def process_from_dump(fname=None, delimiter='\t'):
ppelm_json = []
if fname is None:
# ToDo Get from S3
pass
else:
with open(fname, 'r') as f:
csv_reader = csv.reader(f.readlines(), delimiter=delimiter)
columns = next(csv_reader... | import csv
ppelm_s3_key = ''
def process_from_dump(fname=None, delimiter='\t'):
if fname is None:
# ToDo Get from S3
return []
else:
with open(fname, 'r') as f:
csv_reader = csv.reader(f.readlines(), delimiter=delimiter)
ppelm_json = _get_json_from_entry_rows(c... | Move iterator to own function | Move iterator to own function
| Python | bsd-2-clause | sorgerlab/indra,sorgerlab/belpy,sorgerlab/belpy,bgyori/indra,johnbachman/belpy,johnbachman/indra,johnbachman/belpy,johnbachman/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/indra,johnbachman/indra,bgyori/indra,johnbachman/belpy,sorgerlab/indra |
c5671ab2e5115ce9c022a97a088300dc408e2aa4 | opendc/util/path_parser.py | opendc/util/path_parser.py | import json
import sys
import re
def parse(version, endpoint_path):
"""Map an HTTP call to an API path"""
with open('opendc/api/{}/paths.json'.format(version)) as paths_file:
paths = json.load(paths_file)
endpoint_path_parts = endpoint_path.split('/')
paths_parts = [x.split('/') for x in ... | import json
import sys
import re
def parse(version, endpoint_path):
"""Map an HTTP endpoint path to an API path"""
with open('opendc/api/{}/paths.json'.format(version)) as paths_file:
paths = json.load(paths_file)
endpoint_path_parts = endpoint_path.strip('/').split('/')
paths_parts = [x.... | Make path parser robust to trailing / | Make path parser robust to trailing /
| Python | mit | atlarge-research/opendc-web-server,atlarge-research/opendc-web-server |
87844a776c2d409bdf7eaa99da06d07d77d7098e | tests/test_gingerit.py | tests/test_gingerit.py | import pytest
from gingerit.gingerit import GingerIt
@pytest.mark.parametrize("text,expected", [
(
"The smelt of fliwers bring back memories.",
"The smell of flowers brings back memories."
),
(
"Edwards will be sck yesterday",
"Edwards was sick yesterday"
),
(
... | import pytest
from gingerit.gingerit import GingerIt
@pytest.mark.parametrize("text,expected,corrections", [
(
"The smelt of fliwers bring back memories.",
"The smell of flowers brings back memories.",
[
{'start': 21, 'definition': None, 'correct': u'brings', 'text': 'bring'},... | Extend test to cover corrections output | Extend test to cover corrections output
| Python | mit | Azd325/gingerit |
b47d7b44030a8388d1860316c117e02796ba9ccc | __init__.py | __init__.py | # -*- coding: utf-8 -*-
"""
FLUID DYNAMICS SIMULATOR
Requires Python 2.7 and OpenCV 2
Tom Blanchet (c) 2013 - 2014 (revised 2017)
"""
import cv2
from fluidDoubleCone import FluidDoubleCone, RGB
from fluidDoubleConeView import FluidDCViewCtrl
def slow_example():
inImg = cv2.imread("gameFace.jpg")
game_face_dC... | # -*- coding: utf-8 -*-
"""
FLUID DYNAMICS SIMULATOR
Requires Python 2.7, pygame, numpy, and OpenCV 2
Tom Blanchet (c) 2013 - 2014 (revised 2017)
"""
import cv2
from fluidDoubleCone import FluidDoubleCone, RGB
from fluidDoubleConeView import FluidDCViewCtrl
def slow_example():
inImg = cv2.imread("gameFace.jpg")
... | Include pygame and numpy in discription. | Include pygame and numpy in discription.
| Python | apache-2.0 | FrogBomb/fluidDynamicsSimulator |
c823a476b265b46d27b221831be952a811fe3468 | ANN.py | ANN.py | class Neuron:
pass
class NeuronNetwork:
neurons = []
| class Neuron:
pass
class NeuronNetwork:
neurons = []
def __init__(self, rows, columns):
self.neurons = []
for row in xrange(rows):
self.neurons.append([])
for column in xrange(columns):
self.neurons[row].append(Neuron())
| Create 2D list of Neurons in NeuronNetwork's init | Create 2D list of Neurons in NeuronNetwork's init
| Python | mit | tysonzero/py-ann |
168937c586b228c05ada2da79a55c9416c3180d3 | antifuzz.py | antifuzz.py | '''
File: antifuzz.py
Authors: Kaitlin Keenan and Ryan Frank
'''
import sys
from shutil import copy2
import subprocess
import ssdeep #http://python-ssdeep.readthedocs.io/en/latest/installation.html
def main():
# Take in file
ogFile = sys.argv[1]
# Make copy of file
newFile = sys.argv[2]
# Mess with the giv... | '''
File: antifuzz.py
Authors: Kaitlin Keenan and Ryan Frank
'''
import sys
from shutil import copy2
import subprocess
import ssdeep #http://python-ssdeep.readthedocs.io/en/latest/installation.html
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument("originalFile", help="File to a... | Add help, make output more user friendly | Add help, make output more user friendly
| Python | mit | ForensicTools/antifuzzyhashing-475-2161_Keenan_Frank |
ee81d8966a5ef68edd6bb4459fc015234d6e0814 | setup.py | setup.py | """Open-ovf installer"""
import os
from distutils.core import setup
CODE_BASE_DIR = 'py'
SCRIPTS_DIR = 'py/scripts/'
def list_scripts():
"""List all scripts that should go to /usr/bin"""
file_list = os.listdir(SCRIPTS_DIR)
return [os.path.join(SCRIPTS_DIR, f) for f in file_list]
setup(name='open-ovf',
... | """Open-ovf installer"""
import os
from distutils.core import setup
CODE_BASE_DIR = 'py'
SCRIPTS_DIR = 'py/scripts/'
def list_scripts():
"""List all scripts that should go to /usr/bin"""
file_list = os.listdir(SCRIPTS_DIR)
return [os.path.join(SCRIPTS_DIR, f) for f in file_list]
setup(name='open-ovf',
... | Add env subdirectory to package list | Add env subdirectory to package list
Hi,
This patch adds the ovf/env subdirectory to the package list so that
setup.py installs it properly.
Signed-off-by: David L. Leskovec <376f07f909b7d4aee248a1433ee4548cc2bf1d1b@linux.vnet.ibm.com>
Signed-off-by: Scott Moser <f411aed5b71f5ab75e7f202cdde1f0f4410975aa@linux.vnet.i... | Python | epl-1.0 | Awingu/open-ovf,Awingu/open-ovf,Awingu/open-ovf,Awingu/open-ovf |
3cc473fb6316fffa3c19980115f800518dcee115 | setup.py | setup.py | import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("... | import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("... | Fix missing raven.processors in build | Fix missing raven.processors in build
| Python | mit | virtool/virtool,igboyes/virtool,virtool/virtool,igboyes/virtool |
20764887bc338c2cd366ad11fb41d8932c2326a2 | bot.py | bot.py | import json
import discord
from handlers.message_handler import MessageHandler
with open("config.json", "r") as f:
config = json.load(f)
client = discord.Client()
message_handler = MessageHandler(config, client)
@client.event
async def on_ready():
print("Logged in as", client.user.name)
@client.event
async def ... | #!/usr/bin/env python
import argparse
import json
import discord
from handlers.message_handler import MessageHandler
def main():
p = argparse.ArgumentParser()
p.add_argument("--config", required=True, help="Path to configuration file")
args = p.parse_args()
with open(args.config, "r") as f:
config = json.load... | Add --config argument as a path to the config file | Add --config argument as a path to the config file
| Python | mit | azeier/hearthbot |
a2fb1efc918e18bb0ecebce4604192b03af662b2 | fib.py | fib.py | def fibrepr(n):
fibs = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
def fib_iter(n, fibs, l):
for i, f in enumerate(fibs):
if f == n:
yield '1' + i*'0' + l
elif n > f:
for fib in fib_iter(n - f, fibs[i+1:], '1' + i*'0' + l):
yield fib
... | class Fibonacci(object):
_cache = {0: 1, 1: 2}
def __init__(self, n):
self.n = n
def get(self, n):
if not n in Fibonacci._cache:
Fibonacci._cache[n] = self.get(n-1) + self.get(n-2)
return Fibonacci._cache[n]
def next(self):
return Fibonacci(self.n + 1)
... | Add Fibonacci class and use it in representation | Add Fibonacci class and use it in representation
| Python | mit | kynan/CodeDojo30 |
57f3bec127148c80a9304194e5c3c8a3d3f3bae2 | tests/scoring_engine/web/views/test_scoreboard.py | tests/scoring_engine/web/views/test_scoreboard.py | from tests.scoring_engine.web.web_test import WebTest
class TestScoreboard(WebTest):
def test_home(self):
# todo fix this up!!!!
# resp = self.client.get('/scoreboard')
# assert resp.status_code == 200
# lazy AF
assert 1 == 1
| from tests.scoring_engine.web.web_test import WebTest
from tests.scoring_engine.helpers import populate_sample_data
class TestScoreboard(WebTest):
def test_scoreboard(self):
populate_sample_data(self.session)
resp = self.client.get('/scoreboard')
assert resp.status_code == 200
ass... | Add tests for scoreboard view | Add tests for scoreboard view
| Python | mit | pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine |
ebac72a3753205d3e45041c6db636a378187e3cf | pylua/tests/test_compiled.py | pylua/tests/test_compiled.py | import os
import subprocess
from pylua.tests.helpers import test_file
class TestCompiled(object):
"""
Tests compiled binary
"""
def test_addition(self, capsys):
f = test_file(src="""
-- short add
x = 10
y = 5
z = y + y + x
print(z)
... | import os
import subprocess
from pylua.tests.helpers import test_file
class TestCompiled(object):
"""
Tests compiled binary
"""
PYLUA_BIN = os.path.join(os.path.dirname(os.path.abspath(__file__)), ('../../bin/pylua'))
def test_addition(self, capsys):
f = test_file(src="""
--... | Use absolute path for lua binary in tests | Use absolute path for lua binary in tests
| Python | bsd-3-clause | fhahn/luna,fhahn/luna |
5577b2a20a98aa232f5591a46269e5ee6c88070d | MyMoment.py | MyMoment.py | import datetime
#Humanize time in milliseconds
#Reference: http://stackoverflow.com/questions/26276906/python-convert-seconds-from-epoch-time-into-human-readable-time
def HTM(aa):
a = int(aa)
b = int(datetime.datetime.now().strftime("%s"))
c = b - a
days = c // 86400
hours = c // 3600 % 24
minu... | import datetime
from time import gmtime, strftime
import pytz
#Humanize time in milliseconds
#Reference: http://stackoverflow.com/questions/26276906/python-convert-seconds-from-epoch-time-into-human-readable-time
#http://www.epochconverter.com/
#1/6/2015, 8:19:34 AM PST -> 23 hours ago
#print HTM(1420561174000/1000)
... | Add functions to generate timestamp for logfiles & filenames; use localtimezone | Add functions to generate timestamp for logfiles & filenames; use localtimezone
| Python | mit | harishvc/githubanalytics,harishvc/githubanalytics,harishvc/githubanalytics |
5cf17b6a46a3d4bbf4cecb65e4b9ef43066869d9 | feincms/templatetags/applicationcontent_tags.py | feincms/templatetags/applicationcontent_tags.py | from django import template
# backwards compatibility import
from feincms.templatetags.fragment_tags import fragment, get_fragment, has_fragment
register = template.Library()
register.tag(fragment)
register.tag(get_fragment)
register.filter(has_fragment)
@register.simple_tag
def feincms_render_region_appcontent(pa... | from django import template
# backwards compatibility import
from feincms.templatetags.fragment_tags import fragment, get_fragment, has_fragment
register = template.Library()
register.tag(fragment)
register.tag(get_fragment)
register.filter(has_fragment)
@register.simple_tag
def feincms_render_region_appcontent(pa... | Use all_of_type instead of isinstance check in feincms_render_region_appcontent | Use all_of_type instead of isinstance check in feincms_render_region_appcontent
| Python | bsd-3-clause | feincms/feincms,joshuajonah/feincms,feincms/feincms,matthiask/feincms2-content,matthiask/django-content-editor,michaelkuty/feincms,mjl/feincms,matthiask/feincms2-content,mjl/feincms,matthiask/django-content-editor,matthiask/django-content-editor,michaelkuty/feincms,nickburlett/feincms,matthiask/django-content-editor,jo... |
b457eac63690deba408c4b5bdc1db179347f43da | postgres/fields/uuid_field.py | postgres/fields/uuid_field.py | from __future__ import unicode_literals
import uuid
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from psycopg2.extras import register_uuid
register_uuid()
class UUIDField(six.with_metaclass(mode... | from __future__ import unicode_literals
import uuid
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from psycopg2.extras import register_uuid
register_uuid()
class UUIDField(six.with_metaclass(mode... | Make UUIDField have a fixed max-length | Make UUIDField have a fixed max-length
| Python | bsd-3-clause | wlanslovenija/django-postgres |
89fe38163426efe02da92974bac369538ab5532f | elmextensions/__init__.py | elmextensions/__init__.py | from .sortedlist import *
from .embeddedterminal import *
from .aboutwindow import *
from .fileselector import *
from .tabbedbox import *
from .StandardButton import *
from .StandardPopup import *
from .SearchableList import *
| from .sortedlist import *
from .embeddedterminal import *
from .aboutwindow import *
from .fileselector import *
from .fontselector import *
from .tabbedbox import *
from .StandardButton import *
from .StandardPopup import *
from .SearchableList import *
__copyright__ = "Copyright 2015-2017 Jeff Hoogland"
__license__... | Access to module level information | Access to module level information | Python | bsd-3-clause | JeffHoogland/python-elm-extensions |
f517442097b6ae12eb13b16f2fa6ca40a00b9998 | __init__.py | __init__.py | from .features import Giraffe_Feature_Base
from .features import Aligned_Feature
| from .features import Giraffe_Feature_Base
from .features import Aligned_Feature
from .features import Feature_Type_Choices
| Move Feature_Type_Choices to toplevel name sapce | Move Feature_Type_Choices to toplevel name sapce
| Python | mit | benjiec/giraffe-features |
0830f131b50d9679e6b2097febc7913bc09e5132 | mopidy_scrobbler/__init__.py | mopidy_scrobbler/__init__.py | import pathlib
from mopidy import config, ext
__version__ = "1.2.1"
class Extension(ext.Extension):
dist_name = "Mopidy-Scrobbler"
ext_name = "scrobbler"
version = __version__
def get_default_config(self):
return config.read(pathlib.Path(__file__).parent / "ext.conf")
def get_config_s... | import pathlib
import pkg_resources
from mopidy import config, ext
__version__ = pkg_resources.get_distribution("Mopidy-Scrobbler").version
class Extension(ext.Extension):
dist_name = "Mopidy-Scrobbler"
ext_name = "scrobbler"
version = __version__
def get_default_config(self):
return conf... | Use pkg_resources to read version | Use pkg_resources to read version
| Python | apache-2.0 | mopidy/mopidy-scrobbler |
48ffd37eb826edb78750652628145a924053b204 | website/wsgi.py | website/wsgi.py | """
WSGI config for classicalguitar project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "classicalguitar.settings")
fr... | """
WSGI config for website project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "website.settings")
from django.core.w... | Correct some remaining classical guitar refs | Correct some remaining classical guitar refs
| Python | bsd-3-clause | chrisguitarguy/GuitarSocieties.org,chrisguitarguy/GuitarSocieties.org |
5a8788222d9a5765bf66a2c93eed25ca7879c856 | __init__.py | __init__.py | import inspect
import sys
if sys.version_info[0] == 2:
from .python2 import httplib2
else:
from .python3 import httplib2
globals().update(inspect.getmembers(httplib2))
| import os
import sys
path = os.path.dirname(__file__)+os.path.sep+'python'+str(sys.version_info[0])
sys.path.insert(0, path)
del sys.modules['httplib2']
import httplib2
| Rewrite python version dependent import | Rewrite python version dependent import
The top level of this external includes a __init__.py so that
it may be imported with only 'externals' in sys.path.
However it copies the contents of the python version dependent httplib2
code, resulting in module level variables appearing in two different
namespaces. As a res... | Python | mit | jayvdb/httplib2,wikimedia/pywikibot-externals-httplib2,jayvdb/httplib2,wikimedia/pywikibot-externals-httplib2 |
2b2e0b180393af779c7d303a1a3162febe098639 | permuta/misc/union_find.py | permuta/misc/union_find.py |
class UnionFind(object):
def __init__(self, n):
self.p = [-1]*n
self.leaders = set( i for i in range(n) )
def find(self, x):
if self.p[x] < 0:
return x
self.p[x] = self.find(self.p[x])
return self.p[x]
def size(self, x):
return -self.p[self.find... |
class UnionFind(object):
"""A collection of distjoint sets."""
def __init__(self, n = 0):
"""Creates a collection of n disjoint unit sets."""
self.p = [-1]*n
self.leaders = set( i for i in range(n) )
def find(self, x):
"""Return the identifier of a representative element f... | Document UnionFind and implement add function | Document UnionFind and implement add function
| Python | bsd-3-clause | PermutaTriangle/Permuta |
40e96e99dc8538ae3b5e5a95d9c6d81ec656ad6c | dash2012/auth/views.py | dash2012/auth/views.py | from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
from django.contrib.auth.decorators import login_required
from cloudfish.models import Cloud
def login(... | from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
from django.contrib.auth.decorators import login_required
from cloudfish.models import Cloud
def login(... | Fix erros msg in login view | Fix erros msg in login view
| Python | bsd-3-clause | losmiserables/djangodash2012,losmiserables/djangodash2012 |
01c5b53ba16a95ab77918d30dfa3a63f2ef2707f | var/spack/repos/builtin/packages/libxcb/package.py | var/spack/repos/builtin/packages/libxcb/package.py | from spack import *
class Libxcb(Package):
"""The X protocol C-language Binding (XCB) is a replacement
for Xlib featuring a small footprint, latency hiding, direct
access to the protocol, improved threading support, and
extensibility."""
homepage = "http://xcb.freedesktop.org/"
url = "... | from spack import *
class Libxcb(Package):
"""The X protocol C-language Binding (XCB) is a replacement
for Xlib featuring a small footprint, latency hiding, direct
access to the protocol, improved threading support, and
extensibility."""
homepage = "http://xcb.freedesktop.org/"
url = "htt... | Make libxcb compile with gcc 4.9. | Make libxcb compile with gcc 4.9.
| Python | lgpl-2.1 | krafczyk/spack,krafczyk/spack,mfherbst/spack,skosukhin/spack,tmerrick1/spack,iulian787/spack,EmreAtes/spack,lgarren/spack,EmreAtes/spack,matthiasdiener/spack,lgarren/spack,TheTimmy/spack,LLNL/spack,mfherbst/spack,lgarren/spack,iulian787/spack,skosukhin/spack,LLNL/spack,LLNL/spack,mfherbst/spack,skosukhin/spack,matthias... |
79e68ca4b377f479d7eb557879b3450134efaf16 | ydf/yaml_ext.py | ydf/yaml_ext.py | """
ydf/yaml_ext
~~~~~~~~~~~~
Contains extensions to existing YAML functionality.
"""
import collections
from ruamel import yaml
from ruamel.yaml import resolver
__all__ = ['load_all', 'load_all_gen']
class OrderedRoundTripLoader(yaml.RoundTripLoader):
"""
Extends the default round trip YAML ... | """
ydf/yaml_ext
~~~~~~~~~~~~
Contains extensions to existing YAML functionality.
"""
import collections
from ruamel import yaml
from ruamel.yaml import resolver
__all__ = ['load', 'load_all', 'load_all_gen']
class OrderedRoundTripLoader(yaml.RoundTripLoader):
"""
Extends the default round tr... | Add YAML load for single document. | Add YAML load for single document.
| Python | apache-2.0 | ahawker/ydf |
785236ca766d832d859c2933389e23fd3d1bea20 | djangocms_table/cms_plugins.py | djangocms_table/cms_plugins.py | from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from models import Table
from djangocms_table.forms import TableForm
from django.utils import simplejson
from djangocms_table.utils import static_url... | import json
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from models import Table
from djangocms_table.forms import TableForm
from djangocms_table.utils import static_url
from django.http import... | Fix another simplejson deprecation warning | Fix another simplejson deprecation warning
| Python | bsd-3-clause | freelancersunion/djangocms-table,freelancersunion/djangocms-table,freelancersunion/djangocms-table,divio/djangocms-table,divio/djangocms-table,divio/djangocms-table |
17d54738a57a355fef3e83484162af13ecd2ea63 | localore/localore_admin/migrations/0003_auto_20160316_1646.py | localore/localore_admin/migrations/0003_auto_20160316_1646.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('localore_admin', '0002_auto_20160316_1444'),
]
run_before = [
('home', '0002_create_homepage'),
]
operations = [
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('localore_admin', '0002_auto_20160316_1444'),
]
run_before = [
('home', '0002_create_homepage'),
('people', '0006_aut... | Fix (?) another custom image model migration error | Fix (?) another custom image model migration error
| Python | mpl-2.0 | ghostwords/localore,ghostwords/localore,ghostwords/localore |
6b3f568a6615e9439fc0df0eac68838b6cbda0d9 | anti-XSS.py | anti-XSS.py | #!/usr/bin/env python
'''
Copyright (c) 2016 anti-XSS developers
'''
import sys
from lib.core.link import Link
from optparse import OptionParser
from lib.core.engine import getPage
from lib.core.engine import getScript
from lib.core.engine import xssScanner
from lib.generator.report import gnrReport
def main():
... | #!/usr/bin/env python
'''
Copyright (c) 2016 anti-XSS developers
'''
import sys
from lib.core.urlfun import *
from lib.core.link import Link
from optparse import OptionParser
from lib.core.engine import getPage
from lib.core.engine import getScript
from lib.core.engine import xssScanner
from lib.generator.report im... | Add initialization before get url | Add initialization before get url
| Python | mit | lewangbtcc/anti-XSS,lewangbtcc/anti-XSS |
19d99f6040d1474feee0f2fb0bda7cb14fbf407c | nose2/tests/unit/test_config.py | nose2/tests/unit/test_config.py | from nose2 import config
from nose2.compat import unittest
class TestConfigSession(unittest.TestCase):
def test_can_create_session(self):
config.Session()
class TestConfig(unittest.TestCase):
def setUp(self):
self.conf = config.Config([
('a', ' 1 '), ('b', ' x\n y '), ('c',... | from nose2 import config
from nose2.compat import unittest
class TestConfigSession(unittest.TestCase):
def test_can_create_session(self):
config.Session()
def test_load_plugins_from_module_can_load_plugins(self):
class fakemod:
pass
f = fakemod()
class A(events.Plu... | Add test for as_list bugfix | Add test for as_list bugfix
| Python | bsd-2-clause | ojengwa/nose2,little-dude/nose2,leth/nose2,leth/nose2,ptthiem/nose2,ptthiem/nose2,ezigman/nose2,ojengwa/nose2,ezigman/nose2,little-dude/nose2 |
a3df62c7da4aa29ab9977a0307e0634fd43e37e8 | pywebfaction/exceptions.py | pywebfaction/exceptions.py | import ast
EXCEPTION_TYPE_PREFIX = "<class 'webfaction_api.exceptions."
EXCEPTION_TYPE_SUFFIX = "'>"
def _parse_exc_type(exc_type):
# This is horribly hacky, but there's not a particularly elegant
# way to go from the exception type to a string representing that
# exception.
if not exc_type.startswi... | import ast
EXCEPTION_TYPE_PREFIX = "<class 'webfaction_api.exceptions."
EXCEPTION_TYPE_SUFFIX = "'>"
def _parse_exc_type(exc_type):
# This is horribly hacky, but there's not a particularly elegant
# way to go from the exception type to a string representing that
# exception.
if not exc_type.startswi... | Make code immune to bad fault messages | Make code immune to bad fault messages
| Python | bsd-3-clause | dominicrodger/pywebfaction,dominicrodger/pywebfaction |
9f345963d1c8dc25818d2cf6716d40e6c90cb615 | sentry/client/handlers.py | sentry/client/handlers.py | import logging
import sys
class SentryHandler(logging.Handler):
def emit(self, record):
from sentry.client.models import get_client
from sentry.client.middleware import SentryLogMiddleware
# Fetch the request from a threadlocal variable, if available
request = getattr(SentryLogMidd... | import logging
import sys
class SentryHandler(logging.Handler):
def emit(self, record):
from sentry.client.models import get_client
from sentry.client.middleware import SentryLogMiddleware
# Fetch the request from a threadlocal variable, if available
request = getattr(SentryLogMidd... | Format records before referencing the message attribute | Format records before referencing the message attribute
| Python | bsd-3-clause | pauloschilling/sentry,ngonzalvez/sentry,gencer/sentry,camilonova/sentry,NickPresta/sentry,Natim/sentry,dbravender/raven-python,fuziontech/sentry,korealerts1/sentry,jmagnusson/raven-python,imankulov/sentry,felixbuenemann/sentry,songyi199111/sentry,jokey2k/sentry,SilentCircle/sentry,zenefits/sentry,jean/sentry,jbarbuto/r... |
e7e21188daba6efe02d44c2cef9c1b48c45c0636 | readthedocs/donate/urls.py | readthedocs/donate/urls.py | from django.conf.urls import url, patterns, include
from . import views
urlpatterns = patterns(
'',
url(r'^$', views.DonateListView.as_view(), name='donate'),
url(r'^contribute/$', views.DonateCreateView.as_view(), name='donate_add'),
url(r'^contribute/thanks$', views.DonateSuccessView.as_view(), nam... | from django.conf.urls import url, patterns, include
from .views import DonateCreateView
from .views import DonateListView
from .views import DonateSuccessView
urlpatterns = patterns(
'',
url(r'^$', DonateListView.as_view(), name='donate'),
url(r'^contribute/$', DonateCreateView.as_view(), name='donate_ad... | Resolve linting messages in readthedocs.donate.* | Resolve linting messages in readthedocs.donate.*
| Python | mit | mhils/readthedocs.org,wijerasa/readthedocs.org,davidfischer/readthedocs.org,atsuyim/readthedocs.org,CedarLogic/readthedocs.org,istresearch/readthedocs.org,wanghaven/readthedocs.org,atsuyim/readthedocs.org,CedarLogic/readthedocs.org,hach-que/readthedocs.org,mhils/readthedocs.org,kenwang76/readthedocs.org,kenwang76/readt... |
650e0497c99500810f0fd1fc205e975892b26ff2 | ibmcnx/doc/DataSources.py | ibmcnx/doc/DataSources.py | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | Create documentation of DataSource Settings | 8: Create documentation of DataSource Settings
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 |
a4eb952cc2e583d3b7786f5dea101d1e013c8159 | services/controllers/utils.py | services/controllers/utils.py | def map_range(x, in_min, in_max, out_min, out_max):
out_delta = out_max - out_min
in_delta = in_max - in_min
return (x - in_min) * out_delta / in_delta + out_min
| def lerp(a, b, t):
return (1.0 - t) * a + t * b
def map_range(x, in_min, in_max, out_min, out_max):
out_delta = out_max - out_min
in_delta = in_max - in_min
return (x - in_min) * out_delta / in_delta + out_min
| Add function for linear interpolation (lerp) | Add function for linear interpolation (lerp)
| Python | bsd-3-clause | gizmo-cda/g2x-submarine-v2,gizmo-cda/g2x-submarine-v2,gizmo-cda/g2x-submarine-v2,gizmo-cda/g2x-submarine-v2 |
a509cd74d1e49dd9f9585b8e4c43e88aaf2bc19d | tests/stonemason/service/tileserver/test_tileserver.py | tests/stonemason/service/tileserver/test_tileserver.py | # -*- encoding: utf-8 -*-
"""
tests.stonemason.service.tileserver.test_tileserver
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test interfaces of the tile server application.
"""
import os
import unittest
from stonemason.service.tileserver import AppBuilder
class TestExample(unittest.TestCase):
... | # -*- encoding: utf-8 -*-
"""
tests.stonemason.service.tileserver.test_tileserver
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test interfaces of the tile server application.
"""
import os
import unittest
from stonemason.service.tileserver import AppBuilder
class TestExample(unittest.TestCase):
... | Update tests for the test app | TEST: Update tests for the test app
| Python | mit | Kotaimen/stonemason,Kotaimen/stonemason |
7b66af8bea8e6c25e3c2f88efc22875504e8f87a | openstates/events.py | openstates/events.py | from pupa.scrape import Event
from .base import OpenstatesBaseScraper
import dateutil.parser
dparse = lambda x: dateutil.parser.parse(x) if x else None
class OpenstatesEventScraper(OpenstatesBaseScraper):
def scrape(self):
method = 'events/?state={}&dtstart=1776-07-04'.format(self.state)
self.e... | from pupa.scrape import Event
from .base import OpenstatesBaseScraper
import dateutil.parser
dparse = lambda x: dateutil.parser.parse(x) if x else None
class OpenstatesEventScraper(OpenstatesBaseScraper):
def scrape(self):
method = 'events/?state={}&dtstart=1776-07-04'.format(self.state)
self.e... | Add more keys in; validation | Add more keys in; validation
| Python | bsd-3-clause | openstates/billy,sunlightlabs/billy,sunlightlabs/billy,openstates/billy,sunlightlabs/billy,openstates/billy |
14bd2c0732b5871ac43991a237a8f12a334e982d | sirius/LI_V00/__init__.py | sirius/LI_V00/__init__.py | from . import lattice as _lattice
from . import accelerator as _accelerator
from . import record_names
create_accelerator = accelerator.create_accelerator
# -- default accelerator values for LI_V00 --
energy = _lattice._energy
single_bunch_charge = _lattice._single_bunch_charge
multi_bunch_charge = _lattice... | from . import lattice as _lattice
from . import accelerator as _accelerator
from . import record_names
create_accelerator = accelerator.create_accelerator
# -- default accelerator values for LI_V00 --
energy = _lattice._energy
single_bunch_charge = _lattice._single_bunch_charge
multi_bunch_charge = _lattice... | Add parameters of initial beam distribution at LI | Add parameters of initial beam distribution at LI
| Python | mit | lnls-fac/sirius |
c3ead28e278e2b4e3d44071fb891fa54de46b237 | shopping_app/utils/helpers.py | shopping_app/utils/helpers.py | import os
import random
import string
from datetime import date, datetime
def random_name():
return ''.join([random.choice(string.ascii_lowercase + string.digits) for n in range(20)])
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datet... | import os
import random
import string
from datetime import date, datetime
def random_name():
return ''.join([random.choice(string.ascii_lowercase + string.digits) for n in range(20)])
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datet... | Update generate_secret function to the root of the app | Update generate_secret function to the root of the app
| Python | mit | gr1d99/shopping-list,gr1d99/shopping-list,gr1d99/shopping-list |
61448043a039543c38c5ca7b9828792cfc8afbb8 | justwatch/justwatchapi.py | justwatch/justwatchapi.py | import requests
from babel import Locale
class JustWatch:
def __init__(self, country='AU', **kwargs):
self.kwargs = kwargs
self.country = country
self.language = Locale.parse('und_{}'.format(self.country)).language
def search_for_item(self, **kwargs):
if kwargs:
self.kwargs = kwargs
null = None
pay... | import requests
from babel import Locale
class JustWatch:
def __init__(self, country='AU', **kwargs):
self.kwargs = kwargs
self.country = country
self.language = Locale.parse('und_{}'.format(self.country)).language
def search_for_item(self, **kwargs):
if kwargs:
self.kwargs = kwargs
null = None
pay... | Check and raise HTTP errors | Check and raise HTTP errors
| Python | mit | dawoudt/JustWatchAPI |
fc70feec85f0b22ebef05b0fa1316214a48a465a | background/config/prod.py | background/config/prod.py | from decouple import config
from .base import BaseCeleryConfig
class CeleryProduction(BaseCeleryConfig):
enable_utc = config('CELERY_ENABLE_UTC', default=True, cast=bool)
broker_url = config('CELERY_BROKER_URL')
result_backend = config('CELERY_RESULT_BACKEND')
| from decouple import config
from .base import BaseCeleryConfig
REDIS_URL = config('REDIS_URL')
class CeleryProduction(BaseCeleryConfig):
enable_utc = config('CELERY_ENABLE_UTC', default=True, cast=bool)
broker_url = config('CELERY_BROKER_URL',
default=REDIS_URL)
result_backend = ... | Use REDIS_URL by default for Celery | Use REDIS_URL by default for Celery
| Python | mit | RaitoBezarius/ryuzu-fb-bot |
dd0cef83edbd3849484b7fc0ec5cb6372f99bb3a | batchflow/models/utils.py | batchflow/models/utils.py | """ Auxiliary functions for models """
def unpack_args(args, layer_no, layers_max):
""" Return layer parameters """
new_args = {}
for arg in args:
if isinstance(args[arg], list) and layers_max > 1:
if len(args[arg]) >= layers_max:
arg_value = args[arg][layer_no]
... | """ Auxiliary functions for models """
def unpack_args(args, layer_no, layers_max):
""" Return layer parameters """
new_args = {}
for arg in args:
if isinstance(args[arg], list):
if len(args[arg]) >= layers_max:
arg_value = args[arg][layer_no]
else:
... | Allow for 1 arg in a list | Allow for 1 arg in a list
| Python | apache-2.0 | analysiscenter/dataset |
5c3863fdb366f857fb25b88c2e47508f23660cf3 | tests/test_socket.py | tests/test_socket.py | import socket
from unittest import TestCase
try:
from unitetest import mock
except ImportError:
import mock
from routeros_api import api_socket
class TestSocketWrapper(TestCase):
def test_socket(self):
inner = mock.Mock()
wrapper = api_socket.SocketWrapper(inner)
inner.recv.side_e... | import socket
from unittest import TestCase
try:
from unitetest import mock
except ImportError:
import mock
from routeros_api import api_socket
class TestSocketWrapper(TestCase):
def test_socket(self):
inner = mock.Mock()
wrapper = api_socket.SocketWrapper(inner)
inner.recv.side_e... | Fix python2.6 compatibility in tests. | Fix python2.6 compatibility in tests.
| Python | mit | kramarz/RouterOS-api,socialwifi/RouterOS-api,pozytywnie/RouterOS-api |
889473ba81816aa0ad349823515843c337a6b985 | benchexec/tools/deagle.py | benchexec/tools/deagle.py | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.util as util
import benchexec.tools.tem... | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.util as util
import benchexec.tools.tem... | Move --closure and --no-unwinding-assertions to bench-defs; rewrite choices between --32 and --64 | Move --closure and --no-unwinding-assertions to bench-defs; rewrite choices between --32 and --64
| Python | apache-2.0 | ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.