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 |
|---|---|---|---|---|---|---|---|---|---|
1a06f983a3edf3ee2f887c2e2094eb76820b5a73 | examples/arabic.py | examples/arabic.py | #!/usr/bin/env python
"""
Create wordcloud with Arabic
===============
Generating a wordcloud from Arabic text
Dependencies:
- bidi.algorithm
- arabic_reshaper
Dependencies installation:
pip install python-bidi arabic_reshape
"""
from os import path
import codecs
from wordcloud import WordCloud
import arabic_reshape... | #!/usr/bin/env python
"""
Create wordcloud with Arabic
===============
Generating a wordcloud from Arabic text
Dependencies:
- bidi.algorithm
- arabic_reshaper
Dependencies installation:
pip install python-bidi arabic_reshape
"""
import os
import codecs
from wordcloud import WordCloud
import arabic_reshaper
from bid... | Fix the __file__ is not defined bug | Fix the __file__ is not defined bug
| Python | mit | amueller/word_cloud |
633ba35c87f62b70e0aae275519514632d33a777 | googleanalytics/__init__.py | googleanalytics/__init__.py | # encoding: utf-8
from . import auth, commands, tests, utils, account, auth, blueprint, columns, errors, query, segments
from .auth import authenticate, authorize, revoke
from .blueprint import Blueprint
| # encoding: utf-8
import pkg_resources
from . import auth, commands, tests, utils, account, auth, blueprint, columns, errors, query, segments
from .auth import authenticate, authorize, revoke
from .blueprint import Blueprint
__version__ = pkg_resources.get_distribution("googleanalytics").version | Add version number to package. | Add version number to package.
| Python | isc | debrouwere/google-analytics |
4e6c901140a667612fd311a2f18e1b7c18bafcd0 | tests/test_octadecane_benchmarks.py | tests/test_octadecane_benchmarks.py | """ This module runs the benchmark test suite. """
from .context import phaseflow
def test_lid_driven_cavity_benchmark__ci__():
phaseflow.helpers.run_simulation_with_temporary_output(
phaseflow.octadecane_benchmarks.LidDrivenCavityBenchmarkSimulation())
def test_lid_driven_cavity_benchmark_with... | """ This module runs the benchmark test suite. """
from .context import phaseflow
def test_lid_driven_cavity_benchmark_with_solid_subdomain__ci__():
phaseflow.helpers.run_simulation_with_temporary_output(
phaseflow.octadecane_benchmarks.LDCBenchmarkSimulationWithSolidSubdomain())
def test_h... | Test restarting with Stefan problem instead of heat driven cavity. Removed some redundant tests | Test restarting with Stefan problem instead of heat driven cavity. Removed some redundant tests
| Python | mit | geo-fluid-dynamics/phaseflow-fenics |
c3526f51afc23a4c672e86a850c4f49d094a2482 | libpb/port/__init__.py | libpb/port/__init__.py | """FreeBSD Ports."""
from __future__ import absolute_import
__all__ = ["get_port"]
class PortCache(object):
"""Caches created ports."""
def __init__(self):
"""Initialise port cache."""
self._ports = {}
self._waiters = {}
def __len__(self):
return len(self._ports)
d... | """FreeBSD Ports."""
from __future__ import absolute_import
__all__ = ["get_port", "get_ports", "ports"]
class PortCache(object):
"""Caches created ports."""
def __init__(self):
"""Initialise port cache."""
self._ports = {}
self._waiters = {}
def __len__(self):
return l... | Add ability to iterate over all currently loaded ports. | Add ability to iterate over all currently loaded ports.
This function provides a snapshot of ports and does not provide support to
query ports that are still loading.
| Python | bsd-2-clause | DragonSA/portbuilder,DragonSA/portbuilder |
029d5c9f85dedbe8d1b4d41a8cb27d70652c9c1b | tools/clean_output_directory.py | tools/clean_output_directory.py | #!/usr/bin/env python
#
# Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
#
import shutil
import sys
import subprocess
import utils
def Main():
build_roo... | #!/usr/bin/env python
#
# Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
#
import os
import shutil
import sys
import subprocess
import utils
def Main():
... | Add missing python import to utility script | Add missing python import to utility script
BUG=
R=lrn@google.com
Review URL: https://codereview.chromium.org//1226963005.
| Python | bsd-3-clause | dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart... |
335ce70414ffecbfc506ce2c22a5a7e4aeeca1a1 | sda/__init__.py | sda/__init__.py | # -*- coding: utf-8 -*-
"""sda
.. codeauthor:: John Lane <jlane@fanthreesixty.com>
"""
from sda import element
from sda import locators
from sda import mixins
from sda import page
from sda import site
from sda import structures
__author__ = 'jlane'
__email__ = 'jlane@fanthreesixty.com'
__license__ = "MIT"
__version... | # -*- coding: utf-8 -*-
"""sda
.. codeauthor:: John Lane <jlane@fanthreesixty.com>
"""
from sda import locators
from sda import mixins
from sda import structures
from sda.element import Element
from sda.page import Page
from sda.site import Site
__author__ = 'jlane'
__email__ = 'jlane@fanthreesixty.com'
__license__... | Streamline imports for Element, Page and Site | Streamline imports for Element, Page and Site
| Python | mit | jlane9/selenium_data_attributes,jlane9/selenium_data_attributes |
51b179a6d8d2bef2a0371c870dbc1b7b3ebc9a38 | grammpy/Grammars/Grammar.py | grammpy/Grammars/Grammar.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 16.08.2017 19:25
:Licence GNUv3
Part of grammpy
"""
from .CopyableGrammar import CopyableGrammar as _G
class Grammar(_G):
def __copy__(self):
return self.copy()
def copy(self, terminals=False, nonterminals=False, rules=False):
c = ... | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 16.08.2017 19:25
:Licence GNUv3
Part of grammpy
"""
from .CopyableGrammar import CopyableGrammar as _G
class Grammar(_G):
def __copy__(self):
return self.copy()
def copy(self, terminals=False, nonterminals=False, rules=False):
c = ... | Remove method for copying rules only | Remove method for copying rules only
| Python | mit | PatrikValkovic/grammpy |
56fde910c417a8d1943e5ff110327fee49cb4a6d | fineants/models.py | fineants/models.py | # -*- coding: utf-8 -*-
from datetime import datetime
from django.contrib.auth.models import User
from django.db import models
class Transaction(models.Model):
title = models.CharField("Title", max_length=255, blank=False)
creditor = models.ForeignKey(User, verbose_name="Creditor", related_name="Creditor")
... | # -*- coding: utf-8 -*-
from datetime import datetime
from django.contrib.auth.models import User
from django.db import models
class Transaction(models.Model):
title = models.CharField("Title", max_length=255, blank=False)
creditor = models.ForeignKey(User, verbose_name="Creditor", related_name="Creditor")
... | Add description field to transaction | Add description field to transaction
| Python | mit | n2o/FineAnts,n2o/FineAnts |
bb319f73d16066ffae81cd1f0a7d644b7621dec7 | shcol/config.py | shcol/config.py | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2015, Sebastian Linke
# Released under the Simplified BSD license
# (see LICENSE file for details).
"""
Constants that are used by `shcol` in many places. This is meant to modified (if
needed) only *before* running `shcol`, since most of these constants are only
read durin... | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2015, Sebastian Linke
# Released under the Simplified BSD license
# (see LICENSE file for details).
"""
Constants that are used by `shcol` in many places. This is meant to modified (if
needed) only *before* running `shcol`, since most of these constants are only
read durin... | Use UTF-8 as default encoding. | Use UTF-8 as default encoding.
| Python | bsd-2-clause | seblin/shcol |
fb63b49302560d4ab139c3749347edf5878a18c9 | modules/pushover.py | modules/pushover.py | import http.client
import urllib
def send_message(settings, message):
conn = http.client.HTTPSConnection("api.pushover.net:443")
conn.request("POST", "/1/messages.json",
urllib.parse.urlencode({
"token": settings.PUSHOVER_APP_TOKEN,
"user": settings.P... | import http.client
import urllib
def send_message(settings, message, title="Argus"):
conn = http.client.HTTPSConnection("api.pushover.net:443")
conn.request("POST", "/1/messages.json",
urllib.parse.urlencode({
"token": settings.PUSHOVER_APP_TOKEN,
"us... | Support for title in the notification, defaulting to 'Argus' | Support for title in the notification, defaulting to 'Argus'
| Python | apache-2.0 | aquatix/argus,aquatix/argus |
68673a0c3185b9575ec031c7b7590e5bc091ccb5 | h2o-bindings/bin/gen_all.py | h2o-bindings/bin/gen_all.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import print_function
import gen_csharp
import gen_docs_json
import gen_java
import gen_python
import gen_thrift
import bindings
import sys, os
sys.path.insert(0, "../../scripts")
import run
# Create results/ folder, where H2OCloud stores its logs
if not... | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import print_function
import gen_csharp
import gen_docs_json
import gen_java
import gen_python
import gen_thrift
import bindings
import sys, os
sys.path.insert(0, "../../scripts")
import run
# Create results folder, where H2OCloud stores its logs, and ..... | Create test-results folder, to make Jenkins happy | Create test-results folder, to make Jenkins happy
| Python | apache-2.0 | h2oai/h2o-dev,mathemage/h2o-3,mathemage/h2o-3,mathemage/h2o-3,michalkurka/h2o-3,jangorecki/h2o-3,jangorecki/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,mathemage/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,spennihana/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,spennihana/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/... |
8ee418b9a51d418901951b4f7d4cc975b203c0ed | blanc_basic_assets/listeners.py | blanc_basic_assets/listeners.py | from django.db.models.signals import pre_save, post_delete
from django.core.files.storage import default_storage
def asset_file_change(sender, instance, **kwargs):
# Must be saved already
if instance.pk is not None:
try:
old_obj = sender.objects.get(pk=instance.pk)
# Delete th... | from django.db.models.signals import post_delete, pre_save
def asset_file_change(sender, instance, **kwargs):
# Must be saved already
if instance.pk is not None:
old_obj = sender.objects.get(pk=instance.pk)
# Delete the old file if the file names don't match
if old_obj.file.name != in... | Fix file deletion if we're using remote storage | Fix file deletion if we're using remote storage
| Python | bsd-3-clause | blancltd/blanc-basic-assets |
b04afdc4a6808029443e8107c651a24ba5f9842a | gitman/__init__.py | gitman/__init__.py | """Package for GitMan."""
from pkg_resources import get_distribution
from .commands import delete as uninstall # pylint: disable=redefined-builtin
from .commands import display as list
from .commands import init, install, lock, update
__version__ = get_distribution("gitman").version
| """Package for GitMan."""
from pkg_resources import DistributionNotFound, get_distribution
from .commands import delete as uninstall # pylint: disable=redefined-builtin
from .commands import display as list
from .commands import init, install, lock, update
try:
__version__ = get_distribution("gitman").version
e... | Handle missing distribution on ReadTheDocs | Handle missing distribution on ReadTheDocs
| Python | mit | jacebrowning/gitman |
42f2f4453552c2c01c0a066ba800b4c92d9d06f6 | src/txacme/challenges/_http.py | src/txacme/challenges/_http.py | """
``http-01`` challenge implementation.
"""
from twisted.web.http import OK
from twisted.web.resource import Resource
from zope.interface import implementer
from txacme.interfaces import IResponder
@implementer(IResponder)
class HTTP01Responder(object):
"""
An ``http-01`` challenge responder for txsni.
... | """
``http-01`` challenge implementation.
"""
from twisted.web.resource import Resource
from twisted.web.static import Data
from zope.interface import implementer
from txacme.interfaces import IResponder
@implementer(IResponder)
class HTTP01Responder(object):
"""
An ``http-01`` challenge responder for txsni... | Make HTTP01Responder's resource be at the token's path | Make HTTP01Responder's resource be at the token's path
* Not /.well-known/acme-challenge/<token>, just /<token>
* Use twisted.web.static.Data as the child resource
| Python | mit | mithrandi/txacme |
4212b35221a69468b62f933e3dbe5ffeaa9d53dc | tests/test_domain_parser.py | tests/test_domain_parser.py | import unittest
from domain_parser import domain_parser
class DomainParserTestCase(unittest.TestCase):
def test_google(self):
"""Is google.com properly parsed?"""
assert domain_parser.parse_domain(
'http://www.google.com') == ('com', 'google', 'www')
def test_guardian(self):
... | # -*- coding: utf-8 -*-
import unittest
from domain_parser import domain_parser
class DomainParserTestCase(unittest.TestCase):
def test_google(self):
"""Is google.com properly parsed?"""
assert domain_parser.parse_domain(
'http://www.google.com') == ('com', 'google', 'www')
d... | Add test for internationalized domain names | Add test for internationalized domain names
Test that a domain name composed entirely of non-latin characters is
parsed properly. This should always pass with Python 3 but it will fail
with Python 2 because 'parse_domain' returns 'str(second_level_domain)',
which tries to encode second_level_domain in ASCII.
| Python | apache-2.0 | jeffknupp/domain-parser,jeffknupp/domain-parser |
b7175449096717dcce9d3f90dd55e341a350b47b | flask_nav/elements.py | flask_nav/elements.py | from flask import url_for, request, current_app
from markupsafe import Markup
from . import get_renderer
class NavigationItem(object):
def render(self, renderer=None, **kwargs):
return Markup(
get_renderer(current_app, renderer)(**kwargs).visit(self)
)
class TagItem(NavigationItem):... | from flask import url_for, request, current_app
from markupsafe import Markup
from . import get_renderer
class NavigationItem(object):
active = False
def render(self, renderer=None, **kwargs):
return Markup(
get_renderer(current_app, renderer)(**kwargs).visit(self)
)
class TagI... | Make all navigation items have an active attribute. | Make all navigation items have an active attribute.
| Python | mit | mbr/flask-nav,mbr/flask-nav |
efcdeb17ec1e3afdfbdbb50a201f90c422d7cd8e | tovp/contacts/lookups.py | tovp/contacts/lookups.py | from ajax_select import LookupChannel
from django.utils.html import escape
from django.db.models import Q
from .models import Person
class PersonLookup(LookupChannel):
model = Person
def get_query(self, q, request):
return Person.objects.filter(Q(first_name__icontains=q) | Q(initiated_name__icontain... | from ajax_select import LookupChannel
from django.core.exceptions import PermissionDenied
from django.utils.html import escape
from django.db.models import Q
from .models import Person
class PersonLookup(LookupChannel):
model = Person
def get_query(self, q, request):
return Person.objects.filter(Q(f... | Allow to add contact to logged in users. | Allow to add contact to logged in users.
| Python | mit | phani00/tovp,mayapurmedia/tovp,phani00/tovp,mayapurmedia/tovp,mayapurmedia/tovp,phani00/tovp |
b9388a64b274277eff32fe53c856527716eee282 | docs/examples/servo_sweep.py | docs/examples/servo_sweep.py | from gpiozero import Servo
from gpiozero.tools import sin_values
servo = Servo(17)
servo.source = sin_values()
servo.source_delay = 0.1
| from gpiozero import Servo
from gpiozero.tools import sin_values
from signal import pause
servo = Servo(17)
servo.source = sin_values()
servo.source_delay = 0.1
pause()
| Fix servo sweep example in docs | Fix servo sweep example in docs | Python | bsd-3-clause | waveform80/gpio-zero |
9698dc9da2ca2ac9ba632b14e5757f0f930efe9d | Mollie/API/Object/List.py | Mollie/API/Object/List.py | from .Base import Base
class List(Base):
def __init__(self, result, object_type):
Base.__init__(self, result)
self.object_type = object_type
def __iter__(self):
for item in self['data']:
yield self.object_type(item)
def getTotalCount(self):
if 'totalCount' not... | from .Base import Base
class List(Base):
def __init__(self, result, object_type):
Base.__init__(self, result)
self.object_type = object_type
def getResourceName(self):
return self.object_type.__name__.lower() + 's'
def __iter__(self):
for item in self['_embedded'][self.ge... | Make list objects return the embedded resource data again | Make list objects return the embedded resource data again
| Python | bsd-2-clause | mollie/mollie-api-python |
7a4d9c88895449b54d016226a383bde40502060c | supersaver/product/managers.py | supersaver/product/managers.py | from django.apps import apps
from django.db.models import manager
from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank
class ProductManager (manager.Manager):
# Custom manager to facilitate product query
# Refs: https://docs.djangoproject.com/en/2.0/topics/db/managers/
def sear... | from datetime import datetime
from django.apps import apps
from django.db.models import manager
from django.db.models import expressions
from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank
class ProductManager (manager.Manager):
"""
Custom manager to facilitate product query
... | Add 2 methods to search product by keywords. | Add 2 methods to search product by keywords.
| Python | bsd-2-clause | ftkghost/SuperSaver,ftkghost/SuperSaver |
a7dce25964cd740b0d0db86b255ede60c913e73d | chdb.py | chdb.py | import sqlite3
DB_FILENAME = 'citationhunt.sqlite3'
def init_db():
return sqlite3.connect(DB_FILENAME)
def reset_db():
db = init_db()
with db:
db.execute('''
DROP TABLE IF EXISTS categories
''')
db.execute('''
DROP TABLE IF EXISTS articles
''')
... | import sqlite3
DB_FILENAME = 'citationhunt.sqlite3'
def init_db():
return sqlite3.connect(DB_FILENAME)
def reset_db():
db = init_db()
with db:
db.execute('''
DROP TABLE categories
''')
db.execute('''
DROP TABLE articles
''')
db.execute('''
... | Remove IF EXISTS from DROP TABLE when resetting the db. | Remove IF EXISTS from DROP TABLE when resetting the db.
| Python | mit | Stryn/citationhunt,Stryn/citationhunt,jhsoby/citationhunt,Stryn/citationhunt,Stryn/citationhunt,jhsoby/citationhunt,jhsoby/citationhunt,jhsoby/citationhunt |
280e7cf4f7e667ccba796294c58edd5a0f744b70 | geopandas/__init__.py | geopandas/__init__.py | try:
from geopandas.version import version as __version__
except ImportError:
__version__ = '0.1.0'
from geopandas.geoseries import GeoSeries
from geopandas.geodataframe import GeoDataFrame
from geopandas.io.file import read_file
from geopandas.io.sql import read_postgis
# make the interactive namespace easi... | try:
from geopandas.version import version as __version__
except ImportError:
__version__ = '0.2.0.dev-unknown'
from geopandas.geoseries import GeoSeries
from geopandas.geodataframe import GeoDataFrame
from geopandas.io.file import read_file
from geopandas.io.sql import read_postgis
# make the interactive na... | Set default version to 0.2.0.dev-unknown | BLD: Set default version to 0.2.0.dev-unknown
| Python | bsd-3-clause | IamJeffG/geopandas,geopandas/geopandas,perrygeo/geopandas,jorisvandenbossche/geopandas,ozak/geopandas,ozak/geopandas,micahcochran/geopandas,jorisvandenbossche/geopandas,geopandas/geopandas,scw/geopandas,urschrei/geopandas,koldunovn/geopandas,micahcochran/geopandas,jorisvandenbossche/geopandas,kwinkunks/geopandas,jdmcbr... |
d173f5688d2ea466e52e58673d920723847f12a1 | gittip/utils/timer.py | gittip/utils/timer.py | import time
def start():
return {'start_time': time.time()}
def end(start_time):
print("count#requests=1")
response_time = time.time() - start_time
print("measure#response_time={}ms".format(response_time * 1000))
| import time
def start():
return {'start_time': time.time()}
def end(start_time, website):
if website.log_metrics:
print("count#requests=1")
response_time = time.time() - start_time
print("measure#response_time={}ms".format(response_time * 1000))
| Clean up merge of LOG_METRICS from master | Clean up merge of LOG_METRICS from master
| Python | mit | mccolgst/www.gittip.com,gratipay/gratipay.com,studio666/gratipay.com,eXcomm/gratipay.com,mccolgst/www.gittip.com,eXcomm/gratipay.com,studio666/gratipay.com,studio666/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,eXcomm/gratipay.com,gratipay/gratipay.com,eXcomm/gratipay.com,mccolgst/www.gittip.com,mccolgst/ww... |
b75570a5897383c6fa9834c1f5f1b2aaf8d236cd | wakatime/projects/projectmap.py | wakatime/projects/projectmap.py | # -*- coding: utf-8 -*-
"""
wakatime.projects.projectmap
~~~~~~~~~~~~~~~~~~~~~~~~~~
Information from ~/.waka-projectmap mapping folders (relative to home folder)
to project names
:author: 3onyc
:license: BSD, see LICENSE for more details.
"""
import logging
import os
from ..packages import s... | # -*- coding: utf-8 -*-
"""
wakatime.projects.projectmap
~~~~~~~~~~~~~~~~~~~~~~~~~~
Information from ~/.waka-projectmap mapping folders (relative to home folder)
to project names
:author: 3onyc
:license: BSD, see LICENSE for more details.
"""
import logging
import os
from functools import par... | Fix ProjectMap always returning true if it has a config section | Fix ProjectMap always returning true if it has a config section
| Python | bsd-3-clause | gandarez/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,queenp/wakatime,wakatime/wakatime,prashanthr/wakatime,wangjun/wakatime,wakatime/wakatime,Djabbz/wakatime,wakatime/wakatime,wakatime/wakatime,Djabbz/wakatime,wakatime/wakatime,gandarez/wakatime,queenp/wakatime,wakatime/wakatime,Djabbz/wakatime,prash... |
73ee4af73309c4d20cf7b28ac82a5e1037a5d65a | poetry_core/packages/project_package.py | poetry_core/packages/project_package.py | from poetry_core.semver import VersionRange
from poetry_core.semver import parse_constraint
from poetry_core.version.markers import parse_marker
from .package import Package
from .utils.utils import create_nested_marker
class ProjectPackage(Package):
def __init__(self, name, version, pretty_version=None):
... | from poetry_core.semver import VersionRange
from poetry_core.semver import parse_constraint
from poetry_core.version.markers import parse_marker
from .package import Package
from .utils.utils import create_nested_marker
class ProjectPackage(Package):
def __init__(self, name, version, pretty_version=None):
... | Add the to_dependency method to ProjectPackage | Add the to_dependency method to ProjectPackage
| Python | mit | python-poetry/poetry-core,python-poetry/poetry-core,python-poetry/poetry-core |
3043a2400e46648f01921aad265816d2bcf18211 | test/test_conjunctive_graph.py | test/test_conjunctive_graph.py | from rdflib.graph import ConjunctiveGraph
from rdflib.term import Identifier, URIRef
from rdflib.parser import StringInputSource
from os import path
DATA = u"""
<http://example.org/record/1> a <http://xmlns.com/foaf/0.1/Document> .
"""
PUBLIC_ID = u"http://example.org/record/1"
def test_graph_ids():
def check(... | from rdflib.graph import ConjunctiveGraph
from rdflib.term import Identifier, URIRef
from rdflib.parser import StringInputSource
from os import path
DATA = u"""
<http://example.org/record/1> a <http://xmlns.com/foaf/0.1/Document> .
"""
PUBLIC_ID = u"http://example.org/record/1"
def test_graph_ids():
def check(... | Fix py3-incompatible test code that causes PY3 test failure. | Fix py3-incompatible test code that causes PY3 test failure.
| Python | bsd-3-clause | avorio/rdflib,yingerj/rdflib,avorio/rdflib,RDFLib/rdflib,ssssam/rdflib,marma/rdflib,marma/rdflib,avorio/rdflib,armandobs14/rdflib,RDFLib/rdflib,dbs/rdflib,armandobs14/rdflib,yingerj/rdflib,yingerj/rdflib,ssssam/rdflib,RDFLib/rdflib,dbs/rdflib,yingerj/rdflib,marma/rdflib,dbs/rdflib,armandobs14/rdflib,RDFLib/rdflib,avori... |
9be02e353335db2c5923be0959595aeb35e9311c | testing/test_direct_wrapper.py | testing/test_direct_wrapper.py | import os
from cffitsio._cfitsio import ffi, lib
def test_create_file(tmpdir):
filename = str(tmpdir.join('test.fits'))
f = ffi.new('fitsfile **')
status = ffi.new('int *')
lib.fits_create_file(f, filename, status)
assert status[0] == 0
assert os.path.isfile(filename)
def test_open_file(tes... | import os
from cffitsio._cfitsio import ffi, lib
def test_create_file(tmpdir):
filename = str(tmpdir.join('test.fits'))
f = ffi.new('fitsfile **')
status = ffi.new('int *')
lib.fits_create_file(f, filename, status)
assert status[0] == 0
assert os.path.isfile(filename)
def test_open_file(tes... | Add test for file closing | Add test for file closing
| Python | mit | mindriot101/fitsio-cffi |
a77b62ccadf578b8e352e4fdae8e4efe5060f938 | workshopvenues/venues/models.py | workshopvenues/venues/models.py | from django.db import models
class Venues(models.Model):
name = models.CharField(max_length=30)
website = models.CharField(max_length=50)
address = models.CharField(max_length=200)
town = models.CharField(max_length=30)
postcode = models.CharField(max_length=10)
| from django.db import models
class Venues(models.Model):
name = models.CharField(max_length=30)
website = models.CharField(max_length=50)
address = models.CharField(max_length=200)
town = models.CharField(max_length=30)
postcode = models.CharField(max_length=10)
def __unicode__(self):
... | Add descriptive name to Venues model | Add descriptive name to Venues model
| Python | bsd-3-clause | andreagrandi/workshopvenues |
bdecfc7f31b13718957e598947eb52b2e7988fd6 | numba/postpasses.py | numba/postpasses.py | # -*- coding: utf-8 -*-
"""
Postpasses over the LLVM IR.
The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc
"""
from __future__ import print_function, division, absolute_import
from numba.support.math_support import math_support
default_postpasses = {}
def register_default(name):
def dec... | # -*- coding: utf-8 -*-
"""
Postpasses over the LLVM IR.
The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc
"""
from __future__ import print_function, division, absolute_import
from numba.support.math_support import math_support
default_postpasses = {}
def register_default(name):
def dec... | Add pointer from math library to external numba.math.* functions | Add pointer from math library to external numba.math.* functions
| Python | bsd-2-clause | pombredanne/numba,GaZ3ll3/numba,ssarangi/numba,numba/numba,ssarangi/numba,ssarangi/numba,stefanseefeld/numba,cpcloud/numba,pitrou/numba,cpcloud/numba,pitrou/numba,pitrou/numba,stuartarchibald/numba,jriehl/numba,gdementen/numba,stefanseefeld/numba,numba/numba,IntelLabs/numba,stuartarchibald/numba,IntelLabs/numba,GaZ3ll3... |
25d36ba71aed866de468363ea6004eabbd8f22da | publish/tools/crontool.py | publish/tools/crontool.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
This tool iterates through all of the scrapers in the datasets module
and creates a cron-task for each one.
'''
import os
import pkgutil
import random
import sys
from publish.lib.manifest import get_scraper_names
def get_launch_binary():
this_location = sys.argv[... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
This tool iterates through all of the scrapers in the datasets module
and creates a cron-task for each one.
'''
import os
import pkgutil
import random
import sys
from publish.lib.manifest import get_scraper_names
def get_launch_binary():
this_location = sys.argv[... | Make sure we use the absolute path in generating cron lines | Make sure we use the absolute path in generating cron lines
| Python | mit | nhsengland/publish-o-matic |
ad17e166cac2863692af96bccf0317d97e102e24 | tests/integration/test_juju.py | tests/integration/test_juju.py | import pytest
from juju.controller import Controller
from juju.juju import Juju
from .. import base
@base.bootstrapped
@pytest.mark.asyncio
async def test_get_controllers(event_loop):
async with base.CleanController() as controller:
j = Juju()
controllers = j.get_controllers()
assert isi... | import pytest
from juju.controller import Controller
from juju.juju import Juju
from .. import base
@base.bootstrapped
@pytest.mark.asyncio
async def test_get_controllers(event_loop):
async with base.CleanController() as controller:
j = Juju()
controllers = j.get_controllers()
assert isi... | Make sure to disconnect the extra connection before finishing the test | Make sure to disconnect the extra connection before finishing the test
| Python | apache-2.0 | juju/python-libjuju,juju/python-libjuju |
497116839db95bf734ed66e5cf87e986141ad50d | txircd/modules/rfc/cmd_info.py | txircd/modules/rfc/cmd_info.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd import version
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from zope.interface import implements
class InfoCommand(ModuleData, Command):
implements(IPlugin, IModuleData, ICommand)
name... | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd import version
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from zope.interface import implements
class InfoCommand(ModuleData, Command):
implements(IPlugin, IModuleData, ICommand)
name... | Add self to contributors list | Add self to contributors list
| Python | bsd-3-clause | Heufneutje/txircd,ElementalAlchemist/txircd |
6292cd114d8d982162fa8076605cce569acd8fc5 | panphon/xsampa.py | panphon/xsampa.py | from __future__ import absolute_import, print_function, unicode_literals
import regex as re
import unicodecsv as csv
import os.path
import pkg_resources
class XSampa(object):
def __init__(self, delimiter=' '):
self.delimiter = delimiter
self.xs_regex, self.xs2ipa = self.read_xsampa_table()
d... | from __future__ import absolute_import, print_function, unicode_literals
import regex as re
import unicodecsv as csv
import os.path
import pkg_resources
class XSampa(object):
def __init__(self, delimiter=' '):
self.delimiter = delimiter
self.xs_regex, self.xs2ipa = self.read_xsampa_table()
d... | Convert map objects to lists | Convert map objects to lists
| Python | mit | dmort27/panphon,dmort27/panphon |
2809f97696791f34e659dc9fc3c9e29c802082d2 | django_evolution/tests/test_evolution_models.py | django_evolution/tests/test_evolution_models.py | from datetime import datetime
from django.test.testcases import TestCase
from django_evolution.models import Version
class VersionManagerTests(TestCase):
"""Unit tests for django_evolution.models.VersionManager."""
def test_current_version_with_dup_timestamps(self):
"""Testing Version.current_versi... | from datetime import datetime
from django.test.testcases import TestCase
from django_evolution.models import Version
class VersionManagerTests(TestCase):
"""Unit tests for django_evolution.models.VersionManager."""
def test_current_version_with_dup_timestamps(self):
"""Testing Version.current_versi... | Fix unit tests for Version.objects.get_current(). | Fix unit tests for Version.objects.get_current().
The unit tests assumed that no Version objects were present, but this
wasn't always the case. This clears them before the test runs.
| Python | bsd-3-clause | beanbaginc/django-evolution |
e3959d1dcf33dff0d69ba36abf2ff37f2dcf8d60 | spiff/membership/tests.py | spiff/membership/tests.py | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
from django.contrib.auth.models import User, Group
import models
class MemberTest(TestCase):
def tes... | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
from django.contrib.auth.models import User, Group
import models
from spiff.payment.models import Payme... | Remove broken and old test | Remove broken and old test
| Python | agpl-3.0 | SYNHAK/spiff,SYNHAK/spiff,SYNHAK/spiff |
2430e87f2c44c46863ed47c8b3a55c4010820260 | frontend/modloop/__init__.py | frontend/modloop/__init__.py | from flask import render_template, request, send_from_directory
import saliweb.frontend
from saliweb.frontend import get_completed_job
from . import submit
app = saliweb.frontend.make_application(__name__, "##CONFIG##")
@app.route('/')
def index():
return render_template('index.html')
@app.route('/contact')
d... | from flask import render_template, request, send_from_directory
import saliweb.frontend
from saliweb.frontend import get_completed_job, Parameter, FileParameter
from . import submit
parameters=[Parameter("name", "Job name", optional=True),
FileParameter("pdb", "PDB file to be refined"),
Parame... | Add basic REST API support | Add basic REST API support
| Python | lgpl-2.1 | salilab/modloop,salilab/modloop |
27e7f47f2506be8607f29961dd629a8038c7e67f | ecmd-core/pyecmd/test_api.py | ecmd-core/pyecmd/test_api.py | from pyecmd import *
with Ecmd(fapi2="ver1"):
t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0]
data = t.getScom(0x1234)
t.putScom(0x1234, 0x10100000)
# These interfaces may not be defined for some plugins
# Pull them to prevent compile issues
#core_id, thread_id = t.targetToSequenceId... | from pyecmd import *
extensions = {}
if hasattr(ecmd, "fapi2InitExtension"):
extensions["fapi2"] = "ver1"
with Ecmd(**extensions):
t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0]
data = t.getScom(0x1234)
t.putScom(0x1234, 0x10100000)
# These interfaces may not be defined for some plugins... | Make fapi2 test conditional on fapi2 being built into ecmd | pyecmd: Make fapi2 test conditional on fapi2 being built into ecmd
| Python | apache-2.0 | open-power/eCMD,open-power/eCMD,open-power/eCMD,open-power/eCMD,open-power/eCMD |
aca410866dfdd9ced23df14fb3e51fb02f910e85 | IPython/html/widgets/__init__.py | IPython/html/widgets/__init__.py | from .widget import Widget, DOMWidget, CallbackDispatcher, register
from .widget_bool import Checkbox, ToggleButton
from .widget_button import Button
from .widget_box import Box, Popup, FlexBox, HBox, VBox
from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider
from .widget_... | from .widget import Widget, DOMWidget, CallbackDispatcher, register
from .widget_bool import Checkbox, ToggleButton
from .widget_button import Button
from .widget_box import Box, Popup, FlexBox, HBox, VBox
from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider
from .widget_... | Make the widget error message shorter and more understandable. | Make the widget error message shorter and more understandable.
| Python | bsd-3-clause | jupyter-widgets/ipywidgets,cornhundred/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidg... |
69d18539fb4f394ca45d1116a521084c83ea21b5 | icekit_events/migrations/0012_auto_20160706_1606.py | icekit_events/migrations/0012_auto_20160706_1606.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('icekit_events', '0011_event_show_in_calendar'),
]
operations = [
migrations.AlterModelTable(
name='event',
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('icekit_events', '0011_event_show_in_calendar'),
]
operations = [
migrations.AlterModelTable(
name='event',
... | Make migration reverse no-op a valid SQL query | Make migration reverse no-op a valid SQL query
When using a PostgreSQL database with Django 1.7 empty reverse query
statements in DB migrations cause an error, so we replace the empty
no-op statement with a valid query that still does nothing so the
reverse migration will work in this case.
This problem doesn't seem ... | Python | mit | ic-labs/icekit-events,ic-labs/icekit-events,ic-labs/icekit-events,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit |
033c16034074d4fd6eab054a9c97888d23668316 | tests/test_empty_polygons.py | tests/test_empty_polygons.py | from shapely.geometry import MultiPolygon, Polygon
def test_empty_polygon():
"""No constructor arg makes an empty polygon geometry."""
assert Polygon().is_empty
def test_empty_multipolygon():
"""No constructor arg makes an empty multipolygon geometry."""
assert MultiPolygon().is_empty
def test_mul... | from shapely.geometry import MultiPolygon, Point, Polygon
def test_empty_polygon():
"""No constructor arg makes an empty polygon geometry."""
assert Polygon().is_empty
def test_empty_multipolygon():
"""No constructor arg makes an empty multipolygon geometry."""
assert MultiPolygon().is_empty
def t... | Add test of an empty and non empty polygon | Add test of an empty and non empty polygon
| Python | bsd-3-clause | jdmcbr/Shapely,jdmcbr/Shapely |
c28b0f5ea02652f7899e34d9a8779e2ff47d8020 | tests/test_internal_links.py | tests/test_internal_links.py | # -*- encoding: utf-8
from http_crawler import crawl
def test_no_links_are_broken(baseurl):
"""
Check that all internal links point to working pages.
"""
responses = []
for rsp in crawl(baseurl, follow_external_links=False):
responses.append(rsp)
failed_responses = [rsp for rsp in re... | # -*- encoding: utf-8
from http_crawler import crawl
import pytest
_responses = []
@pytest.fixture
def responses(baseurl):
if not _responses:
for rsp in crawl(baseurl, follow_external_links=False):
_responses.append(rsp)
return _responses
def test_no_links_are_broken(responses):
""... | Move the responses to a cacheable fixture | Move the responses to a cacheable fixture
| Python | mit | alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net |
178006e4a299ca67e758184be50ae94333f09821 | test_settings.py | test_settings.py | from malaria24.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'malaria24',
}
}
ONAPIE_ACCESS_TOKEN = 'foo'
VUMI_GO_ACCOUNT_KEY = 'VUMI_GO_ACCOUNT_KEY'
VUMI_GO_API_TOKEN = 'VUMI_GO_API_TOKEN'
VUMI_GO_CONVERSATION_KEY = 'VUMI_GO_CONVERSATION_KEY'
| from malaria24.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'malaria24',
}
}
ONAPIE_ACCESS_TOKEN = 'foo'
ONA_API_URL = 'https://odk.ona.io'
VUMI_GO_ACCOUNT_KEY = 'VUMI_GO_ACCOUNT_KEY'
VUMI_GO_API_TOKEN = 'VUMI_GO_API_TOKEN'
VUMI_GO_CONVERSATION_K... | Add url setting to test settings | Add url setting to test settings
| Python | bsd-2-clause | praekelt/malaria24-django,praekelt/malaria24-django,praekelt/malaria24-django,praekelt/malaria24-django |
0d81ecbe4126585d8af089e76fc3bb98b5dc2098 | eforge/__init__.py | eforge/__init__.py | # -*- coding: utf-8 -*-
# EForge project management system, Copyright © 2010, Element43
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWA... | # -*- coding: utf-8 -*-
# EForge project management system, Copyright © 2010, Element43
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWA... | Add beta version tagging for 0.5 beta 1 | Add beta version tagging for 0.5 beta 1
| Python | isc | oshepherd/eforge,oshepherd/eforge,oshepherd/eforge |
690dbc1ce63a6dc107a34d5b0315d316ef334e49 | vdi/context_preprocessors.py | vdi/context_preprocessors.py | from django.conf import settings
def context_preprocessor(request):
d = {
'vdi_media_dir': settings.VDI_MEDIA_PREFIX,
}
if request.user.is_authenticated():
d['institution'] = request.user.username.split('++')[0]
return d
| from django.conf import settings
def context_preprocessor(request):
d = {
'vdi_media_dir': settings.VDI_MEDIA_PREFIX,
}
if request.user.is_authenticated():
institution = request.user.username.split('++')
if len(institution) == 1:
institution = 'local'
else:
... | Edit to populate the local themeing. | Edit to populate the local themeing.
| Python | apache-2.0 | bmbouter/Opus,ehelms/Opus,ehelms/Opus,bmbouter/Opus,ehelms/Opus,bmbouter/Opus |
3ed33d83b1ade56b41166b50713b1087d6559b70 | hello-world/hello_world_test.py | hello-world/hello_world_test.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
import hello_world
class BobTests(unittest.TestCase):
def test_hello_without_name(self):
self.assertEqual(
'Hello, World!',
hello_world.hello()
)
def test_hello_with_name(self):
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
import hello_world
class HelloWorldTests(unittest.TestCase):
def test_hello_without_name(self):
self.assertEqual(
'Hello, World!',
hello_world.hello()
)
def test_hello_with_sample_name(s... | Fix Hello World test class name & update test | Fix Hello World test class name & update test
Fix test class name to reflect exercise name.
Update tests to reflect Hello World metadata in x-common.
| Python | mit | pheanex/xpython,de2Zotjes/xpython,jmluy/xpython,rootulp/xpython,rootulp/xpython,oalbe/xpython,exercism/xpython,mweb/python,outkaj/xpython,exercism/xpython,mweb/python,jmluy/xpython,behrtam/xpython,N-Parsons/exercism-python,pheanex/xpython,smalley/python,orozcoadrian/xpython,N-Parsons/exercism-python,orozcoadrian/xpytho... |
c2726978a1272b13af2ffdfb10b4238985768317 | tests/test_db.py | tests/test_db.py | import pytest
from handy.db import do_sql, fetch_all, fetch_row, fetch_col, fetch_val
def pytestmark(func):
pytest.mark.django_db(func)
pytest.mark.usefixtures('test_table')(func)
@pytest.fixture(scope='module')
def test_table():
do_sql('''
begin;
create table test (
id int ... | import pytest
from handy.db import do_sql, fetch_all, fetch_row, fetch_col, fetch_val
def pytestmark(func):
pytest.mark.django_db(func)
pytest.mark.usefixtures('test_table')(func)
@pytest.fixture(scope='module')
def test_table():
# NOTE: We wrap that into transaction because in other case django will g... | Add NOTE regarding transaction to db tests setup | Add NOTE regarding transaction to db tests setup
| Python | bsd-3-clause | leliel12/handy,leliel12/handy |
221a94c38ac0ad0c6d08f02b587c259423b96311 | wagtailaltgenerator/utils.py | wagtailaltgenerator/utils.py | import os
import requests
from django.utils.translation import get_language
from wagtailaltgenerator.translation_providers import get_current_provider
from wagtailaltgenerator.providers import DescriptionResult
def get_image_data(image_url):
'''
Load external image and return byte data
'''
image_dat... | import os
import requests
from django.utils.translation import get_language
from wagtailaltgenerator.translation_providers import get_current_provider
from wagtailaltgenerator.providers import DescriptionResult
def get_image_data(image_url):
'''
Load external image and return byte data
'''
image_dat... | Fix issue where lang was not parsed properly | Fix issue where lang was not parsed properly
| Python | mit | marteinn/wagtail-alt-generator,marteinn/wagtail-alt-generator,marteinn/wagtail-alt-generator |
b2c527e912260253be459c9ad3dd6139be21a75d | faucet/valve_manager_base.py | faucet/valve_manager_base.py | """Valve Manager base class"""
# pylint: disable=R0201
# pylint: disable=W0613
class ValveManagerBase: # pylint: disable=too-few-public-methods
"""Base class for ValveManager objects.
Expected to control the installation of flows into datapath tables.
Ideally each datapath table should be controlled by 1... | """Valve Manager base class"""
# pylint: disable=R0201
# pylint: disable=W0613
class ValveManagerBase: # pylint: disable=too-few-public-methods
"""Base class for ValveManager objects.
Expected to control the installation of flows into datapath tables.
Ideally each datapath table should be controlled by 1... | Update manager API for update. | Update manager API for update.
| Python | apache-2.0 | REANNZ/faucet,faucetsdn/faucet,mwutzke/faucet,anarkiwi/faucet,shivarammysore/faucet,trungdtbk/faucet,REANNZ/faucet,gizmoguy/faucet,anarkiwi/faucet,mwutzke/faucet,trungdtbk/faucet,shivarammysore/faucet,faucetsdn/faucet,gizmoguy/faucet |
82ba42bf269e7897129976c07d28b4bc0f23df69 | shopify/mixins.py | shopify/mixins.py | import shopify.resources
class Countable(object):
@classmethod
def count(cls, _options=None, **kwargs):
if _options is None:
_options = kwargs
return int(cls.get("count", **_options))
class Metafields(object):
def metafields(self):
return shopify.resources.Metafield.... | import shopify.resources
class Countable(object):
@classmethod
def count(cls, _options=None, **kwargs):
if _options is None:
_options = kwargs
return int(cls.get("count", **_options))
class Metafields(object):
def metafields(self, _options=None, **kwargs):
if _option... | Enable keyword arguments when requesting metafields | Enable keyword arguments when requesting metafields
| Python | mit | Shopify/shopify_python_api |
3395943d4c202709c2f1f110e19a2aa0dc741e63 | UM/Qt/Bindings/DirectoryListModel.py | UM/Qt/Bindings/DirectoryListModel.py | from UM.Qt.ListModel import ListModel
from UM.Application import Application
from PyQt5.QtCore import Qt, pyqtProperty, pyqtSignal, QUrl
import os
import os.path
class DirectoryListModel(ListModel):
NameRole = Qt.UserRole + 1
UrlRole = Qt.UserRole + 2
def __init__(self):
super().__init__()
... | from UM.Qt.ListModel import ListModel
from UM.Application import Application
from PyQt5.QtCore import Qt, pyqtProperty, pyqtSignal, QUrl
import os
import os.path
import platform
class DirectoryListModel(ListModel):
NameRole = Qt.UserRole + 1
UrlRole = Qt.UserRole + 2
def __init__(self):
super().... | Fix directory listing on windows. | Fix directory listing on windows.
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium |
5429534fc79237fb175aa8f7888565dd14092d9d | yetibridge/bridge/console.py | yetibridge/bridge/console.py | import threading
from . import BaseBridge
from .. import BaseEvent
class ConsoleBridge(BaseBridge):
def __init__(self, config):
BaseBridge.__init__(self, config)
self._thread = threading.Thread(target=self.run, daemon=True)
self.users = {}
def on_register(self):
self._thread.s... | import threading
from . import BaseBridge
from .. import BaseEvent
class ConsoleBridge(BaseBridge):
def __init__(self, config):
BaseBridge.__init__(self, config)
self._thread = threading.Thread(target=self.run, daemon=True)
self.users = {}
def on_register(self):
self._thread.s... | Add name method to ConsoleBridge | Add name method to ConsoleBridge
Add method to name an id, be it a user, bridge, or the manager itself.
| Python | mit | Hornwitser/YetiBridge |
ab8fc00a7dc6618d23e06f06e125da5ee69b2dba | event_registration_hr_contract/__openerp__.py | event_registration_hr_contract/__openerp__.py | # -*- coding: utf-8 -*-
# (c) 2016 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Event Registration Hr Contract",
'version': '8.0.1.1.0',
'license': "AGPL-3",
'author': "AvanzOSC",
'website': "http://www.avanzosc.es",
'contributors': ... | # -*- coding: utf-8 -*-
# (c) 2016 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Event Registration Hr Contract",
'version': '8.0.1.1.0',
'license': "AGPL-3",
'author': "AvanzOSC",
'website': "http://www.avanzosc.es",
'contributors': ... | Remove the dependence with the module hr_contract_stage. | [IMP] event_registration_hr_contract: Remove the dependence with the module hr_contract_stage.
| Python | agpl-3.0 | avanzosc/event-wip |
44a7c59d798d9a20d4d54b9cce7e56b8f88595cc | ch14/caesar.py | ch14/caesar.py | # Caesar Cipher
MAX_KEY_SIZE = 26
def getMode():
while True:
print('Do you wish to encrypt or decrypt a message?')
mode = input().lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d".')
... | # Caesar Cipher
MAX_KEY_SIZE = 26
def getMode():
while True:
print('Do you wish to encrypt or decrypt a message?')
mode = input().lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d".')
... | Modify the code in the getKey() function so that it gracefully ignores non-integer input. | Modify the code in the getKey() function so that it gracefully ignores non-integer input.
| Python | bsd-2-clause | aclogreco/InventGamesWP |
014b4905784f50fd13111ca8528fade9be4bd767 | skimage/feature/__init__.py | skimage/feature/__init__.py | from ._hog import hog
from ._greycomatrix import greycomatrix, greycoprops
from .hog import hog
from .texture import greycomatrix, greycoprops, local_binary_pattern
from .peak import peak_local_max
from ._harris import harris
from .template import match_template
| from ._hog import hog
from .texture import greycomatrix, greycoprops, local_binary_pattern
from .peak import peak_local_max
from ._harris import harris
from .template import match_template
| Fix import bug due to rebase | Fix import bug due to rebase
| Python | bsd-3-clause | blink1073/scikit-image,robintw/scikit-image,emon10005/scikit-image,newville/scikit-image,michaelaye/scikit-image,GaZ3ll3/scikit-image,chintak/scikit-image,chriscrosscutler/scikit-image,warmspringwinds/scikit-image,vighneshbirodkar/scikit-image,robintw/scikit-image,dpshelio/scikit-image,Hiyorimi/scikit-image,youprofit/s... |
72865598fbe8658ade68f67da4e2a244a13713b9 | analysis/plot-marker-trajectories.py | analysis/plot-marker-trajectories.py | import climate
import lmj.plot
import numpy as np
import source
import plots
@climate.annotate(
root='load experiment data from this directory',
pattern='plot data from files matching this pattern',
markers='plot traces of these markers',
)
def main(root, pattern='*5/*block00/*circuit00.csv.gz', markers=... | import climate
import lmj.plot
import numpy as np
import source
import plots
@climate.annotate(
root='load experiment data from this directory',
pattern=('plot data from files matching this pattern', 'option'),
markers=('plot traces of these markers', 'option'),
spline=('interpolate data with a splin... | Add command-line flags for spline order and accuracy. | Add command-line flags for spline order and accuracy.
| Python | mit | lmjohns3/cube-experiment,lmjohns3/cube-experiment,lmjohns3/cube-experiment |
d38599b88a4537d92b562010ca4b7e56580f2e35 | graphene_django_extras/directives/__init__.py | graphene_django_extras/directives/__init__.py | # -*- coding: utf-8 -*-
from graphql.type.directives import specified_directives as default_directives
from .list import ShuffleGraphQLDirective, SampleGraphQLDirective
from .numbers import FloorGraphQLDirective, CeilGraphQLDirective
from .string import (
DefaultGraphQLDirective,
Base64GraphQLDirective,
Nu... | # -*- coding: utf-8 -*-
from graphql.type.directives import specified_directives as default_directives
from .date import *
from .list import *
from .numbers import *
from .string import *
all_directives = (
# date
DateGraphQLDirective,
# list
ShuffleGraphQLDirective,
SampleGraphQLDirective,
# ... | Reorder imports and use Black code style. Updated version to 0.4.4 | Reorder imports and use Black code style.
Updated version to 0.4.4
| Python | mit | eamigo86/graphene-django-extras |
baf41667c9c86484319c58e56187792ed571b6db | certificates/generator.py | certificates/generator.py | from os import system
from os import unlink
from os.path import dirname
from os.path import realpath
def generate_certificate_for(event_id, certificate_name, name_of_certificate_holder):
resources_path = dirname(realpath(__file__)) + '/resources/'
static_files_path = dirname(dirname(realpa... | from os import system
from os import unlink
from os.path import dirname
from os.path import realpath
def generate_certificate_for(event_id, certificate_name, name_of_certificate_holder):
resources_path = dirname(realpath(__file__)) + '/resources/'
static_files_path = dirname(dirname(realpa... | Fix writing UTF-8 texts to certificate templates | Fix writing UTF-8 texts to certificate templates
The certificate PDF can’t reliably render all variants of UTF-8 text.
We will need to disable non-ASCII input. | Python | mit | codeeu/coding-events,codeeu/coding-events,codeeu/coding-events,codeeu/coding-events,codeeu/coding-events |
5bad3f45bdca436515b416bbcfb45ca53b46ca2a | application/lomadee/data_importer.py | application/lomadee/data_importer.py | from django.conf import settings
from urllib.parse import urljoin, urlencode
class ComputerDataImporter(object):
def __init__(self):
pass
def build_api_url(self, **kwargs):
api_url = urljoin(settings.LOMADEE_API_URL, settings.LOMADEE_APP_TOKEN)
# Specific path to 'Computer' category... | from django.conf import settings
from urllib.parse import urljoin, urlencode
import requests
class ComputerDataImporter(object):
def __init__(self):
pass
def build_api_url(self, **kwargs):
api_url = urljoin(settings.LOMADEE_API_URL, settings.LOMADEE_APP_TOKEN)
# Specific path to 'Co... | Add get_data method to data importer | Add get_data method to data importer
Signed-off-by: Matheus Fernandes <9de26933bf4170c6685be29c190c23bc8c34d55f@gmail.com>
| Python | mit | msfernandes/facebook-chatbot |
b08bff08d69960c9035cefa4e4021d48530c5158 | anemoi/Tests/test_Analytical.py | anemoi/Tests/test_Analytical.py | import unittest
import numpy as np
from anemoi import AnalyticalHelmholtz
class TestMiniZephyr(unittest.TestCase):
def setUp(self):
pass
def test_forwardModelling(self):
nx = 100
nz = 200
systemConfig = {
'dx': 1., # m
'dz': 1., # ... | import unittest
import numpy as np
from anemoi import AnalyticalHelmholtz
class TestAnalyticalHelmholtz(unittest.TestCase):
def setUp(self):
pass
def test_cleanExecution(self):
nx = 100
nz = 200
systemConfig = {
'c': 2500., # m/s
'nx': n... | Rename one test, use default dx and dz, fix naming of test class. | Rename one test, use default dx and dz, fix naming of test class.
| Python | mit | uwoseis/zephyr,uwoseis/anemoi |
e97b5d343ca80ff050fca6d37efffcfe739b42e0 | cloud_maker/py_version.py | cloud_maker/py_version.py | # vim: fileencoding=utf-8
from __future__ import print_function, absolute_import, unicode_literals
import sys
class VersionError (ValueError):
pass
def check_ex ():
major, minor, patch = sys.version_info[0:2]
if major == 3:
if minor < 3 or (minor == 3 and patch < 4):
raise VersionError... | # vim: fileencoding=utf-8
from __future__ import print_function, absolute_import, unicode_literals
import sys
class VersionError (ValueError):
pass
def check_ex ():
v = sys.version_info
if v.major == 3:
if v.minor < 3 or (v.minor == 3 and v.micro < 4):
raise VersionError("Error: this i... | Fix usage of `version_info` on Python 2. | Fix usage of `version_info` on Python 2.
| Python | mit | sapphirecat/cloud-maker,sapphirecat/cloud-maker |
036a5f879ddf6f8c2f1ae3bfea6a58962783f949 | moocng/portal/management/commands/mailtest.py | moocng/portal/management/commands/mailtest.py | # Copyright 2013 Rooter Analysis S.L.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | # Copyright 2013 Rooter Analysis S.L.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | Change subject to every mail to was sent | Change subject to every mail to was sent
| Python | apache-2.0 | OpenMOOC/moocng,GeographicaGS/moocng,GeographicaGS/moocng,GeographicaGS/moocng,OpenMOOC/moocng,GeographicaGS/moocng |
08b4fae4352f68a524d51a7e14767e5b093c4a73 | social_django/migrations/0005_auto_20160727_2333.py | social_django/migrations/0005_auto_20160727_2333.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-07-28 02:33
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
replaces = [
('default', '0005_auto_20160727_2333'),
('social_auth', '0005_auto_20160727_2333')
]
depend... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-07-28 02:33
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
replaces = [
('social_auth', '0005_auto_20160727_2333')
]
dependencies = [
('social_django', '0004_auto_... | Remove replacement of non existing migration | Remove replacement of non existing migration
Fixes #16
| Python | bsd-3-clause | python-social-auth/social-app-django,python-social-auth/social-app-django,python-social-auth/social-app-django |
042c11e298dd76c16ef84b2ee1d96d75de6203d4 | print_traceback.py | print_traceback.py | import sys
import traceback
class CustomException(Exception):
def __init__(self, *args, **kwargs):
super(CustomException, self).__init__(*args, **kwargs)
def custom_function():
raise CustomException('Test to raise custom exception.')
try:
custom_function()
except:
_type, _value, _traceback = sys... | import sys
import traceback
class CustomException(Exception):
def __init__(self, *args, **kwargs):
super(CustomException, self).__init__(*args, **kwargs)
def custom_deep_function():
raise CustomException('Test to raise custom exception.')
def custom_function():
custom_deep_function()
try:
custom_f... | Print stack trace of exception. | Print stack trace of exception.
| Python | mit | iandmyhand/python-utils |
75f7ff7754eee79da9cd0a430a4fa16af21cdd4d | adhocracy4/actions/signals.py | adhocracy4/actions/signals.py | from django.apps import apps
from django.conf import settings
from django.db.models.signals import post_save
from .models import Action
from .verbs import Verbs
def _extract_target(instance):
target = None
if hasattr(instance, 'content_object'):
target = instance.content_object
elif hasattr(insta... | from itertools import chain
from django.apps import apps
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_delete, post_save
from .models import Action
from .verbs import Verbs
SYSTEM_ACTIONABLES = (
('a4phases', 'Phase'),
('... | Delete Actions if the related object is deleted | Delete Actions if the related object is deleted
As we are loosing all the information when the object of an action is
deleted, the action itself may be deleted, too.
| Python | agpl-3.0 | liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4 |
c5cd62969ebee36c99923ad7a5b9e7c527bff6cc | quantecon/__init__.py | quantecon/__init__.py | """
Import the main names to top level.
"""
try:
import numba
except:
raise ImportError("Cannot import numba from current anaconda distribution. Please run `conda install numba` to install the latest version.")
from .compute_fp import compute_fixed_point
from .discrete_rv import DiscreteRV
from .ecdf import ECDF
fr... | """
Import the main names to top level.
"""
try:
import numba
except:
raise ImportError("Cannot import numba from current anaconda distribution. Please run `conda install numba` to install the latest version.")
#-Modules-#
from . import quad
from . import random
#-Objects-#
from .compute_fp import compute_fixed_po... | Update base api to include module and object imports, fix missing import of random subpackage | Update base api to include module and object imports, fix missing import of random subpackage
| Python | bsd-3-clause | QuantEcon/QuantEcon.py,oyamad/QuantEcon.py,oyamad/QuantEcon.py,QuantEcon/QuantEcon.py |
05ecac15aa9b975bd83378daa0560182041bef97 | src/format_go_correspondance.py | src/format_go_correspondance.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import argparse
import re
def format_go_correspondance(args):
go = {}
with open(args.go_correspondance_input, "r") as go_correspondance_input:
for line in go_correspondance_input.readlines():
split_line = line[:-1].split('\... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import argparse
import re
def format_go_correspondance(args):
go = {}
with open(args.go_correspondance_input, "r") as go_correspondance_input:
for line in go_correspondance_input.readlines():
if not line.startswith('GO'):
... | Add test for go correspondance file begin | Add test for go correspondance file begin
| Python | apache-2.0 | ASaiM/group_humann2_uniref_abundances_to_GO,ASaiM/group_humann2_uniref_abundances_to_GO |
52933f030b246615429ac74f7f156b7a33225d7f | opengrid/tests/test_plotting.py | opengrid/tests/test_plotting.py | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 30 02:37:25 2013
@author: Jan
"""
import unittest
class PlotStyleTest(unittest.TestCase):
def test_default(self):
from opengrid.library.plotting import plot_style
plt = plot_style()
class CarpetTest(unittest.TestCase):
def test_default(self):
... | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 30 02:37:25 2013
@author: Jan
"""
import unittest
import pandas as pd
from opengrid.library import plotting
class PlotStyleTest(unittest.TestCase):
def test_default(self):
plt = plotting.plot_style()
class CarpetTest(unittest.TestCase):
def test_defau... | Resolve RuntimeError: Invalid DISPLAY variable - tst | [BLD] Resolve RuntimeError: Invalid DISPLAY variable - tst
| Python | apache-2.0 | opengridcc/opengrid |
33e1c57cd6186820fb95b5d04a1f494710b2ccbe | democracy_club/apps/authorities/management/commands/import_mapit_area_type.py | democracy_club/apps/authorities/management/commands/import_mapit_area_type.py | import time
import requests
from bs4 import BeautifulSoup
from django.core.management.base import BaseCommand
from django.contrib.gis.geos import GEOSGeometry
from django.contrib.gis.geos import Point
from authorities.models import Authority, MapitArea
from authorities import constants
from authorities.helpers impor... | """
DIW
MTW
UTW
"""
import time
import requests
from bs4 import BeautifulSoup
from django.core.management.base import BaseCommand
from django.contrib.gis.geos import GEOSGeometry
from django.contrib.gis.geos import Point
from authorities.models import Authority, MapitArea
from authorities import constants
from auth... | Comment for types of area that need importing | Comment for types of area that need importing
| Python | bsd-3-clause | DemocracyClub/Website,DemocracyClub/Website,DemocracyClub/Website,DemocracyClub/Website |
cc8e643902eb46f9e9d73a4367518e6ab6195308 | kindergarten-garden/kindergarten_garden.py | kindergarten-garden/kindergarten_garden.py | # File: kindergarten_garden.py
# Purpose: Write a program that, given a diagram, can tell you which plants each child in the kindergarten class is responsible for.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Thursday 10th September 2016, 10:51 PM
| # File: kindergarten_garden.py
# Purpose: Write a program that, given a diagram, can tell you which plants each child in the kindergarten class is responsible for.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Thursday 10th September 2016, 10:51 PM
class Garden(object):
plant_... | Add plant names and childs | Add plant names and childs
| Python | mit | amalshehu/exercism-python |
94d3b36e08a546ef470dd0d8dab55a4be3d4265b | examples/get_config.py | examples/get_config.py | import logging
logging.basicConfig()
from jenkinsapi.jenkins import Jenkins
J = Jenkins('http://localhost:8080')
jobName = 'create_fwrgmkbbzk'
config = J[jobName].get_config()
print config
| """
An example of how to use JenkinsAPI to fetch the config XML of a job.
"""
from jenkinsapi.jenkins import Jenkins
J = Jenkins('http://localhost:8080')
jobName = 'create_fwrgmkbbzk'
config = J[jobName].get_config()
print config
| Add a comment to this example | Add a comment to this example
| Python | mit | imsardine/jenkinsapi,domenkozar/jenkinsapi,jduan/jenkinsapi,mistermocha/jenkinsapi,zaro0508/jenkinsapi,salimfadhley/jenkinsapi,zaro0508/jenkinsapi,aerickson/jenkinsapi,imsardine/jenkinsapi,JohnLZeller/jenkinsapi,aerickson/jenkinsapi,jduan/jenkinsapi,zaro0508/jenkinsapi,mistermocha/jenkinsapi,JohnLZeller/jenkinsapi,sali... |
450f082237e5b302988cece5c6eb091a5d8503df | examples/img_server.py | examples/img_server.py | #!/usr/bin/env python
"""
This example implements a server taking a single image when receiving a message from the client.
The image will be fragmented into chunks. The first packet sent contains the number of chunks to expect.
"""
import io
import picamera
import time
from nuts import UDPAuthChannel
def ta... | #!/usr/bin/env python
"""
This example implements a server taking a single image when receiving a message from the client.
The image will be fragmented into chunks. The first packet sent contains the number of chunks to expect.
"""
import io
import picamera
import time
from nuts import UDPAuthChannel
def ta... | Remove python2 print from img server | Remove python2 print from img server
| Python | mit | thusoy/nuts-auth,thusoy/nuts-auth |
8ddab20fd41217fe4ea9b5e267443a4953d2d8f7 | apps/authentication/forms.py | apps/authentication/forms.py | from django import forms
class SignupForm(forms.Form):
def signup(self, request, user):
user.is_active = False
user.save()
| from django import forms
from django.core.mail import send_mail
class SignupForm(forms.Form):
def signup(self, request, user):
user.is_active = False
user.save()
send_mail(
'New user on MyQuotes',
'There is one new user asking for access. ID: {id}, Email: {email}'.... | Add email notification when new user has signed up | Add email notification when new user has signed up
| Python | bsd-3-clause | lucifurtun/myquotes,lucifurtun/myquotes,lucifurtun/myquotes,lucifurtun/myquotes |
3ff5ae10396da6571c54d1aebf7b604c2946bbe4 | _tests/run_tests.py | _tests/run_tests.py | #!/usr/bin/env python
# -*- encoding: utf-8
import pytest
import requests
@pytest.mark.parametrize('path', [
# Check pagination is working correctly
'/page/2/', '/page/3/',
])
def test_pages_appear_correctly(path):
resp = requests.get(f'http://localhost:5757/{path}')
assert resp.status_code == 200
| #!/usr/bin/env python
# -*- encoding: utf-8
import pytest
import requests
@pytest.mark.parametrize('path', [
# Check pagination is working correctly
'/page/2/', '/page/3/',
])
def test_pages_appear_correctly(path):
resp = requests.get(f'http://localhost:5757/{path}')
assert resp.status_code == 200
... | Add tests for year and month archives | Add tests for year and month archives
| Python | mit | alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net |
969344a4ed822eafcfbf7bd9d666ca45bf38168f | mass_mailing_partner/wizard/partner_merge.py | mass_mailing_partner/wizard/partner_merge.py | # Copyright 2020 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import models
class BasePartnerMergeAutomaticWizard(models.TransientModel):
_inherit = "base.partner.merge.automatic.wizard"
def _merge(self, partner_ids, dst_partner=None, extra_check... | # Copyright 2020 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import models
class BasePartnerMergeAutomaticWizard(models.TransientModel):
_inherit = "base.partner.merge.automatic.wizard"
def _merge(self, partner_ids, dst_partner=None, extra_check... | Add sudo() to prevent user without mailing access try to merge contacts | [FIX] mass_mailing_partner: Add sudo() to prevent user without mailing access try to merge contacts
| Python | agpl-3.0 | OCA/social,OCA/social,OCA/social |
7a50f9e69e8b9c57b87eb113e8b6736a94d43866 | satchmo/product/templatetags/satchmo_product.py | satchmo/product/templatetags/satchmo_product.py | from django import template
from django.conf import settings
from django.core import urlresolvers
from django.template import Context, Template
from django.utils.translation import get_language, ugettext_lazy as _
from satchmo.configuration import config_value
from satchmo.product.models import Category
from satchmo.sh... | from django import template
from django.conf import settings
from django.core import urlresolvers
from django.template import Context, Template
from django.utils.translation import get_language, ugettext_lazy as _
from satchmo.configuration import config_value
from satchmo.product.models import Category
from satchmo.sh... | Change the is_producttype template tag to return a boolean rather than a string. | Change the is_producttype template tag to return a boolean rather than a string.
| Python | bsd-3-clause | grengojbo/satchmo,grengojbo/satchmo |
726662d102453f7c7be5fb31499a8c4d5ab34444 | apps/storybase_user/models.py | apps/storybase_user/models.py | from django.contrib.auth.models import User
from django.db import models
from uuidfield.fields import UUIDField
from storybase.fields import ShortTextField
class Organization(models.Model):
""" An organization or a community group that users and stories can be associated with. """
organization_id = UUIDField(a... | from django.contrib.auth.models import User
from django.db import models
from uuidfield.fields import UUIDField
from storybase.fields import ShortTextField
class Organization(models.Model):
""" An organization or a community group that users and stories can be associated with. """
organization_id = UUIDField(a... | Revert "Updated fields for Project model." | Revert "Updated fields for Project model."
This reverts commit f68fc56dd2a7ec59d472806ffc14e993686e1f24.
| Python | mit | denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase |
00e5adf2aa4223e37a191a454300d888af5687f5 | src/pip/__pip-runner__.py | src/pip/__pip-runner__.py | """Execute exactly this copy of pip, within a different environment.
This file is named as it is, to ensure that this module can't be imported via
an import statement.
"""
import importlib.util
import runpy
import sys
import types
from importlib.machinery import ModuleSpec
from os.path import dirname, join
from typin... | """Execute exactly this copy of pip, within a different environment.
This file is named as it is, to ensure that this module can't be imported via
an import statement.
"""
import runpy
import sys
import types
from importlib.machinery import ModuleSpec, PathFinder
from os.path import dirname
from typing import Optiona... | Rework the pip runner to use `PathFinder` | Rework the pip runner to use `PathFinder`
This makes it possible to only "replace" `pip` and have the submodules
get correctly located by the regular importlib machinery. This also
asserts that it was able to locate the module, ensuring that failure to
locate the module results in an exception.
| Python | mit | pypa/pip,sbidoul/pip,pfmoore/pip,pfmoore/pip,pypa/pip,pradyunsg/pip,pradyunsg/pip,sbidoul/pip |
7d722b5ff87ae1306e089e1bf5839632e628b663 | aws/customise-stack-template.py | aws/customise-stack-template.py | from amazonia.classes.sns import SNS
from troposphere import Ref, Join, cloudwatch
from troposphere.sns import Topic, Subscription
def user_registration_topic(emails):
return topic("UserRegistrationReceived", emails)
def topic(topic_title, emails):
topic = Topic(topic_title,
DisplayName=Join("", ... | from amazonia.classes.sns import SNS
from troposphere import Ref, Join, cloudwatch
from troposphere.sns import Topic, Subscription
def user_registration_topic(emails):
return topic("UserRegistrationReceived", emails)
def new_cors_site_request_received_topic(emails):
return topic("NewCorsSiteRequestReceived",... | Add SNS topic for event NewCorsSiteRequestReceived | Add SNS topic for event NewCorsSiteRequestReceived
| Python | bsd-3-clause | GeoscienceAustralia/geodesy-domain-model,GeoscienceAustralia/Geodesy-Web-Services,GeoscienceAustralia/Geodesy-Web-Services,GeoscienceAustralia/Geodesy-Web-Services,GeoscienceAustralia/geodesy-domain-model,GeoscienceAustralia/Geodesy-Web-Services |
d0e634e4472dcd82009801626c8e51d0a16fcae6 | cfp/management/commands/update_talks_and_workshops_from_applications.py | cfp/management/commands/update_talks_and_workshops_from_applications.py | from django.core.management.base import BaseCommand, CommandError
from events.models import Event
class Command(BaseCommand):
help = "Copies talk title and descriptions from the application."
def add_arguments(self, parser):
parser.add_argument('event_id', type=int)
def handle(self, *args, **op... | from django.core.management.base import BaseCommand, CommandError
from events.models import Event
class Command(BaseCommand):
help = "Copies talk title and descriptions from the application."
def add_arguments(self, parser):
parser.add_argument('event_id', type=int)
def handle(self, *args, **op... | Update workshops as well as talks | Update workshops as well as talks
| Python | bsd-3-clause | WebCampZg/conference-web,WebCampZg/conference-web,WebCampZg/conference-web |
2c4524c1f40ef9963caefec4ed258974b80a6db1 | messente/api/sms/__init__.py | messente/api/sms/__init__.py | # -*- coding: utf-8 -*-
# Copyright 2016 Messente Communications OÜ
#
# 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 2016 Messente Communications OÜ
#
# 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 ... | Define public interface in sms module | Define public interface in sms module
| Python | apache-2.0 | messente/messente-python |
456bf650d0c6c487616869986ca29bab4768b0cb | dash2012/fabfile.py | dash2012/fabfile.py | #encoding: utf-8
from fabric.api import run, settings, cd, env
env.use_ssh_config = True
env.ssh_config_path = '~/.ssh/config'
def deploy():
with settings(host_string='dash.daltonmatos.com'):
with cd("/var/mongrel2/apps/djangodash2012.daltonmatos.com"):
with cd("app/djangodash2012/"):
... | #encoding: utf-8
from fabric.api import run, settings, cd, env
env.use_ssh_config = True
env.ssh_config_path = '~/.ssh/config'
def deploy(branch='master'):
with settings(host_string='dash.daltonmatos.com'):
with cd("/var/mongrel2/apps/djangodash2012.daltonmatos.com"):
with cd("app/djangodash2... | Choose which branch will be deployed | Choose which branch will be deployed
| Python | bsd-3-clause | losmiserables/djangodash2012,losmiserables/djangodash2012 |
5b63b724a89c11aa06a8281cf778063c4a8a7096 | Artifactor/views.py | Artifactor/views.py | # -*- coding: utf-8 -*-
# vim: set ts=4
from django.forms import ModelForm
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from Artifactor.models import Artifact
def ... | # -*- coding: utf-8 -*-
# vim: set ts=4
from django.forms import ModelForm
from django.http import Http404, HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from Artifactor.models import Artifact
def index(re... | Return the right URL when a file is posted | Return the right URL when a file is posted
| Python | mit | ivoire/Artifactorial,ivoire/Artifactorial,ivoire/Artifactorial |
5706257685820787b70bfef6798491c34b9b9ad9 | ckanext/romania_theme/plugin.py | ckanext/romania_theme/plugin.py | import ckan.model as model
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
import os
def get_number_of_files():
return model.Session.execute("select count(*) from resource where state = 'active'").first()[0]
def get_number_of_external_links():
return model.Session.execute("select count... | import ckan.model as model
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
import os
def get_number_of_files():
return model.Session.execute("select count(*) from resource where state = 'active'").first()[0]
def get_number_of_external_links():
return model.Session.execute("select count... | Add check for PDF files | Add check for PDF files
| Python | agpl-3.0 | govro/ckanext-romania_theme,govro/ckanext-romania_theme,govro/ckanext-romania_theme,govro/ckanext-romania_theme |
618bf6d4c1fc5e60b7e94d1ad1030bf2cf0de5c2 | src/main/python/alppaca/server_mock/__init__.py | src/main/python/alppaca/server_mock/__init__.py | from __future__ import print_function, absolute_import, unicode_literals, division
from datetime import datetime, timedelta
from textwrap import dedent
from bottle import Bottle
import pytz
""" Super simple IMS mock.
Just listens on localhost:8080 for the appropriate url, returns a test role and
a dummy JSON respon... | """ Super simple IMS mock.
Just listens on localhost:8080 for the appropriate url, returns a test role and
a dummy JSON response.
"""
from __future__ import print_function, absolute_import, unicode_literals, division
from datetime import datetime, timedelta
from textwrap import dedent
from bottle import Bottle
impo... | Move string above the imports so it becomes a docstring | Move string above the imports so it becomes a docstring
| Python | apache-2.0 | ImmobilienScout24/afp-alppaca,ImmobilienScout24/alppaca,ImmobilienScout24/alppaca,ImmobilienScout24/afp-alppaca |
65be9926d1e6d769fcf6d88a6a9788791beef187 | id3lab/__init__.py | id3lab/__init__.py | import IPython
import ts_charting.lab.lab as tslab
import ipycli.standalone as sa
from workbench import sharedx
class ID3Lab(tslab.Lab):
def get_varname(self):
"""
Try to get the variable that this lab is
bound to in the IPython kernel
"""
inst = IPython.InteractiveShell._... | import IPython
import ts_charting.lab.lab as tslab
import ipycli.standalone as sa
from workbench import sharedx
class ID3Lab(tslab.Lab):
_html_obj = None
def __init__(self, draw=False, html_obj=None):
super(ID3Lab, self).__init__(draw=draw)
if html_obj is None:
html_obj = sharedx
... | Make ID3Lab allow attr to be pluggable | ENH: Make ID3Lab allow attr to be pluggable
| Python | apache-2.0 | dalejung/id3lab,dalejung/id3lab |
f0871086222be67ba4add4574cf03d3cb9d39d63 | tests/circular/template/test_interpolatedstr.py | tests/circular/template/test_interpolatedstr.py | from src.circular.template.interpolatedstr import InterpolatedStr
from src.circular.template.context import Context
from tests.utils import TObserver
def test_string_interp():
ctx = Context()
ctx.name = "James"
s = InterpolatedStr("My name is {{ surname }}, {{name}} {{ surname}}.")
s.bind_ctx(ctx)
... | from src.circular.template.interpolatedstr import InterpolatedStr
from src.circular.template.context import Context
from tests.utils import TObserver
def test_string_interp():
ctx = Context()
ctx.name = "James"
s = InterpolatedStr("My name is {{ surname }}, {{name}} {{ surname}}.")
s.bind_ctx(ctx)
... | Add test for run-together interpolated expressions. | Add test for run-together interpolated expressions.
| Python | mit | jonathanverner/circular,jonathanverner/circular,jonathanverner/circular |
7ce48df1dc525b214a5993853d313d7e1ab6050d | cms/templatetags/cms_js_tags.py | cms/templatetags/cms_js_tags.py | # -*- coding: utf-8 -*-
from classytags.core import Tag, Options
from django import template
from django.core.serializers.json import DjangoJSONEncoder
from django.utils import simplejson
from django.utils.text import javascript_quote
register = template.Library()
@register.filter
def js(value):
return simplejson... | # -*- coding: utf-8 -*-
from distutils.version import LooseVersion
from classytags.core import Tag, Options
import django
from django import template
from django.core.serializers.json import DjangoJSONEncoder
from django.utils.text import javascript_quote
DJANGO_1_4 = LooseVersion(django.get_version()) < LooseVersion... | Use json module instead of django.utils.simplejson for Django 1.5 | Use json module instead of django.utils.simplejson for Django 1.5
| Python | bsd-3-clause | wyg3958/django-cms,cyberintruder/django-cms,josjevv/django-cms,jproffitt/django-cms,webu/django-cms,mkoistinen/django-cms,czpython/django-cms,ojii/django-cms,memnonila/django-cms,Jaccorot/django-cms,11craft/django-cms,mkoistinen/django-cms,isotoma/django-cms,jsma/django-cms,bittner/django-cms,jproffitt/django-cms,intgr... |
793c477f4e365d47d9245f43e9d49fccce303d2a | vcs/models.py | vcs/models.py | from django.db import models
class Activity(models.Model):
group = models.CharField(max_length=4)
grouptype = models.TextField()
groupdetail = models.TextField()
details = models.TextField()
disabled = models.BooleanField()
time = models.DecimalField(decimal_places=2, max_digits=10)
unique_... | from django.db import models
class Activity(models.Model):
group = models.CharField(max_length=4)
grouptype = models.TextField()
groupdetail = models.TextField()
details = models.TextField()
disabled = models.BooleanField()
time = models.DecimalField(decimal_places=2, max_digits=10)
unique_... | Use a OneToMany field for the activity joiner. | Use a OneToMany field for the activity joiner.
| Python | bsd-3-clause | AeroNotix/django-timetracker,AeroNotix/django-timetracker,AeroNotix/django-timetracker |
0b7d69869009888c26d1fdf3dee8a4f858fa70a3 | diary/forms.py | diary/forms.py | from django import forms
import cube.diary.models
class DiaryIdeaForm(forms.ModelForm):
class Meta(object):
model = cube.diary.models.DiaryIdea
class EventForm(forms.ModelForm):
class Meta(object):
model = cube.diary.models.Event
class ShowingForm(forms.ModelForm):
class Meta(object):
... | from django import forms
import cube.diary.models
class DiaryIdeaForm(forms.ModelForm):
class Meta(object):
model = cube.diary.models.DiaryIdea
class EventForm(forms.ModelForm):
class Meta(object):
model = cube.diary.models.Event
# Ensure soft wrapping is set for textareas:
wid... | Set wrapping to soft on textareas | Set wrapping to soft on textareas
| Python | agpl-3.0 | BenMotz/cubetoolkit,BenMotz/cubetoolkit,BenMotz/cubetoolkit,BenMotz/cubetoolkit |
6018abc4a1c2dfa139bb104ae6db69fef5994ff6 | plugins/chrome_extensions.py | plugins/chrome_extensions.py | ###################################################################################################
#
# chrome_extensions.py
# Adds the name and description of each Chrome extension found in a URLItem to the Interpretation field
#
# Plugin Author: Ryan Benson (ryan@obsidianforensics.com)
#
###########################... | ###################################################################################################
#
# chrome_extensions.py
# Adds the name and description of each Chrome extension found in a URLItem to the Interpretation field
#
# Plugin Author: Ryan Benson (ryan@obsidianforensics.com)
#
###########################... | Add try/except to catch if no extensions are parsed. | Add try/except to catch if no extensions are parsed.
| Python | apache-2.0 | obsidianforensics/hindsight,obsidianforensics/hindsight |
1b23ca7327d5414233222fdb26c1c1e88d0137a6 | takeyourmeds/telephony/views.py | takeyourmeds/telephony/views.py | import os
import json
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from . import actions
def info(request, uuid):
"""
Return the Twillio ML that we generated when the user
called /call
"""
data = open(os.path.join("/tmp", uuid + ".xml")).read()
re... | import os
from django.http import HttpResponse
def info(request, uuid):
"""
Return the Twillio ML that we generated when the user called /call
"""
with open(os.path.join('/tmp', '%s.xml' % uuid)) as f:
data = f.read()
return HttpResponse(data, content_type='text/xml')
| Tidy imports and opening the tmpfile | Tidy imports and opening the tmpfile
| Python | mit | takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web |
b7b0724b7f663a8a0d0e5c46d66f42726d700f45 | djng/router.py | djng/router.py | from django.conf.urls.defaults import patterns
from django.core import urlresolvers
class Router(object):
"""
Convenient wrapper around Django's urlresolvers, allowing them to be used
from normal application code.
from django.http import HttpResponse
from django_openid.request_factory import Requ... | from django.conf.urls.defaults import patterns
from django.core import urlresolvers
class Router(object):
"""
Convenient wrapper around Django's urlresolvers, allowing them to be used
from normal application code.
from django.http import HttpResponse
from django_openid.request_factory import Requ... | Add back 1.0.X compatibility for Router URL resolution. | Add back 1.0.X compatibility for Router URL resolution.
Signed-off-by: Simon Willison <088e16a1019277b15d58faf0541e11910eb756f6@simonwillison.net> | Python | bsd-2-clause | simonw/djng |
97e048d0a743808ab0ec62b39306940b59dd3c8a | test.py | test.py | import bluePoV
import pygame
x,y = (480,64)
MAC = "00:00:00:00:00:00"
pygame.init()
pygame.display.set_mode((x,y))
s = pygame.display.get_surface()
driver = bluePoV.Driver([x,y],1)
#driver.connect(MAC)
s.fill([0,255,0])
driver.blit(s)
pygame.display.flip()
input("Press any key... ")
| import bluePoV
import pygame
x,y = (480,64)
MAC = "00:00:00:00:00:00"
pygame.init()
pygame.display.set_mode((x,y))
s = pygame.display.get_surface()
driver = bluePoV.Driver([x,y],depth=1,asServer=True)
#driver.connect(MAC)
s.fill([0,255,0])
driver.blit(s)
pygame.display.flip()
input("Press any key... ")
| Throw an error if bluetooth is not supported on the py3 installation | Throw an error if bluetooth is not supported on the py3 installation
| Python | mit | ABorgna/BluePoV-PC,ABorgna/BluePoV-PC,ABorgna/BluePoV-PC |
88b198ff1de67d675b81c736eceeb7a2308851db | json2csv_business.py | json2csv_business.py | import json
def main():
# print the header of output csv file
print 'business_id,city,latitude,longitude'
# for each entry in input json file print one csv row
for line in open("data/yelp_academic_dataset_business.json"):
input_json = json.loads(line)
business_id = input_json['busines... | import json
def main():
# print the header of output csv file
print 'business_id,city,latitude,longitude'
# for each entry in input json file print one csv row
for line in open("data/yelp_academic_dataset_business.json"):
input_json = json.loads(line)
business_id = input_json['busines... | Replace commas in names of cities with spaces | Replace commas in names of cities with spaces | Python | mit | aysent/yelp-photo-explorer |
89485bf26ebb7cf4570549cda42543061d6b4fd7 | docker/transport/basehttpadapter.py | docker/transport/basehttpadapter.py | import requests.adapters
class BaseHTTPAdapter(requests.adapters.HTTPAdapter):
def close(self):
self.pools.clear()
| import requests.adapters
class BaseHTTPAdapter(requests.adapters.HTTPAdapter):
def close(self):
super(BaseHTTPAdapter, self).close()
if hasattr(self, 'pools'):
self.pools.clear()
| Fix BaseHTTPAdapter for the SSL case | Fix BaseHTTPAdapter for the SSL case
Signed-off-by: Ulysses Souza <a0ff1337c6a0e43e9559f5f67fc3acb852912071@docker.com>
| Python | apache-2.0 | docker/docker-py,funkyfuture/docker-py,funkyfuture/docker-py,vdemeester/docker-py,vdemeester/docker-py,docker/docker-py |
b4d86431806cc9ce3019aa65db2a3b22c2bd4ac3 | flask_skeleton_api/views/general.py | flask_skeleton_api/views/general.py | from flask import request, Blueprint, Response
from flask import current_app
import json
# This is the blueprint object that gets registered into the app in blueprints.py.
general = Blueprint('general', __name__)
@general.route("/health")
def check_status():
return Response(response=json.dumps({
"app": "... | from flask import request, Blueprint, Response
from flask import current_app
import json
# This is the blueprint object that gets registered into the app in blueprints.py.
general = Blueprint('general', __name__)
@general.route("/health")
def check_status():
return Response(response=json.dumps({
"app": "... | Improve list of headers returned with health route in order to remove /r/n | Improve list of headers returned with health route in order to remove /r/n
| Python | mit | matthew-shaw/thing-api |
e1df9380be8891c813a8c87e8d8175393171ac17 | rest_framework_sso/querysets.py | rest_framework_sso/querysets.py | # coding: utf-8
from __future__ import absolute_import, unicode_literals
from django.db.models import QuerySet, Q
from django.utils import timezone
import logging
logger = logging.getLogger(__name__)
class SessionTokenQuerySet(QuerySet):
def active(self):
return self.filter(Q(revoked_at__isnull=True) |... | # coding: utf-8
from __future__ import absolute_import, unicode_literals
from django.db.models import QuerySet, Q
from django.utils import timezone
import logging
logger = logging.getLogger(__name__)
class SessionTokenQuerySet(QuerySet):
def active(self):
return self.filter(Q(revoked_at__isnull=True) |... | Stop using django's internal `_create_object_from_params` | Stop using django's internal `_create_object_from_params`
| Python | mit | namespace-ee/django-rest-framework-sso,namespace-ee/django-rest-framework-sso |
ff4b34cda7c0b5bc516d9f9e3689818000301336 | tests/test_planner.py | tests/test_planner.py | import cutplanner
import unittest
class TestPlanner(unittest.TestCase):
def setUp(self):
sizes = [80, 120]
needed = [10, 25, 75]
loss = 0.25
self.planner = cutplanner.Planner(sizes, needed, loss)
def test_get_largest(self):
largest = self.planner.get_largest_stock()
... | import cutplanner
import unittest
class TestPlanner(unittest.TestCase):
def setUp(self):
sizes = [80, 120]
needed = [10, 25, 75]
loss = 0.25
self.planner = cutplanner.Planner(sizes, needed, loss)
def test_largest_stock(self):
largest = self.planner.largest_stock
... | Update test for largest stock | Update test for largest stock
| Python | mit | alanc10n/py-cutplanner |
a1679be616d6d0d6ee807a708690549ec1798d04 | python/array_manipulation.py | python/array_manipulation.py | #!/bin/python3
import math
import os
import random
import re
import sys
def arrayManipulation(n, queries):
array = [0] * n
for a, b, k in queries:
# Start is a - 1 because this is a one indexed array
for i in range(a - 1, b):
array[i] += k
print(array)
return max(a... | #!/bin/python3
import math
import os
import random
import re
import sys
def arrayManipulation(n, queries):
# An array used to capture the difference of an element
# compared to the previous element.
# Therefore the value of diffs[n] after all array manipulations is
# the cumulative sum of values from... | Improve runtime by using an array of diffs | Improve runtime by using an array of diffs
| Python | mit | rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank |
34a3bf209c1bb09e2057eb4dd91ef426e3107c11 | monitor_temperature.py | monitor_temperature.py | import time
import serial
import matplotlib.pyplot as plt
import csv
import os
import brewkettle
reload(brewkettle)
filename = time.strftime("%Y-%m-%d %H:%M") + ".csv"
path = os.path.join("data", filename)
f = open(path, "w")
csv_writer = csv.writer(f)
kettle = brewkettle.BrewKettle()
kettle.turn_pump_on()
start = t... | import time
import serial
import matplotlib.pyplot as plt
import csv
import os
import brewkettle
reload(brewkettle)
filename = time.strftime("%Y-%m-%d %H:%M") + ".csv"
path = os.path.join("data", filename)
f = open(path, "w")
csv_writer = csv.writer(f)
csv_writer.writerow(["Time [s]", "Temperature [C]"])
kettle = bre... | Monitor temperature script as used for heating measurement | Monitor temperature script as used for heating measurement
| Python | mit | beercanlah/ardumashtun,beercanlah/ardumashtun |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.