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 |
|---|---|---|---|---|---|---|---|---|---|
601b3d7db3bedd090291f1a52f22f6daee9987fd | imapbox.py | imapbox.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
# import mailboxresource
from mailboxresource import MailboxClient
import argparse
def main():
argparser = argparse.ArgumentParser(description="Dump a IMAP folder into .eml files")
argparser.add_argument('-s', dest='host', help="IMAP host, like imap.gmail.com", req... | #!/usr/bin/env python
#-*- coding:utf-8 -*-
# import mailboxresource
from mailboxresource import MailboxClient
import argparse
import ConfigParser, os
def load_configuration(args):
config = ConfigParser.ConfigParser(allow_no_value=True)
config.read(['/etc/imapbox/config.cfg', os.path.expanduser('~/.config/im... | Load multiple accounts using a config file | Load multiple accounts using a config file
| Python | mit | polo2ro/imapbox |
f4f529aca5a37a19c3445ec7fc572ece08ba4293 | examples/hosts-production.py | examples/hosts-production.py | #!/usr/bin/env python3
# (c) 2014 Brainly.com, Pawel Rozlach <pawel.rozlach@brainly.com>
# This script is intended to only find "where it is" and invoke the inventory
# tool with correct inventory path basing on it's name.
import os.path as op
import sys
# Configuration:
backend_domain = 'example.com'
ipaddress_key... | #!/usr/bin/env python3
# Copyright (c) 2014 Pawel Rozlach, Brainly.com sp. z o.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 re... | Add missing preamble for wrapper script | Add missing preamble for wrapper script
Change-Id: I26d002ca739544bc3d431a6cdb6b441bd33deb5a
| Python | apache-2.0 | brainly/inventory_tool,vespian/inventory_tool |
b856207fe42d480975618f5749ef9febc84f0363 | geolocation_helper/models.py | geolocation_helper/models.py | from django.contrib.gis.db import models as geomodels
from django.contrib.gis.geos.point import Point
from geopy import geocoders
class GeoLocatedModel(geomodels.Model):
geom = geomodels.PointField(null=True, blank=True)
objects = geomodels.GeoManager()
def get_location_as_string(self):
... | from django.contrib.gis.db import models as geomodels
from django.contrib.gis.geos.point import Point
from geopy import geocoders
class GeoLocatedModel(geomodels.Model):
geom = geomodels.PointField(null=True, blank=True)
objects = geomodels.GeoManager()
def get_location_as_string(self):
... | Add is_geolocated property for admin purpuse | Add is_geolocated property for admin purpuse
| Python | bsd-2-clause | atiberghien/django-geolocation-helper,atiberghien/django-geolocation-helper |
7bace98978e0058489b4872d7af300d91fe7f55d | createAdminOnce.py | createAdminOnce.py | #!/usr/bin/env python
import django
django.setup()
import sys,os
from django.contrib.auth.models import User
from django.core.management import call_command
admin_username = os.getenv('WEBLATE_ADMIN_NAME', 'admin')
try:
user = User.objects.get(username=admin_username)
except:
print 'Creating Admin...'
User.ob... | #!/usr/bin/env python
import django
django.setup()
import sys,os
from django.contrib.auth.models import User
from django.core.management import call_command
admin_username = os.getenv('WEBLATE_ADMIN_NAME', 'admin')
try:
user = User.objects.get(username=admin_username)
except:
print 'Creating Admin...'
User.ob... | Clarify admin user creation message | Clarify admin user creation message
| Python | mit | beevelop/docker-weblate,beevelop/docker-weblate |
ed05dbf4dc231ea659b19310e6065d4781bd18bc | code/tests/test_smoothing.py | code/tests/test_smoothing.py | """
Tests functions in smoothing.py
Run with:
nosetests test_smoothing.py
"""
# Test method .smooth()
smooth1, smooth2 = subtest_runtest1.smooth(0), subtest_runtest1.smooth(1, 5)
smooth3 = subtest_runtest1.smooth(2, 0.25)
assert [smooth1.max(), smooth1.shape, smooth1.sum()] == [0, (3, 3, 3), 0]
assert [smooth2.ma... | """
==================Test file for smoothing.py======================
Test convolution module, hrf function and convolve function
Run with:
nosetests nosetests code/tests/test_smoothing.py
"""
from __future__ import absolute_import, division, print_function
from nose.tools import assert_equal
from numpy.testing... | Add seperate test function for smoothing.py | Add seperate test function for smoothing.py
| Python | bsd-3-clause | berkeley-stat159/project-delta |
e9171e8d77b457e2c96fca37c89d68c518bec5f7 | src/urllib3/util/util.py | src/urllib3/util/util.py | from types import TracebackType
from typing import NoReturn, Optional, Type, Union
def to_bytes(
x: Union[str, bytes], encoding: Optional[str] = None, errors: Optional[str] = None
) -> bytes:
if isinstance(x, bytes):
return x
elif not isinstance(x, str):
raise TypeError(f"not expecting typ... | from types import TracebackType
from typing import NoReturn, Optional, Type, Union
def to_bytes(
x: Union[str, bytes], encoding: Optional[str] = None, errors: Optional[str] = None
) -> bytes:
if isinstance(x, bytes):
return x
elif not isinstance(x, str):
raise TypeError(f"not expecting typ... | Bring coverage back to 100% | Bring coverage back to 100%
All calls to reraise() are in branches where value is truthy, so we
can't reach that code. | Python | mit | sigmavirus24/urllib3,sigmavirus24/urllib3,urllib3/urllib3,urllib3/urllib3 |
80e67ffa99cc911219b316b172d7c74e1ede5c50 | camera_selection/scripts/camera_selection.py | camera_selection/scripts/camera_selection.py | #!/usr/bin/env python
import rospy
import Adafruit_BBIO.GPIO as GPIO
from vortex_msgs.msg import CameraFeedSelection
GPIO_PIN_MAP = rospy.get_param('/camera/pin_map')
class CameraSelection(object):
def __init__(self):
rospy.init_node('camera_selection')
self.cam_select_sub = rospy.Subscriber('came... | #!/usr/bin/env python
import rospy
import Adafruit_BBIO.GPIO as GPIO
from vortex_msgs.msg import CameraFeedSelection
PIN_MAP_FEED0 = rospy.get_param('/camera/pin_map_feed0')
PIN_MAP_FEED1 = rospy.get_param('/camera/pin_map_feed1')
PIN_MAP_FEED2 = rospy.get_param('/camera/pin_map_feed2')
PIN_MAP_LIST = [PIN_MAP_FEED0,P... | Add callback, set camera feed selection pins based on msg | Add callback, set camera feed selection pins based on msg
| Python | mit | vortexntnu/rov-control,vortexntnu/rov-control,vortexntnu/rov-control |
f9572834538d40f5ae58e2f611fed7bf22af6311 | templatemailer/mailer.py | templatemailer/mailer.py | import logging
from django.core import mail
from .tasks import task_email_user
logger = logging.getLogger(__name__)
def email_user(user, template, context, attachments=None, delete_attachments_after_send=False, send_to=None,
language_code=None):
'''
Send email to user
:param user: User ... | import logging
from django.core import mail
from .tasks import task_email_user
logger = logging.getLogger(__name__)
def send_email(user, template, context, attachments=None, delete_attachments_after_send=False,
language_code=None):
'''
Send email to user
:param user: User instance or re... | Rename email_user method to send_email and fix parameters | Rename email_user method to send_email and fix parameters
| Python | mit | tuomasjaanu/django-templatemailer |
4b34053ce422e9be15e0ac386a591f8052a778b1 | 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 the app string version of foreign keying. It prevents a circular import. | Use the app string version of foreign keying. It prevents a circular import.
| Python | bsd-3-clause | AeroNotix/django-timetracker,AeroNotix/django-timetracker,AeroNotix/django-timetracker |
eef628750711b8bb4b08eb5f913b731d76541ab1 | shop_catalog/filters.py | shop_catalog/filters.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.admin import SimpleListFilter
from django.utils.translation import ugettext_lazy as _
from shop_catalog.models import Product
class ProductParentListFilter(SimpleListFilter):
title = _('Parent')
parameter_name = 'parent'
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db.models import Q
from django.contrib.admin import SimpleListFilter
from django.utils.translation import ugettext_lazy as _
from shop_catalog.models import Product
class ProductParentListFilter(SimpleListFilter):
title = _('Parent')
... | Modify parent filter to return variants and self | Modify parent filter to return variants and self
| Python | bsd-3-clause | dinoperovic/django-shop-catalog,dinoperovic/django-shop-catalog |
ae201ae3c8b3f25f96bea55f9a69c3612a74c7cf | inboxen/tests/settings.py | inboxen/tests/settings.py | from __future__ import absolute_import
import os
os.environ['INBOX_TESTING'] = '1'
from settings import *
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.dummy.DummyCache"
}
}
db = os.environ.get('DB')
SECRET_KEY = "This is a test, you don't need secrets"
if db == "sqlite":
DATAB... | from __future__ import absolute_import
import os
os.environ['INBOX_TESTING'] = '1'
from settings import *
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache"
}
}
db = os.environ.get('DB')
SECRET_KEY = "This is a test, you don't need secrets"
if db == "sqlite":
DAT... | Use local memory as cache so ratelimit tests don't fail | Use local memory as cache so ratelimit tests don't fail
| Python | agpl-3.0 | Inboxen/Inboxen,Inboxen/infrastructure,Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen |
4d95f634dd7f856fa4fbaf4a20bda58c01fa58b4 | tests/test_epubcheck.py | tests/test_epubcheck.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import epubcheck
from epubcheck import samples
from epubcheck.cli import main
def test_valid():
assert epubcheck.validate(samples.EPUB3_VALID)
def test_invalid():
assert not epubcheck.validate(samples.EPUB3_INVALID)
def test_main_valid(capsys... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
import pytest
import tablib
import epubcheck
from epubcheck import samples
from epubcheck.cli import main
def test_valid():
assert epubcheck.validate(samples.EPUB3_VALID)
def test_invalid():
assert not epubcheck.validate(samples.EP... | Add tests for CSV and XLS reporting | Add tests for CSV and XLS reporting
CSV export currently fails due to epubcheck passing the delimiting
character as bytes although Tablib expects it to be of type str.
The issue will not be fixed as Python 2 has reached end of life [1].
[1] https://github.com/jazzband/tablib/issues/369
| Python | bsd-2-clause | titusz/epubcheck |
e16a292d027f07c1f425229bdb8b74e0d2c66e1f | aws_roleshell.py | aws_roleshell.py | import argparse
from awscli.customizations.commands import BasicCommand
import os
def awscli_initialize(event_hooks):
event_hooks.register('building-command-table.main', inject_commands)
def inject_commands(command_table, session, **kwargs):
command_table['roleshell'] = RoleShell(session)
def get_exec_args... | import argparse
import os
import shlex
import textwrap
from awscli.customizations.commands import BasicCommand
def awscli_initialize(event_hooks):
event_hooks.register('building-command-table.main', inject_commands)
def inject_commands(command_table, session, **kwargs):
command_table['roleshell'] = RoleShe... | Make it possible to eval() output instead of execing another shell. | Make it possible to eval() output instead of execing another shell.
| Python | mit | hashbrowncipher/aws-roleshell |
7a8112249de859a5ef73fe07eb6029aeb1266f35 | tob-api/tob_api/urls.py | tob-api/tob_api/urls.py | """
Definition of urls for tob_api.
"""
from django.conf.urls import include, url
from django.views.generic import RedirectView
from . import views
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = [
url(r"^$", RedirectView.as_view(url="ap... | """
Definition of urls for tob_api.
"""
from django.conf.urls import include, url
from django.views.generic import RedirectView
from . import views
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = [
url(r"^$", RedirectView.as_view(url="ap... | Remove commented-out reference to v1 | Remove commented-out reference to v1
Signed-off-by: Nicholas Rempel <b7f0f2181f2dc324d159332b253a82a715a40706@gmail.com>
| Python | apache-2.0 | swcurran/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,swcurran/TheOrgBook |
8b80b8b82400bd78d72158471b5030309075310c | rdd/api.py | rdd/api.py | # -*- coding: utf-8 -*-
"""Python implementation of the Readability Shortener API"""
import requests
try:
import simplejson as json
except ImportError:
import json
class Readability(object):
def __init__(self, url=None, verbose=None):
self.url = url or 'https://readability.com/api/shortener/v1'... | # -*- coding: utf-8 -*-
"""Python implementation of the Readability Shortener API"""
import requests
try:
import simplejson as json
except ImportError:
import json
class Readability(object):
def __init__(self, url=None, verbose=None):
self.url = url or 'https://readability.com/api/shortener/v1'... | Print HTTP content in verbose mode | Print HTTP content in verbose mode
| Python | mit | mlafeldt/rdd.py,mlafeldt/rdd.py,mlafeldt/rdd.py |
eb2699b6050534045b95e5ea78cb0ea68de474ed | website/members/apps.py | website/members/apps.py | from django.apps import AppConfig
class MembersConfig(AppConfig):
name = 'members'
verbose_name = 'UTN Member Management'
| from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class MembersConfig(AppConfig):
name = 'members'
verbose_name = _('UTN Member Management')
| Make members verbose name translatable | :speech_balloon: Make members verbose name translatable
| Python | agpl-3.0 | Dekker1/moore,UTNkar/moore,Dekker1/moore,Dekker1/moore,UTNkar/moore,UTNkar/moore,UTNkar/moore,Dekker1/moore |
b545ebcd2b604bf293bfbbb1af5a9ab2ba6965c7 | wayback3/wayback3.py | wayback3/wayback3.py | """
Simple Python 3-safe package for accessing Wayback Machine archives
via its JSON API
"""
import datetime
import requests
FORMAT_STRING = "%Y%m%d%H%M%S" # Looks like "20130919044612"
AVAILABILITY_URL = "http://archive.org/wayback/available?url=%s"
def availability(url):
response = requests.get(AVAILABILITY_... | """
Simple Python 3-safe package for accessing Wayback Machine archives
via its JSON API
"""
import datetime
import requests
FORMAT_STRING = "%Y%m%d%H%M%S" # Looks like "20130919044612"
AVAILABILITY_URL = "http://archive.org/wayback/available?url=%s"
WAYBACK_URL_ROOT = "http://web.archive.org"
def availability(url... | Add a constant for WB root URL | Add a constant for WB root URL
| Python | agpl-3.0 | OpenSSR/openssr-parser,OpenSSR/openssr-parser |
cb7b51414a034d50e44fb30c6528b878aa9c64ee | web_ui/opensesame.py | web_ui/opensesame.py | # Enter the password of the email address you intend to send emails from
password = "" | # Enter the password of the email address you intend to send emails from
email_address = ""
email_password = ""
# Enter the login information for the EPNM API Account
API_username = ""
API_password = ""
| Add email and API template | Add email and API template | Python | apache-2.0 | cisco-gve/epnm_alarm_report,cisco-gve/epnm_alarm_report,cisco-gve/epnm_alarm_report,cisco-gve/epnm_alarm_report |
ce8dc3daa6a4af3c5ed743fb2b5c4470bff7647b | test_knot.py | test_knot.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import knot
class TestContainer(unittest.TestCase):
def test_wrapper_looks_like_service(self):
c = knot.Container()
@c.service('service')
def service(container):
"""Docstring."""
pass
self.asse... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import knot
class TestContainer(unittest.TestCase):
def test_wrapper_looks_like_service(self):
c = knot.Container()
@c.service('service')
def service(container):
"""Docstring."""
pass
self.asse... | Add test for default values. | Add test for default values.
| Python | mit | jaapverloop/knot |
05fa3c4c6ab1d7619281399bb5f1db89e55c6fa8 | einops/__init__.py | einops/__init__.py | __author__ = 'Alex Rogozhnikov'
__version__ = '0.4.1'
class EinopsError(RuntimeError):
""" Runtime error thrown by einops """
pass
__all__ = ['rearrange', 'reduce', 'repeat', 'parse_shape', 'asnumpy', 'EinopsError']
from .einops import rearrange, reduce, repeat, parse_shape, asnumpy
| __author__ = 'Alex Rogozhnikov'
__version__ = '0.4.1'
class EinopsError(RuntimeError):
""" Runtime error thrown by einops """
pass
__all__ = ['rearrange', 'reduce', 'repeat', 'einsum',
'parse_shape', 'asnumpy', 'EinopsError']
from .einops import rearrange, reduce, repeat, einsum, parse_shape, as... | Include einsum in main library | Include einsum in main library
| Python | mit | arogozhnikov/einops |
948dc7e7e6d54e4f4e41288ab014cc2e0aa53e98 | scraper.py | scraper.py | """
Interface for web scraping
"""
import os
import sys
from selenium import webdriver
def scrape():
browser = webdriver.Chrome('/home/lowercase/Desktop/scheduler/chromedriver')
if __name__ == "__main__":
scrape()
| """
Interface for web scraping
"""
import os
import sys
import getpass
from selenium import webdriver
def scrape():
browser = webdriver.Chrome('/home/lowercase/Desktop/scheduler/chromedriver')
browser.get('https://my.unt.edu/psp/papd01/EMPLOYEE/EMPL/h/?tab=NTPA_GUEST')
euid = input('What is your EUI... | Load sign in page and collect password. | Load sign in page and collect password.
| Python | mit | undercase/scheduler |
fc87264fec2b13afb04fb89bfc7b2d4bbe2debdf | src/arc_utilities/ros_helpers.py | src/arc_utilities/ros_helpers.py | #! /usr/bin/env python
import rospy
from threading import Lock
class Listener:
def __init__(self, topic_name, topic_type, lock=None):
"""
Listener is a wrapper around a subscriber where the callback simply records the latest msg.
Parameters:
topic_name (str): name of topic to... | #! /usr/bin/env python
import rospy
from threading import Lock
class Listener:
def __init__(self, topic_name, topic_type):
"""
Listener is a wrapper around a subscriber where the callback simply records the latest msg.
Listener does not consume the message
(for consuming beh... | Remove optional lock input (I can't see when it would be useful) Document when Listener should be used | Remove optional lock input (I can't see when it would be useful)
Document when Listener should be used
| Python | bsd-2-clause | WPI-ARC/arc_utilities,UM-ARM-Lab/arc_utilities,UM-ARM-Lab/arc_utilities,WPI-ARC/arc_utilities,UM-ARM-Lab/arc_utilities,WPI-ARC/arc_utilities |
cc3f363c1fefb758302b82e7d0ddff69d55a8261 | recognition/scrobbleTrack.py | recognition/scrobbleTrack.py | import os, sys, json, pylast, calendar
from datetime import datetime
resultJson = json.loads(sys.stdin.read())
# exit immediately if recognition failed
if resultJson["status"]["msg"] != "Success":
print "Recognition failed."
sys.exit(2)
# load Last.fm auth details into environment variables
apiKey = os.environ["LAS... | import os, sys, json, pylast, calendar
from datetime import datetime
resultJson = json.loads(sys.stdin.read())
# exit immediately if recognition failed
if resultJson["status"]["msg"] != "Success":
print "Recognition failed."
sys.exit(2)
# load Last.fm auth details into environment variables
apiKey = os.environ["LAS... | Check for existing Last.fm creds before scrobbling | Check for existing Last.fm creds before scrobbling
| Python | mit | jeffstephens/pi-resto,jeffstephens/pi-resto |
4c9e5df1bd52b0bad6fcfb2ac599999a00c8f413 | __init__.py | __init__.py | """distutils
The main package for the Python Module Distribution Utilities. Normally
used from a setup script as
from distutils.core import setup
setup (...)
"""
# This module should be kept compatible with Python 2.1.
__revision__ = "$Id$"
import sys
__version__ = "%d.%d.%d" % sys.version_info[:3]
del sys... | """distutils
The main package for the Python Module Distribution Utilities. Normally
used from a setup script as
from distutils.core import setup
setup (...)
"""
# This module should be kept compatible with Python 2.1.
__revision__ = "$Id$"
# Distutils version
#
# Please coordinate with Marc-Andre Lemburg ... | Revert to having static version numbers again. | Revert to having static version numbers again.
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools |
e6210531dac1d7efd5fd4d343dcac74a0b74515e | request_profiler/settings.py | request_profiler/settings.py | # -*- coding: utf-8 -*-
# models definitions for request_profiler
from django.conf import settings
# cache key used to store enabled rulesets.
RULESET_CACHE_KEY = getattr(settings, 'REQUEST_PROFILER_RULESET_CACHE_KEY', "request_profiler__rulesets") # noqa
# how long to cache them for - defaults to 10s
RULESET_CACHE_T... | # -*- coding: utf-8 -*-
# models definitions for request_profiler
from django.conf import settings
# cache key used to store enabled rulesets.
RULESET_CACHE_KEY = getattr(settings, 'REQUEST_PROFILER_RULESET_CACHE_KEY', "request_profiler__rulesets") # noqa
# how long to cache them for - defaults to 10s
RULESET_CACHE_T... | Update GLOBAL_EXCLUDE_FUNC default to exclude admins | Update GLOBAL_EXCLUDE_FUNC default to exclude admins
| Python | mit | yunojuno/django-request-profiler,yunojuno/django-request-profiler,sigshen/django-request-profiler,sigshen/django-request-profiler |
8e202175767660bd90c4a894953d2553eec1a1d3 | pythonx/completers/common/__init__.py | pythonx/completers/common/__init__.py | # -*- coding: utf-8 -*-
import completor
import itertools
import re
from completor.compat import text_type
from .filename import Filename # noqa
from .buffer import Buffer # noqa
from .omni import Omni # noqa
try:
from UltiSnips import UltiSnips_Manager # noqa
from .ultisnips import Ultisnips # noqa
ex... | # -*- coding: utf-8 -*-
import completor
import itertools
import re
from completor.compat import text_type
from .filename import Filename # noqa
from .buffer import Buffer # noqa
from .omni import Omni # noqa
try:
from UltiSnips import UltiSnips_Manager # noqa
from .ultisnips import Ultisnips # noqa
ex... | Make it possible to extend common completions | Make it possible to extend common completions
| Python | mit | maralla/completor.vim,maralla/completor.vim |
536bed6c3ff0a819075a04e14296518f1368cc74 | rest_framework_json_api/exceptions.py | rest_framework_json_api/exceptions.py | from django.utils import encoding
from django.utils.translation import ugettext_lazy as _
from rest_framework import status
from rest_framework.exceptions import APIException
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework_json_api.utils import format_value
def excepti... | from django.utils import encoding
from django.utils.translation import ugettext_lazy as _
from rest_framework import status
from rest_framework.exceptions import APIException
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework_json_api.utils import format_value
def excepti... | Modify exception_handler for a string error like AuthenticationError | Modify exception_handler for a string error like AuthenticationError
| Python | bsd-2-clause | leo-naeka/django-rest-framework-json-api,Instawork/django-rest-framework-json-api,pombredanne/django-rest-framework-json-api,grapo/django-rest-framework-json-api,hnakamur/django-rest-framework-json-api,leo-naeka/rest_framework_ember,django-json-api/django-rest-framework-json-api,abdulhaq-e/django-rest-framework-json-ap... |
3ad37c4acfb1d34978941cea2663cb31f1460503 | spotify.py | spotify.py | from willie import web
from willie import module
import time
import json
import urllib
@module.rule('.*(play.spotify.com\/track\/)([\w-]+).*')
def spotify(bot, trigger, found_match=None):
match = found_match or trigger
resp = web.get('https://api.spotify.com/v1/tracks/%s' % match.group(2))
result = json... | from willie import web
from willie import module
import time
import json
import re
regex = re.compile('(play.spotify.com\/track\/)([\w-]+)')
def setup(bot):
if not bot.memory.contains('url_callbacks'):
bot.memory['url_callbacks'] = tools.WillieMemory()
bot.memory['url_callbacks'][regex] = spotify
def... | Add callback to url_callbacks so url module doesn't query it | Add callback to url_callbacks so url module doesn't query it
| Python | mit | Metastruct/hal1320 |
ff4204659b158827070fbb4bdf9bfc1f263e8b33 | fanstatic/registry.py | fanstatic/registry.py | import pkg_resources
ENTRY_POINT = 'fanstatic.libraries'
class LibraryRegistry(dict):
"""A dictionary-like registry of libraries.
This is a dictionary that mains libraries. A value is
a :py:class:`Library` instance, and a key is its
library ``name``.
Normally there is only a single global Librar... | import pkg_resources
ENTRY_POINT = 'fanstatic.libraries'
class LibraryRegistry(dict):
"""A dictionary-like registry of libraries.
This is a dictionary that mains libraries. A value is
a :py:class:`Library` instance, and a key is its
library ``name``.
Normally there is only a single global Librar... | Remove some code that wasn't in use anymore. | Remove some code that wasn't in use anymore.
| Python | bsd-3-clause | fanstatic/fanstatic,fanstatic/fanstatic |
45cfd59f5bc8e91a88e54fda83f868f7bb3c4884 | examples/wsgi_app.py | examples/wsgi_app.py | import guv
guv.monkey_patch()
import json
import bottle
import guv.wsgi
import logger
logger.configure()
app = bottle.Bottle()
@app.route('/')
def index():
data = json.dumps({'status': True})
return data
if __name__ == '__main__':
server_sock = guv.listen(('0.0.0.0', 8001))
guv.wsgi.serve(serve... | import guv
guv.monkey_patch()
import guv.wsgi
import logger
logger.configure()
def app(environ, start_response):
status = '200 OK'
output = [b'Hello World!']
content_length = str(len(b''.join(output)))
response_headers = [('Content-type', 'text/plain'),
('Content-Length', co... | Use bare WSGI application for testing and benchmarking | Use bare WSGI application for testing and benchmarking
| Python | mit | veegee/guv,veegee/guv |
3f747610f080879774720aa1efe38f40364ea151 | raco/myrial/type_tests.py | raco/myrial/type_tests.py | """Various tests of type safety."""
import unittest
from raco.fakedb import FakeDatabase
from raco.scheme import Scheme
from raco.myrial.myrial_test import MyrialTestCase
from collections import Counter
class TypeTests(MyrialTestCase):
schema = Scheme(
[("clong", "LONG_TYPE"),
("cint", "INT_TYPE... | """Various tests of type safety."""
import unittest
from raco.fakedb import FakeDatabase
from raco.scheme import Scheme
from raco.myrial.myrial_test import MyrialTestCase
from raco.expression import TypeSafetyViolation
from collections import Counter
class TypeTests(MyrialTestCase):
schema = Scheme(
[("c... | Test of invalid equality test | Test of invalid equality test
| Python | bsd-3-clause | uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco |
2048045b9b77d8cab88c0cab8e90cf72cb88b2a4 | station.py | station.py | """Creates the station class"""
class Station:
"""
Each train station is an instance of the Station class.
Methods:
__init__: creates a new stations
total_station_pop: calculates total station population
"""
def __init__(self):
self.capacity = capacity
self.escalators = es... | """Creates the station class"""
class Station:
"""
Each train station is an instance of the Station class.
Methods:
__init__: creates a new stations
total_station_pop: calculates total station population
"""
def __init__(self):
self.capacity = eval(input("Enter the max capacity of... | Add input parameters and test function | Add input parameters and test function
Added input parameters at time of instantiation.
Ref #23 | Python | mit | ForestPride/rail-problem |
0bcbd9656723726f1098899d61140a3f1a11c7ea | scripts/1d-load-images.py | scripts/1d-load-images.py | #!/usr/bin/python
import sys
sys.path.insert(0, "/usr/local/opencv-2.4.11/lib/python2.7/site-packages/")
import argparse
import commands
import cv2
import fnmatch
import os.path
sys.path.append('../lib')
import ProjectMgr
# for all the images in the project image_dir, load the image meta data
# this script produce... | #!/usr/bin/python
import sys
sys.path.insert(0, "/usr/local/opencv-2.4.11/lib/python2.7/site-packages/")
import argparse
import commands
import cv2
import fnmatch
import os.path
sys.path.append('../lib')
import ProjectMgr
# for all the images in the project image_dir, load the image meta data
# this script produce... | Add an option to force recomputing of image dimensions. | Add an option to force recomputing of image dimensions.
| Python | mit | UASLab/ImageAnalysis |
fe397dccf389e31e6b39d5eaa77aedd266cef72d | Practice.py | Practice.py | print 2**3
print pow(2,3)
print abs(-10)
print round(1.536,2)
print 1/2
print 1.0//2.0
print 0xAF
print 010
| print 2**3
print pow(2,3)
print abs(-10)
print round(1.536,2)
print 1/2
print 1.0//2.0
print 0xAF
print 010
import cmath
print cmath.sqrt(-1)
import math
print math.floor(32.8)
| Test math and cmath module. | Test math and cmath module.
| Python | apache-2.0 | Vayne-Lover/Python |
e4964832cf330f57c4ef6dc7be942d2533c840a7 | breakpad.py | breakpad.py | # Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Breakpad for Python.
Sends a notification when a process stops on an exception."""
import atexit
import getpass
import urllib
import traceback
impor... | # Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Breakpad for Python.
Sends a notification when a process stops on an exception."""
import atexit
import getpass
import urllib
import traceback
impor... | Fix KeyboardInterrupt exception filtering. Add exception information and not just the stack trace. Make the url easier to change at runtime. | Fix KeyboardInterrupt exception filtering.
Add exception information and not just the stack trace.
Make the url easier to change at runtime.
Review URL: http://codereview.chromium.org/2109001
git-svn-id: bd64dd6fa6f3f0ed0c0666d1018379882b742947@47179 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
| Python | bsd-3-clause | svn2github/chromium-depot-tools,svn2github/chromium-depot-tools,svn2github/chromium-depot-tools |
ad97fa93ad50bfb73c29798f9f1f24465c6a3683 | _lua_paths.py | _lua_paths.py | import os
import re
_findBackslash = re.compile("/")
# http://rosettacode.org/wiki/Find_common_directory_path#Python
def __commonprefix(*args, sep='/'):
return os.path.commonprefix(*args).rpartition(sep)[0]
def __getProjectPaths(view):
project_data=view.window().project_data()
if project_data is None:
re... | import os
import re
_findBackslash = re.compile("/")
# http://rosettacode.org/wiki/Find_common_directory_path#Python
def __commonprefix(*args, sep='/'):
return os.path.commonprefix(*args).rpartition(sep)[0]
def __getProjectPaths(view):
project_data=view.window().project_data()
if project_data is None:
re... | Fix crash if view returns no valid path | Fix crash if view returns no valid path
| Python | mit | coronalabs/CoronaSDK-SublimeText,coronalabs/CoronaSDK-SublimeText |
a0151bb7934beac7f5db3c79c60d7335a594d29a | alg_minmax.py | alg_minmax.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def find_min_max_naive(a_ls):
"""Find mix & max in a list by naive method."""
_min = a_ls[0]
_max = a_ls[0]
for i in range(1, len(a_ls)):
_min = min(_min, a_ls[i])
_max = max(_ma... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def find_min_max_naive(a_ls):
"""Find mix & max in a list by naive method."""
_min = a_ls[0]
_max = a_ls[0]
for i in range(1, len(a_ls)):
_min = min(_min, a_ls[i])
_max = max(_ma... | Complete find_min_max_dc() with divide and conquer method | Complete find_min_max_dc() with divide and conquer method
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
85bba7e080100ed7154330c8b0d1476bc3718e28 | one_time_eval.py | one_time_eval.py | # usage: python one_time_eval.py as8sqdtc
# usage: python one_time_eval.py as8sqdtc 2skskd
from convenience import find_pcts, pr, str2cards
import sys
## argv to strings
hole_cards_str = sys.argv[1]
board_str = ''
if len(sys.argv) > 2:
board_str = sys.argv[2]
## strings to lists of Card objects
hole_cards = str2... | # usage: python one_time_eval.py hole_cards [board_cards]
# examples:
# python one_time_eval.py as8sqdtc
# python one_time_eval.py as8sqdtc 2skskd
# python one_time_eval.py as8sqdtc3d3c 2skskd
# python one_time_eval.py as8sqdtc3d3c 2skskd3h5s
from convenience import find_pcts_multi, pr,... | Add support for multi-way pots. | Add support for multi-way pots.
| Python | mit | zimolzak/poker-experiments,zimolzak/poker-experiments,zimolzak/poker-experiments |
c5e319363727f332b04ac863e494cb04c52c91b5 | drupal/Revert.py | drupal/Revert.py | from fabric.api import *
from fabric.contrib.files import sed
import random
import string
import time
# Custom Code Enigma modules
import Drupal
import common.MySQL
# Small function to revert db
@task
@roles('app_primary')
def _revert_db(repo, branch, build, buildtype, site):
print "===> Reverting the database..."
... | from fabric.api import *
from fabric.contrib.files import sed
import random
import string
import time
# Custom Code Enigma modules
import Drupal
import common.MySQL
# Small function to revert db
@task
@roles('app_primary')
def _revert_db(repo, branch, build, buildtype, site):
print "===> Reverting the database..."
... | Add back the stable_build variable which is needed in the _revert_settings() function. Woops. | Add back the stable_build variable which is needed in the _revert_settings() function. Woops.
| Python | mit | codeenigma/deployments,codeenigma/deployments,codeenigma/deployments,codeenigma/deployments |
d600fc56127f234a7a14b4a89be14b5c31b072e7 | examples/edge_test.py | examples/edge_test.py | """
This test is only for Microsoft Edge (Chromium)!
"""
from seleniumbase import BaseCase
class EdgeTests(BaseCase):
def test_edge(self):
if self.browser != "edge":
print("\n This test is only for Microsoft Edge (Chromium)!")
print(' (Run this test using "--edge" or "--browser=... | """
This test is only for Microsoft Edge (Chromium)!
(Tested on Edge Version 89.0.774.54)
"""
from seleniumbase import BaseCase
class EdgeTests(BaseCase):
def test_edge(self):
if self.browser != "edge":
print("\n This test is only for Microsoft Edge (Chromium)!")
print(' (Run th... | Update the Edge example test | Update the Edge example test
| Python | mit | mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase |
166fd73f5ac4501b9357d0263e6b68888836588a | tests/test_cookiecutter_invocation.py | tests/test_cookiecutter_invocation.py | # -*- coding: utf-8 -*-
"""
test_cookiecutter_invocation
----------------------------
Tests to make sure that cookiecutter can be called from the cli without
using the entry point set up for the package.
"""
import os
import pytest
import subprocess
import sys
from cookiecutter import utils
def test_should_raise_... | # -*- coding: utf-8 -*-
"""
test_cookiecutter_invocation
----------------------------
Tests to make sure that cookiecutter can be called from the cli without
using the entry point set up for the package.
"""
import os
import pytest
import subprocess
import sys
from cookiecutter import utils
def test_should_raise_... | Use sys.executable when invoking python interpreter from tests | Use sys.executable when invoking python interpreter from tests
When we only have python3 installed, the test for missing argument is
failing because there is no "python" executable. Use `sys.executable`
instead. Also set environment correctly, like done in 7024d3b36176.
| Python | bsd-3-clause | audreyr/cookiecutter,hackebrot/cookiecutter,pjbull/cookiecutter,michaeljoseph/cookiecutter,michaeljoseph/cookiecutter,luzfcb/cookiecutter,hackebrot/cookiecutter,audreyr/cookiecutter,pjbull/cookiecutter,luzfcb/cookiecutter |
f48344f8b961971eb0946bcb4066df021f3eef8a | tinysrt.py | tinysrt.py | #!/usr/bin/env python
import re
import datetime
from collections import namedtuple
SUBTITLE_REGEX = re.compile(r'''\
(\d+)
(\d+:\d+:\d+,\d+) --> (\d+:\d+:\d+,\d+)
(.+)
''')
Subtitle = namedtuple('Subtitle', ['index', 'start', 'end', 'content'])
def parse_time(time):
hours, minutes, seconds, milliseconds = map(... | #!/usr/bin/env python
import re
import datetime
from collections import namedtuple
SUBTITLE_REGEX = re.compile(r'''\
(\d+)
(\d+:\d+:\d+,\d+) --> (\d+:\d+:\d+,\d+)
(.+)
''')
Subtitle = namedtuple('Subtitle', ['index', 'start', 'end', 'content'])
def parse_time(time):
hours, minutes, seconds, milliseconds = map(... | Allow passing a string since we're just going to .read() the FH | parse(): Allow passing a string since we're just going to .read() the FH
| Python | mit | cdown/srt |
19a96cb5b687e580bd3bda348a47255394da7826 | tools/telemetry/telemetry/core/platform/power_monitor/ippet_power_monitor_unittest.py | tools/telemetry/telemetry/core/platform/power_monitor/ippet_power_monitor_unittest.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import unittest
from telemetry import decorators
from telemetry.core.platform import win_platform_backend
from telemetry.core.platform.power_... | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import unittest
from telemetry import decorators
from telemetry.core.platform import win_platform_backend
from telemetry.core.platform.power_... | Disable IppetPowerMonitorTest.testFindOrInstallIppet which is failing on new trybots. | Disable IppetPowerMonitorTest.testFindOrInstallIppet which is failing on new trybots.
BUG=424027
TBR=dtu@chromium.org
Review URL: https://codereview.chromium.org/643763005
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#299833}
| Python | bsd-3-clause | dushu1203/chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,dednal/chromium.src,markYoungH/chromium.src,Chilledheart/chromium,jaruba/chromium.src,Jonekee/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,... |
cc09da295d61965af1552b35b7ece0caf4e5a399 | accountant/interface/forms.py | accountant/interface/forms.py | # -*- coding: utf-8 -*-
from django import forms
from django.core.exceptions import NON_FIELD_ERRORS
from django.utils.translation import ugettext_lazy as _
from core import models
DUPLICATE_PLAYER_ERROR = \
_('There is already a player with this name in your game')
class CreateGameForm(forms.Form):
bank_cash... | # -*- coding: utf-8 -*-
from django import forms
from django.core.exceptions import NON_FIELD_ERRORS
from django.utils.translation import ugettext_lazy as _
from core import models
DUPLICATE_PLAYER_ERROR = \
_('There is already a player with this name in your game')
class CreateGameForm(forms.Form):
bank_cash... | Hide Game ID input since it is automatically set | Hide Game ID input since it is automatically set
| Python | mit | XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant |
c9ca9ae51ebc976bc60b982b9e98f68325301aea | corehq/util/es/interface.py | corehq/util/es/interface.py | class ElasticsearchInterface(object):
def __init__(self, es):
self.es = es
def update_index_settings(self, index, settings_dict):
return self.es.indices.put_settings(settings_dict, index=index)
| import abc
from django.conf import settings
class AbstractElasticsearchInterface(metaclass=abc.ABCMeta):
def __init__(self, es):
self.es = es
def update_index_settings(self, index, settings_dict):
return self.es.indices.put_settings(settings_dict, index=index)
class ElasticsearchInterface1... | Split ElasticsearchInterface into ElasticsearchInterface1 and ElasticsearchInterface2 | Split ElasticsearchInterface into ElasticsearchInterface1 and ElasticsearchInterface2
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
a97f3948c0f9c2b7e446c70a2f158b38a6c9365b | modules/play/play.py | modules/play/play.py | from flask import Blueprint, request, url_for, render_template
from flask.ext.security import current_user
play = Blueprint('play', __name__, template_folder='templates')
@play.route('/')
def index():
api_token = current_user.api_token
return render_template('play/index.html', api_token=api_token)
| from flask import Blueprint, request, url_for, render_template
from flask import redirect
from flask.ext.security import current_user, AnonymousUser
play = Blueprint('play', __name__, template_folder='templates')
@play.route('/')
def index():
if hasattr(current_user, 'api_token'):
api_token = current_use... | Fix error if anonymous user is logged in, instead redirect to login page | Fix error if anonymous user is logged in, instead redirect to login page
| Python | mit | KanColleTool/kcsrv,KanColleTool/kcsrv,KanColleTool/kcsrv |
764a6387ddd117c5dc55b5345fcf7ebab5a01190 | addons/zotero/serializer.py | addons/zotero/serializer.py | from addons.base.serializer import CitationsAddonSerializer
class ZoteroSerializer(CitationsAddonSerializer):
addon_short_name = 'zotero'
@property
def serialized_node_settings(self):
result = super(ZoteroSerializer, self).serialized_node_settings
result['library'] = {
'name': ... | from addons.base.serializer import CitationsAddonSerializer
class ZoteroSerializer(CitationsAddonSerializer):
addon_short_name = 'zotero'
@property
def serialized_node_settings(self):
result = super(ZoteroSerializer, self).serialized_node_settings
result['library'] = {
'name': ... | Add groups key in response to zotero/settings. | Add groups key in response to zotero/settings.
| Python | apache-2.0 | brianjgeiger/osf.io,Johnetordoff/osf.io,pattisdr/osf.io,mfraezz/osf.io,chennan47/osf.io,cslzchen/osf.io,adlius/osf.io,aaxelb/osf.io,caseyrollins/osf.io,erinspace/osf.io,aaxelb/osf.io,mattclark/osf.io,baylee-d/osf.io,Johnetordoff/osf.io,HalcyonChimera/osf.io,saradbowman/osf.io,binoculars/osf.io,chennan47/osf.io,mfraezz/... |
da619869c8d321863a1cc081189ebda79e1b5dbc | djclick/test/test_params.py | djclick/test/test_params.py | from click.exceptions import BadParameter
import pytest
from djclick import params
@pytest.mark.django_db
def test_modelinstance_init():
from testapp.models import DummyModel
from django.db.models.query import QuerySet
param = params.ModelInstance(DummyModel)
assert isinstance(param.qs, QuerySet)
... | from click.exceptions import BadParameter
import pytest
from djclick import params
@pytest.mark.django_db
def test_modelinstance_init():
from testapp.models import DummyModel
from django.db.models.query import QuerySet
param = params.ModelInstance(DummyModel)
assert isinstance(param.qs, QuerySet)
... | Fix a check for specific formatting of an error message | tests: Fix a check for specific formatting of an error message
Instead of checking for the specific formatting of pytest's wrapper
around an exception, check the error message with `ExceptionInfo.match`.
This improves compatibility with different versions of pytest.
| Python | mit | GaretJax/django-click |
6c870e242914d40601bf7ad24e48af2b0d28559e | notification/urls.py | notification/urls.py | from django.conf.urls.defaults import *
from notification.views import notices, mark_all_seen, feed_for_user, single, notice_settings
urlpatterns = patterns("",
url(r"^$", notices, name="notification_notices"),
url(r"^settings/$", notice_settings, name="notification_notice_settings"),
url(r"^(\d+)/$", si... | try:
from django.conf.urls.defaults import *
except ImportError:
from django.conf.urls import *
from notification.views import notices, mark_all_seen, feed_for_user, single, notice_settings
urlpatterns = patterns("",
url(r"^$", notices, name="notification_notices"),
url(r"^settings/$", notice_setting... | Change to work with django 1.7 | Change to work with django 1.7
| Python | mit | daniell/django-notification,daniell/django-notification |
07ae4af01043887d584e3024d7d7e0aa093c85f4 | intercom.py | intercom.py | import configparser
import time
import RPi.GPIO as GPIO
from client import MumbleClient
class InterCom:
def __init__(self):
config = configparser.ConfigParser()
config.read('intercom.ini')
self.mumble_client = MumbleClient(config['mumbleclient'])
self.exit = False
self.sen... | import configparser
import time
import RPi.GPIO as GPIO
from client import MumbleClient
class InterCom:
def __init__(self):
config = configparser.ConfigParser()
config.read('intercom.ini')
self.mumble_client = MumbleClient(config['mumbleclient'])
self.exit = False
if conf... | Add clearing if not recording and remove useless member | Add clearing if not recording and remove useless member
| Python | mit | pkronstrom/intercom |
094380f4e30608713de549389adc1657f55b97b6 | UCP/login/serializers.py | UCP/login/serializers.py | from rest_framework import serializers
from django.contrib.auth.models import User
from login.models import UserProfile
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'password')
write_only_fields = ('password',)
read... | from rest_framework import serializers
from django.contrib.auth.models import User
from login.models import UserProfile
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'password')
write_only_fields = ('password',)
read... | Fix saving passwords in Register API | Fix saving passwords in Register API
override the create method in UserSerializer and set password there
| Python | bsd-3-clause | BuildmLearn/University-Campus-Portal-UCP,BuildmLearn/University-Campus-Portal-UCP,BuildmLearn/University-Campus-Portal-UCP |
8db1207cc8564fff8fb739b627932ea3ce4785fc | app/gbi_server/forms/wfs.py | app/gbi_server/forms/wfs.py | # This file is part of the GBI project.
# Copyright (C) 2013 Omniscale GmbH & Co. KG <http://omniscale.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licens... | # This file is part of the GBI project.
# Copyright (C) 2013 Omniscale GmbH & Co. KG <http://omniscale.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licens... | Allow all characters for layer title | Allow all characters for layer title
| Python | apache-2.0 | omniscale/gbi-server,omniscale/gbi-server,omniscale/gbi-server |
382d304a3f8a4a1d2a396074836ed6e951245800 | cropList.py | cropList.py | #!/usr/bin/python
import os
if __name__ == '__main__':
js_file = open('cropList.js', 'w')
js_file.write('imageNames = [\n')
js_file.write(',\n'.join(['\t"%s"' % name for name in os.listdir('originals')
if name[-4:] in ('.JPG', '.jpg', '.PNG', '.png')]))
js_file.write('\n\t];\n')
js_file.close()
| #!/usr/bin/python
import os
if __name__ == '__main__':
js_file = open('cropList.js', 'w')
js_file.write('var imageNames = [\n')
js_file.write(',\n'.join(['\t"{}"'.format(name) for name in os.listdir('originals')
if name[-4:] in ('.JPG', '.jpg', '.PNG', '.png')]))
js_file.write('\n];\n')
js_file.close()
| Declare imageNames with var, use .format() instead of %, remove tab before closing bracket | Declare imageNames with var, use .format() instead of %, remove tab before closing bracket
| Python | mit | nightjuggler/pig,nightjuggler/pig,nightjuggler/pig |
abe30517c0a16cb54977979ab4a90c3fd841f801 | modules/tools.py | modules/tools.py | inf = infinity = float('inf')
class Timer:
def __init__(self, duration, *callbacks):
self.duration = duration
self.callbacks = list(callbacks)
self.elapsed = 0
self.paused = False
def register(self, callback):
self.callbacks.append(callback)
def unregister(self, ... | inf = infinity = float('inf')
class Timer:
def __init__(self, duration, *callbacks):
self.duration = duration
self.callbacks = list(callbacks)
self.elapsed = 0
self.expired = False
self.paused = False
def register(self, callback):
self.callbacks.append(callbac... | Add a has_expired() method to the Timer class. | Add a has_expired() method to the Timer class.
| Python | mit | kxgames/kxg |
661299275942813a0c45aa90db64c9603d287839 | lib_common/src/d1_common/iter/string.py | lib_common/src/d1_common/iter/string.py | # -*- coding: utf-8 -*-
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2016 DataONE
#
# Licensed under the Apache License, Version 2.0 ... | # -*- coding: utf-8 -*-
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2016 DataONE
#
# Licensed under the Apache License, Version 2.0 ... | Improve StringIterator to allow for more general usage | Improve StringIterator to allow for more general usage
| Python | apache-2.0 | DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python |
0b6b90a91390551fffebacea55e9cccb4fa3d277 | capmetrics_etl/cli.py | capmetrics_etl/cli.py | import click
from . import etl
@click.command()
@click.option('--test', default=False)
def run(test):
if not test:
etl.run_excel_etl()
else:
click.echo('Capmetrics test.')
# Call run function when module deployed as script. This is approach is common
# within the python community
if __name__ ... | import click
import configparser
import json
from . import etl
def parse_capmetrics_configuration(config_parser):
worksheet_names = json.loads(config_parser['capmetrics']['worksheet_names'])
capmetrics_configuration = {
'timezone': 'America/Chicago',
'engine': config_parser['capmetrics']['e... | Add configuration parsing to CLI. | Add configuration parsing to CLI.
| Python | mit | jga/capmetrics-etl,jga/capmetrics-etl |
3d1774aeb21b38e7cbb677228aed25e36374d560 | basics/candidate.py | basics/candidate.py |
import numpy as np
class Candidate(object):
"""
Class for candidate bubble portions from 2D planes.
"""
def __init__(self, mask, img_coords):
super(Candidate, self).__init__()
self.mask = mask
self.img_coords = img_coords
self._parent = None
self._child = None... |
import numpy as np
class Bubble2D(object):
"""
Class for candidate bubble portions from 2D planes.
"""
def __init__(self, props):
super(Bubble2D, self).__init__()
self._channel = props[0]
self._y = props[1]
self._x = props[2]
self._major = props[3]
sel... | Update class for 2D bubbles | Update class for 2D bubbles
| Python | mit | e-koch/BaSiCs |
c9d8833d59ae4858cfba69e44c1e8aaa5dd07df9 | tests/test_create_template.py | tests/test_create_template.py | # -*- coding: utf-8 -*-
"""
test_create_template
--------------------
"""
import os
import pip
import pytest
import shutil
import subprocess
TEMPLATE = os.path.realpath('.')
@pytest.fixture(autouse=True)
def clean_tmp_dir(tmpdir, request):
"""
Remove the project directory that is created by cookiecutter d... | # -*- coding: utf-8 -*-
"""
test_create_template
--------------------
"""
import os
import pip
import pytest
import shutil
import subprocess
from cookiecutter.main import cookiecutter
TEMPLATE = os.path.realpath('.')
@pytest.fixture(autouse=True)
def clean_tmp_dir(tmpdir, request):
"""
Remove the projec... | Add a test that uses the cookiecutter python API | Add a test that uses the cookiecutter python API
| Python | mit | luzfcb/cookiecutter-pytest-plugin,pytest-dev/cookiecutter-pytest-plugin,s0undt3ch/cookiecutter-pytest-plugin |
cf05e02a1efc1bf680904df5f34eb783131b37bb | db/sql_server/pyodbc.py | db/sql_server/pyodbc.py | from django.db import connection
from django.db.models.fields import *
from south.db import generic
class DatabaseOperations(generic.DatabaseOperations):
"""
django-pyodbc (sql_server.pyodbc) implementation of database operations.
"""
def create_table(self, table_name, fields):
# Tweak stuff a... | from django.db import connection
from django.db.models.fields import *
from south.db import generic
class DatabaseOperations(generic.DatabaseOperations):
"""
django-pyodbc (sql_server.pyodbc) implementation of database operations.
"""
add_column_string = 'ALTER TABLE %s ADD %s;'
def create_ta... | Add column support for sql server | Add column support for sql server
--HG--
extra : convert_revision : svn%3A69d324d9-c39d-4fdc-8679-7745eae9e2c8/trunk%40111
| Python | apache-2.0 | philipn/django-south,RaD/django-south,RaD/django-south,philipn/django-south,RaD/django-south,nimnull/django-south,nimnull/django-south |
0213bbb8f8075b2dc36a33380a66932c9d541f63 | src/sphobjinv/__init__.py | src/sphobjinv/__init__.py | r"""``sphobjinv`` *package definition module*.
``sphobjinv`` is a toolkit for manipulation and inspection of
Sphinx |objects.inv| files.
**Author**
Brian Skinn (bskinn@alum.mit.edu)
**File Created**
17 May 2016
**Copyright**
\(c) Brian Skinn 2016-2022
**Source Repository**
https://github.com/bskinn... | r"""``sphobjinv`` *package definition module*.
``sphobjinv`` is a toolkit for manipulation and inspection of
Sphinx |objects.inv| files.
**Author**
Brian Skinn (bskinn@alum.mit.edu)
**File Created**
17 May 2016
**Copyright**
\(c) Brian Skinn 2016-2022
**Source Repository**
https://github.com/bskinn... | Clean up the error imports | Clean up the error imports
The new errors that had been added for _intersphinx.py had left
the sphobjinv.error import line split. No need, when it all fits on
one line.
| Python | mit | bskinn/sphobjinv |
a3e5f553fdf8dffa894d7ba3b89fefd0019653fe | oscar/apps/customer/alerts/receivers.py | oscar/apps/customer/alerts/receivers.py | from django.conf import settings
from django.db.models import get_model
from django.db.models.signals import post_save
from django.contrib.auth.models import User
def send_product_alerts(sender, instance, created, **kwargs):
from oscar.apps.customer.alerts import utils
utils.send_product_alerts(instance.produ... | from django.conf import settings
from django.db.models import get_model
from django.db.models.signals import post_save
from django.db import connection
from django.contrib.auth.models import User
def send_product_alerts(sender, instance, created, **kwargs):
from oscar.apps.customer.alerts import utils
utils.s... | Adjust post-user-create receiver to check database state | Adjust post-user-create receiver to check database state
Need to avoid situation where this signal gets raised by syncdb and the
database isn't in the correct state.
Fixes #475
| Python | bsd-3-clause | rocopartners/django-oscar,marcoantoniooliveira/labweb,Idematica/django-oscar,rocopartners/django-oscar,adamend/django-oscar,makielab/django-oscar,michaelkuty/django-oscar,django-oscar/django-oscar,amirrpp/django-oscar,adamend/django-oscar,jinnykoo/wuyisj.com,jinnykoo/christmas,binarydud/django-oscar,jinnykoo/wuyisj.com... |
a565235303e1f2572ed34490e25c7e0f31aba74c | turngeneration/serializers.py | turngeneration/serializers.py | from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers
from . import models
class ContentTypeField(serializers.Field):
def to_representation(self, obj):
ct = ContentType.objects.get_for_model(obj)
return u'{ct.app_label}.{ct.model}'.format(ct=ct)
de... | from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers
from . import models
class ContentTypeField(serializers.Field):
def to_representation(self, value):
return u'{value.app_label}.{value.model}'.format(value=value)
def to_internal_value(self, data):
... | Support nested generator inside the realm. | Support nested generator inside the realm.
| Python | mit | jbradberry/django-turn-generation,jbradberry/django-turn-generation |
1f75d6b1d13814207c5585da166e59f3d67af4c1 | stickord/commands/xkcd.py | stickord/commands/xkcd.py | '''
Provides commands to the xkcd system
'''
from stickord.helpers.xkcd_api import get_random, get_by_id, print_comic, get_recent
from stickord.registry import Command
@Command('xkcd', category='xkcd')
async def get_comic(cont, _mesg):
''' Search for a comic by id, if no id is provided it will post a random comic.... | '''
Provides commands to the xkcd system
'''
from stickord.helpers.xkcd_api import get_random, get_by_id, print_comic, get_recent
from stickord.registry import Command
@Command('xkcd', category='xkcd')
async def get_comic(cont, _mesg):
''' Search for a comic by id, if no id is provided it will post a random comic.... | Fix crash on invalid int | Fix crash on invalid int
| Python | mit | RobinSikkens/Sticky-discord |
936a8b77625f881f39f2433fad126f1b5d73fa3f | commands.py | commands.py | from runcommands import command
from runcommands.commands import local as _local
@command
def format_code(check=False):
_local(f"black . {'--check' if check else ''}")
@command
def lint():
_local("flake8 .")
@command
def test(with_coverage=True, check=True):
if with_coverage:
_local(
... | from runcommands import command
from runcommands.commands import local as _local
@command
def format_code(check=False):
_local(f"black . {'--check' if check else ''}")
@command
def lint():
_local("flake8 .")
@command
def test(with_coverage=True, check=True):
if with_coverage:
_local(
... | Fix test command, esp. wrt. coverage | Fix test command, esp. wrt. coverage
| Python | mit | wylee/django-local-settings |
d1be59a87fce8e20d698c4d1f6a272c21834a1c3 | providers/popularity/kickasstorrents.py | providers/popularity/kickasstorrents.py | from providers.popularity.provider import PopularityProvider
from utils.torrent_util import torrent_to_movie, remove_bad_torrent_matches
IDENTIFIER = "kickasstorrents"
class Provider(PopularityProvider):
PAGES_TO_FETCH = 1
def get_popular(self):
names = []
for page in range(Provider.PAGES_TO_... | from providers.popularity.provider import PopularityProvider
from utils.torrent_util import torrent_to_movie, remove_bad_torrent_matches
IDENTIFIER = "kickasstorrents"
class Provider(PopularityProvider):
PAGES_TO_FETCH = 3
def get_popular(self):
names = []
base = "https://kickasstorrents.to/h... | Fix Kickasstorrents by using one of many mirrors. | Fix Kickasstorrents by using one of many mirrors.
| Python | mit | EmilStenstrom/nephele |
f919aa183d1a82ba745df6a5640e8a7a83f8e87e | stix/indicator/valid_time.py | stix/indicator/valid_time.py | # Copyright (c) 2015, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
from mixbox import fields
import stix
from stix.common import DateTimeWithPrecision
import stix.bindings.indicator as indicator_binding
class ValidTime(stix.Entity):
_namespace = "http://stix.mitre.org/Indicato... | # Copyright (c) 2015, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
from mixbox import fields
import stix
from stix.common import DateTimeWithPrecision
import stix.bindings.indicator as indicator_binding
from mixbox.entities import Entity
class ValidTime(Entity):
_namespace = "... | Change ValidTime to a mixbox Entity | Change ValidTime to a mixbox Entity
| Python | bsd-3-clause | STIXProject/python-stix |
bc6e6f0faec8405849c896b0661c181e9853359d | match/management/commands/import-users.py | match/management/commands/import-users.py | from django.core.management.base import BaseCommand, CommandError
from match.models import User
import csv
import sys
class Command(BaseCommand):
help = 'Import a list of users from stdin'
def handle(self, *args, **options):
# read a file and copy its contents as test users
tsvin = csv.reade... | from django.core.management.base import BaseCommand, CommandError
from match.models import User
import csv
import sys
class Command(BaseCommand):
help = 'Import a list of users from stdin'
def handle(self, *args, **options):
# read a file and copy its contents as test users
User.objects.all(... | Delete users before importing them | Delete users before importing them
| Python | mit | maxf/address-matcher,maxf/address-matcher,maxf/address-matcher,maxf/address-matcher |
d656c0117e8487b8b56b4ee3caceb2dcb38ec198 | sympy/concrete/tests/test_gosper.py | sympy/concrete/tests/test_gosper.py | def test_normal():
pass
def test_gosper():
pass
| from sympy import Symbol, normal
from sympy.abc import n
def test_normal():
assert normal(4*n+5, 2*(4*n+1)*(2*n+3), n)
def test_gosper():
pass
| Add test for part of gosper's algorithm. | Add test for part of gosper's algorithm.
| Python | bsd-3-clause | abhiii5459/sympy,mafiya69/sympy,atreyv/sympy,wanglongqi/sympy,pandeyadarsh/sympy,liangjiaxing/sympy,srjoglekar246/sympy,Sumith1896/sympy,bukzor/sympy,atsao72/sympy,sunny94/temp,moble/sympy,cccfran/sympy,yashsharan/sympy,drufat/sympy,maniteja123/sympy,AunShiLord/sympy,shikil/sympy,pandeyadarsh/sympy,Davidjohnwilson/symp... |
bcb84a5b85259644ec0949f820ac1ed8f03d1676 | scripts/reactions.py | scripts/reactions.py | import argparse
from lenrmc.nubase import System
from lenrmc.terminal import TerminalView
class App(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
def run(self):
s = System.parse(self.kwargs['system'], **self.kwargs)
for line in TerminalView(s).lines(**self.kwargs):
... | import argparse
from lenrmc.nubase import System
from lenrmc.terminal import TerminalView, StudiesTerminalView
class App(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
if 'studies' == self.kwargs.get('view'):
self.view_cls = StudiesTerminalView
else:
... | Add ability to print out studies view from command line. | Add ability to print out studies view from command line.
| Python | mit | emwalker/lenrmc |
00103355232a0efb76f401dbec3ab4f8be32526a | qual/calendar.py | qual/calendar.py | from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar... | from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar... | Handle julian leap days separately. | Handle julian leap days separately.
| Python | apache-2.0 | jwg4/calexicon,jwg4/qual |
c4cd02672c81a486f6397ea099b9ed1e95b05df6 | docs/tests.py | docs/tests.py | import os
from django.test import Client, TestCase
from django.core.urlresolvers import reverse
from django.core.management import call_command
import views
class DocsTestCase(TestCase):
def setUp(self):
self.client = Client()
def test_index(self):
response = self.client.get(reverse(views.... | import os
from django.test import Client, TestCase
from django.core.urlresolvers import reverse
from django.core.management import call_command
import views
class DocsTestCase(TestCase):
def setUp(self):
self.client = Client()
def test_index(self):
response = self.client.get(reverse(views.... | Add test case for 404 on docs pages | Add test case for 404 on docs pages
| Python | mit | crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp |
952550b344e96236995ac72eaa0777fd356f21e2 | infinity.py | infinity.py | try:
from functools import total_ordering
except ImportError:
# Use Python 2.6 port
from total_ordering import total_ordering
@total_ordering
class Infinity(object):
"""
An object that is greater than any other object (except itself).
Inspired by https://pypi.python.org/pypi/Extremes
Exa... | try:
from functools import total_ordering
except ImportError:
# Use Python 2.6 port
from total_ordering import total_ordering
@total_ordering
class Infinity(object):
"""
An object that is greater than any other object (except itself).
Inspired by https://pypi.python.org/pypi/Extremes
Exa... | Add float coercion, datetime comparison support | Add float coercion, datetime comparison support
| Python | bsd-3-clause | kvesteri/infinity |
4334cbf05da1c1f6a6a984e1a062a7e8f252b664 | components/includes/utilities.py | components/includes/utilities.py | import random
import json
import time
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if ... | import random
import json
import time
import socket
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(... | Clean up, comments, liveness checking, robust data transfer | Clean up, comments, liveness checking, robust data transfer
| Python | bsd-2-clause | mavroudisv/Crux |
c538e1a673e208030db04ab9ad3b97e962f3e2ac | download_summaries.py | download_summaries.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from utils.summary_downloader import SummaryDownloader
if __name__ == '__main__':
# setting target dir and time interval of interest
tgt_dir = r"D:\nhl\official_and_json\2016-17"
tgt_dir = r"d:\tmp\test"
date = "2017/05/01"
to_date = "2017/05/01"
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
from datetime import datetime
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
from utils.summary_downloader import SummaryDownloader
if __name__ == '__main__':
# retrieving arguments specified on command ... | Allow control of download process via command line | Allow control of download process via command line
| Python | mit | leaffan/pynhldb |
2f5417811eb8048659bd9b5408c721d481af4ece | tests/python-support/experiments.py | tests/python-support/experiments.py | import os
import subprocess
import json
def _experiment_runner_path():
this_path = os.path.dirname(os.path.realpath(__file__))
return this_path + "/../../target/release/experiments"
def run_experiment(params):
args = [_experiment_runner_path() ]
result = subprocess.run(args=args,
... | import os
import subprocess
import json
def _experiment_runner_path():
this_path = os.path.dirname(os.path.realpath(__file__))
return this_path + "/../../target/release/experiments"
def run_experiment(params):
args = [_experiment_runner_path()]
result = subprocess.run(args=args,
... | Print JSON document upon parse error | Print JSON document upon parse error
| Python | mit | Andlon/crest,Andlon/crest,Andlon/crest |
cc2fcbf73b0f3eb6ddfee2b55edc6239df3171e0 | bower/commands/install.py | bower/commands/install.py | import sublime_plugin
from bower.utils.api import API
class InstallCommand(sublime_plugin.WindowCommand):
def run(self, *args, **kwargs):
self.list_packages()
def list_packages(self):
fileList = []
packages = API().get('packages')
packages.reverse()
for package in pack... | import sublime_plugin
from bower.utils.api import API
class InstallCommand(sublime_plugin.WindowCommand):
def run(self, *args, **kwargs):
self.list_packages()
def list_packages(self):
fileList = []
packages = API().get('packages')
packages.reverse()
for package in pack... | Correct my cowboy fix that broke. | Correct my cowboy fix that broke.
| Python | mit | benschwarz/sublime-bower,ebidel/sublime-bower |
dd9fb6cf515d9e7ceb26cc6f7e8fd869d721552c | shop/models/fields.py | shop/models/fields.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.postgresql':
from django.contrib.postgres.fields import JSONField as _JSONField
else:
from jsonfield.fields import JSONField as _JSONField
class... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
postgresql_engine_names = [
'django.db.backends.postgresql',
'django.db.backends.postgresql_psycopg2',
]
if settings.DATABASES['default']['ENGINE'] in postgresql_engine_names:
from django.contrib.postgres.fie... | Check for older Postgresql engine name for JSONField | Check for older Postgresql engine name for JSONField
The Postgresql database engine name was changed from
'django.db.backends.postgresql_psycopg2' to
'django.db.backends.postgresql' in Django 1.9. However, the former name
still works in newer versions of Django for compatibility reasons. This
value should also be chec... | Python | bsd-3-clause | divio/django-shop,khchine5/django-shop,nimbis/django-shop,khchine5/django-shop,khchine5/django-shop,awesto/django-shop,khchine5/django-shop,awesto/django-shop,awesto/django-shop,divio/django-shop,nimbis/django-shop,divio/django-shop,nimbis/django-shop,nimbis/django-shop |
74f26f0c0a0cb014539212f5b7a703d436b29f29 | backend/globaleaks/jobs/base.py | backend/globaleaks/jobs/base.py | # -*- coding: UTF-8
# jobs/base
# *********
#
# Base class for implement the scheduled tasks
import sys
from twisted.internet import task
from twisted.python.failure import Failure
from globaleaks.utils.utility import log
from globaleaks.utils.mailutils import mail_exception
class GLJob(task.LoopingCall):
d... | # -*- coding: UTF-8
# jobs/base
# *********
#
# Base class for implement the scheduled tasks
import sys
from twisted.internet import task
from twisted.python.failure import Failure
from globaleaks.utils.utility import log
from globaleaks.utils.mailutils import mail_exception
class GLJob(task.LoopingCall):
d... | Patch job scheduler avoiding possibilities for concurrent runs of the same | Patch job scheduler avoiding possibilities for concurrent runs of the same
| Python | agpl-3.0 | vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks |
0b53adc34259fedc23e42e7576517fb62f4cb33e | base_contact/models/ir_model.py | base_contact/models/ir_model.py | # -*- coding: utf-8 -*-
# © 2016 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import logging
from openerp import api, models
_logger = logging.getLogger(__name__)
class IrModel(models.Model):
_inherit = "ir.model"
@api.cr
... | # -*- coding: utf-8 -*-
# © 2016 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import logging
from openerp import api, models
_logger = logging.getLogger(__name__)
class IrModel(models.Model):
_inherit = "ir.model"
@api.cr
... | Downgrade to INFO, since runbots install this. | Downgrade to INFO, since runbots install this.
| Python | agpl-3.0 | open-synergy/partner-contact,acsone/partner-contact,diagramsoftware/partner-contact |
4178bb331014089c69df81b8a99204c94b6e200f | eventsource_parser.py | eventsource_parser.py | from collections import namedtuple
Event = namedtuple('Event', ['id', 'type', 'data'])
def parse(source):
eid = None
etype = None
data = []
retry = None
extra = ''
dispatch = False
lines = source.splitlines()
for line in lines:
if dispatch:
extra += line + '\n... | from collections import namedtuple
Event = namedtuple('Event', ['id', 'type', 'data'])
def parse(source):
eid = None
etype = None
data = []
retry = None
extra = ''
dispatch = False
cursor = 0
lines = source.splitlines()
for line in lines:
if not line:
... | Fix extra in case of fragmented sources | Fix extra in case of fragmented sources
| Python | apache-2.0 | tOkeshu/eventsource-parser |
5e3a9ad00558547475e7b5674bb623cafc99643a | data_exploration.py | data_exploration.py | # importing modules/ libraries
import pandas as pd
import random
# loading the data
aisles_df = pd.read_csv('Data/aisles.csv')
print(aisles_df.head())
departments_df = pd.read_csv('Data/departments.csv')
print(departments_df.head())
#n = 32434489
#s = round(0.1 * n)
#skip = sorted(random.sample(range(1,n), n-s))
ord... | # importing modules/ libraries
import pandas as pd
# loading the data
aisles_df = pd.read_csv('Data/aisles.csv')
print(aisles_df.head())
departments_df = pd.read_csv('Data/departments.csv')
print(departments_df.head())
order_products__prior_df = pd.read_csv('Data/order_products__prior_sample.csv')
print(order_produc... | Update data explorations data sets to samples | fix: Update data explorations data sets to samples
| Python | mit | rjegankumar/instacart_prediction_model |
3c1203d5f4665873e34de9600c6cf18cbd7f7611 | moa/tools.py | moa/tools.py |
__all__ = ('to_bool', 'ConfigPropertyList')
from kivy.properties import ConfigParserProperty
from re import compile, split
from functools import partial
to_list_pat = compile(', *')
def to_bool(val):
'''
Takes anything and converts it to a bool type.
'''
if val == 'False':
return False
... |
__all__ = ('to_bool', 'ConfigPropertyList')
from kivy.properties import ConfigParserProperty
from re import compile, split
to_list_pat = compile('(?:, *)?\\n?')
def to_bool(val):
'''
Takes anything and converts it to a bool type.
'''
if val == 'False':
return False
return not not val
... | Add 2d list to ConfigProperty. | Add 2d list to ConfigProperty.
| Python | mit | matham/moa |
e21fd90de3b97f3ea2564a8d2c35351f2136b4e5 | feder/letters/tests/base.py | feder/letters/tests/base.py | import email
from os.path import dirname, join
from django.utils import six
from django_mailbox.models import Mailbox
from feder.letters.signals import MessageParser
class MessageMixin(object):
def setUp(self):
self.mailbox = Mailbox.objects.create(from_email='from@example.com')
super(MessageMix... | import email
from os.path import dirname, join
from django.utils import six
from django_mailbox.models import Mailbox
from feder.letters.signals import MessageParser
class MessageMixin(object):
def setUp(self):
self.mailbox = Mailbox.objects.create(from_email='from@example.com')
super(MessageMix... | Fix detect Git-LFS in tests | Fix detect Git-LFS in tests
| Python | mit | watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder |
b80e1facf3c47364384fa04f764838ba1b8cb55c | form_designer/apps.py | form_designer/apps.py | from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class FormDesignerConfig(AppConfig):
name = "form_designer"
verbose_name = _("Form Designer")
| from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class FormDesignerConfig(AppConfig):
default_auto_field = "django.db.models.AutoField"
name = "form_designer"
verbose_name = _("Form Designer")
| Set the default auto field to be AutoField | Set the default auto field to be AutoField
On django 3.2 it creates a migration to be BigAutoField. This fixes it. | Python | bsd-3-clause | feincms/form_designer,feincms/form_designer |
9c176de1fd280e72dd06c9eaa64060e52abca746 | python/prebuild.py | python/prebuild.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def extract_function_names(module):
'''
extract function names from attributes of 'module'.
'''
from importlib import import_module
mod = import_module(module.__name__)
attr_list = dir(mod)
scope = locals()
def iscallable(name):
r... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def extract_function_names(module):
'''
extract function names from attributes of 'module'.
'''
from importlib import import_module
mod = import_module(module.__name__)
attr_list = dir(mod)
scope = locals()
def iscallable(name):
i... | Remove python decorators from list | Remove python decorators from list
| Python | mit | koji-kojiro/matplotlib-d |
dcc32e96bccc0f679dc9d3330d3da7f3a7ec3983 | fireplace/cards/tgt/mage.py | fireplace/cards/tgt/mage.py | from ..utils import *
##
# Minions
# Dalaran Aspirant
class AT_006:
inspire = Buff(SELF, "AT_006e")
# Spellslinger
class AT_007:
play = Give(ALL_PLAYERS, RandomSpell())
# Rhonin
class AT_009:
deathrattle = Give(CONTROLLER, "EX1_277") * 3
##
# Spells
# Flame Lance
class AT_001:
play = Hit(TARGET, 8)
# Ar... | from ..utils import *
##
# Minions
# Dalaran Aspirant
class AT_006:
inspire = Buff(SELF, "AT_006e")
# Spellslinger
class AT_007:
play = Give(ALL_PLAYERS, RandomSpell())
# Rhonin
class AT_009:
deathrattle = Give(CONTROLLER, "EX1_277") * 3
##
# Spells
# Flame Lance
class AT_001:
play = Hit(TARGET, 8)
# Ar... | Fix Effigy to properly reveal itself | Fix Effigy to properly reveal itself
| Python | agpl-3.0 | Meerkov/fireplace,Ragowit/fireplace,Ragowit/fireplace,jleclanche/fireplace,smallnamespace/fireplace,amw2104/fireplace,smallnamespace/fireplace,beheh/fireplace,Meerkov/fireplace,NightKev/fireplace,amw2104/fireplace |
cdd8b6a7b669dc81e360fa1bcc9b71b5e798cfd5 | map_loader.py | map_loader.py | import os
def read_map_file(map_name):
""" Load map data from disk. """
root = os.path.dirname(os.path.abspath(__file__))
map_path = os.path.join(root, 'maps', map_name + '.txt')
print('Loading map file [{}]'.format(map_name))
if not os.path.isfile(map_path):
print('Map file [{}] does not ... | import logging
import os
def read_map_file(map_name):
""" Load map data from disk. """
root = os.path.dirname(os.path.abspath(__file__))
map_path = os.path.join(root, 'maps', map_name + '.txt')
if not os.path.isfile(map_path):
logging.error('Map file [{}] does not exist'.format(map_path))
... | Remove debug print and log properly | Remove debug print and log properly
| Python | mit | supermitch/mech-ai,supermitch/mech-ai,supermitch/mech-ai |
d0f2b11fb67655b884f298bd8c1bf6be8396de4f | mail/email.py | mail/email.py | from django.conf import settings
from mail import models as mail_api
from groups import models as group_api
from mailgun import api as mailgun_api
def send_email( email_uri ):
""" Send the email to the intended target audience """
email = mail_api.get_email(email_uri)
if email['audience'] == 'groups':
... | from django.conf import settings
from mail import models as mail_api
from groups import models as group_api
from mailgun import api as mailgun_api
def send_email( email_uri ):
""" Send the email to the intended target audience """
email = mail_api.get_email(email_uri)
if email['audience'] == 'groups':
... | Fix bug with campaign id | Fix bug with campaign id
| Python | mit | p2pu/mechanical-mooc,p2pu/mechanical-mooc,p2pu/mechanical-mooc,p2pu/mechanical-mooc |
8be701cabf05e62385f5cc2eaf008b0d0da93d9c | pww/inputs.py | pww/inputs.py | # coding: utf-8
from getpass import getpass
class CLIInput():
def get_user_name(self):
return input('user name: ')
def get_password(self):
return getpass()
def entry_selector(self, entries):
if not entries:
return None, None
titles = list(entries.keys())
... | # coding: utf-8
from getpass import getpass
class CLIInput():
def get_user_name(self):
return input('user name: ')
def get_password(self):
return getpass()
def entry_selector(self, entries):
if not entries:
return None, None
titles = list(entries.keys())
... | Modify that using default value when input value is None. | Modify that using default value when input value is None.
| Python | mit | meganehouser/pww |
043b5e7026663c8fdae8df4f27d3887ef881d405 | src/viewsapp/views.py | src/viewsapp/views.py | from django.shortcuts import (
get_object_or_404, redirect, render)
from django.views.generic import View
from .forms import ExampleForm
from .models import ExampleModel
class ModelDetail(View):
def get(self, request, *args, **kwargs):
request_slug = kwargs.get('slug')
example_obj = get_obje... | from django.shortcuts import redirect, render
from django.views.generic import DetailView, View
from .forms import ExampleForm
from .models import ExampleModel
class ModelDetail(DetailView):
model = ExampleModel
template_name = 'viewsapp/detail.html'
class ModelCreate(View):
context_object_name = 'form... | Refactor ModelDetail to inherit DetailView GCBV. | Refactor ModelDetail to inherit DetailView GCBV.
| Python | bsd-2-clause | jambonrose/djangocon2015-views,jambonrose/djangocon2015-views |
59426d66a252a5f53fab2d56d1f88883b743f097 | gears/processors/hexdigest_paths.py | gears/processors/hexdigest_paths.py | import os
import re
from ..assets import build_asset
from ..exceptions import FileNotFound
from .base import BaseProcessor
URL_RE = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def rewrite_paths(source, func):
repl = lambda match: 'url({quote}{path}{quote})'.format(
quote=match.group(1),
path=... | import os
import re
from ..assets import build_asset
from ..exceptions import FileNotFound
from .base import BaseProcessor
URL_RE = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def rewrite_paths(source, func):
repl = lambda match: 'url({quote}{path}{quote})'.format(
quote=match.group(1),
path=... | Convert string to raw string, in order to print "\\" in css. Otherwise the browse cannot reach the file. | Convert string to raw string, in order to print "\\" in css. Otherwise the browse cannot reach the file.
| Python | isc | gears/gears,gears/gears,gears/gears |
0eb1b641f55a43e83ccc098a0ee33ec2620a86ce | glue/utils/qt/qmessagebox_widget.py | glue/utils/qt/qmessagebox_widget.py | # A patched version of QMessageBox that allows copying the error
from ...external.qt import QtGui
__all__ = ['QMessageBoxPatched']
class QMessageBoxPatched(QtGui.QMessageBox):
def __init__(self, *args, **kwargs):
super(QMessageBoxPatched, self).__init__(*args, **kwargs)
copy_action = QtGui.QA... | # A patched version of QMessageBox that allows copying the error
import os
from ...external.qt import QtGui
__all__ = ['QMessageBoxPatched']
class QMessageBoxPatched(QtGui.QMessageBox):
def __init__(self, *args, **kwargs):
super(QMessageBoxPatched, self).__init__(*args, **kwargs)
copy_action ... | Fix newlines in copying of errors | Fix newlines in copying of errors | Python | bsd-3-clause | JudoWill/glue,stscieisenhamer/glue,stscieisenhamer/glue,saimn/glue,saimn/glue,JudoWill/glue |
8aed9b9402446a311f1f3f93c9bac4416ea114d9 | server/response.py | server/response.py | class HttpResponse(object):
def __init__(self):
self.body = ''
self.headers = {}
self.status_code = 200
self.status_string = 'OK'
self.version = 'HTTP/1.1'
def to_string(self):
h = '%s %d %s\r\n' % (
self.version, self.status_code, self.status_st... | class HttpResponse(object):
def __init__(self):
self.body = ''
self.headers = {}
self.status_code = 200
self.status_string = 'OK'
self.version = 'HTTP/1.1'
def to_string(self):
h = '%s %d %s\r\n' % (
self.version, self.status_code, self.status_st... | Set Content-Length to 0 when no body is set | Set Content-Length to 0 when no body is set
| Python | apache-2.0 | USMediaConsulting/pywebev |
7af01726bbfe1474efdb0fdca58ce83975e6918e | submit_mpi.py | submit_mpi.py | import subprocess
def read_node_status():
process = subprocess.Popen('pestat -f', shell=True,
stdout=subprocess.PIPE)
process.wait()
return process.stdout
if __name__ == '__main__':
stdout = read_node_status()
| import subprocess
def read_node_status():
process = subprocess.Popen('pestat -f', shell=True,
stdout=subprocess.PIPE)
process.wait()
return process.stdout
if __name__ == '__main__':
stdout = read_node_status()
for line in stdout:
print line
| Print stdout, forgot about that. | Print stdout, forgot about that.
| Python | mit | Johanu/submit_mpi |
e7a6c4f669c31bc25ac0eb738e9b6584793db5dc | indra/reach/reach_reader.py | indra/reach/reach_reader.py | from indra.java_vm import autoclass, JavaException
class ReachReader(object):
"""The ReachReaader wraps a singleton instance of the REACH reader.
This allows calling the reader many times without having to wait for it to
start up each time.
Attributes
----------
api_ruler : edu.arizona.sista.... | from indra.java_vm import autoclass, JavaException
class ReachReader(object):
"""The ReachReaader wraps a singleton instance of the REACH reader.
This allows calling the reader many times without having to wait for it to
start up each time.
Attributes
----------
api_ruler : org.clulab.reach.a... | Update REACH reader to new API class path | Update REACH reader to new API class path
| Python | bsd-2-clause | johnbachman/belpy,bgyori/indra,pvtodorov/indra,johnbachman/belpy,pvtodorov/indra,sorgerlab/belpy,pvtodorov/indra,jmuhlich/indra,pvtodorov/indra,johnbachman/belpy,johnbachman/indra,johnbachman/indra,sorgerlab/belpy,bgyori/indra,sorgerlab/belpy,jmuhlich/indra,bgyori/indra,sorgerlab/indra,jmuhlich/indra,sorgerlab/indra,jo... |
1937d8ad8a98058b00d48af4a56f8dd4c6a2176d | tests/__init__.py | tests/__init__.py | """Unit and functional test suite for SkyLines."""
import os
import shutil
from skylines.model import db
from tests.data.bootstrap import bootstrap
__all__ = ['setup_db', 'setup_app', 'teardown_db']
def setup_db():
"""Method used to build a database"""
db.create_all()
def setup_dirs(app):
filesdir = a... | """Unit and functional test suite for SkyLines."""
import os
import shutil
from skylines.model import db
from tests.data.bootstrap import bootstrap
__all__ = ['setup_db', 'setup_app', 'teardown_db']
def setup_db():
"""Method used to build a database"""
db.create_all()
def setup_dirs(app):
filesdir = a... | Fix database connection leak in tests | Fix database connection leak in tests
Without this, each flask app created in tests will hold
one database connection until all tests are finished. This may result
in test failure if database limits number of concurrent connections.
| Python | agpl-3.0 | snip/skylines,Turbo87/skylines,RBE-Avionik/skylines,Turbo87/skylines,shadowoneau/skylines,TobiasLohner/SkyLines,TobiasLohner/SkyLines,Turbo87/skylines,snip/skylines,Harry-R/skylines,shadowoneau/skylines,TobiasLohner/SkyLines,Turbo87/skylines,skylines-project/skylines,RBE-Avionik/skylines,kerel-fs/skylines,shadowoneau/s... |
4d547ffa4112412e340abd6231cd406d14b8ff35 | l10n_lu_ecdf/__openerp__.py | l10n_lu_ecdf/__openerp__.py | {
"name": "eCDF annual reports",
"version": "8.0.1.0.0",
"author": "ACSONE SA/NV",
"license": "AGPL-3",
"category": "Accounting & Finance",
"website": "http://acsone.eu",
"depends": ["l10n_lu_mis_reports",
"mis_builder"],
"module": "",
"summary": "Generates XML eCDF a... | {
"name": "eCDF annual reports",
"version": "8.0.1.0.0",
"author": "ACSONE SA/NV",
"license": "AGPL-3",
"category": "Accounting & Finance",
"website": "http://acsone.eu",
"depends": ["l10n_lu_ext",
"l10n_lu_mis_reports",
"mis_builder"],
"module": "",
"... | Add dependency on l10n_lu_ext, for the field l10n_lu_matricule | [FIX] Add dependency on l10n_lu_ext, for the field l10n_lu_matricule
| Python | agpl-3.0 | acsone/l10n-luxemburg |
e6d7181ababaa9f08602c48e03d6557ddb6a4deb | tests/test_gio.py | tests/test_gio.py | # -*- Mode: Python -*-
import os
import unittest
from common import gio, gobject
class TestInputStream(unittest.TestCase):
def setUp(self):
f = open("inputstream.txt", "w")
f.write("testing")
self._f = open("inputstream.txt", "r")
self.stream = gio.unix.InputStream(self._f.filen... | # -*- Mode: Python -*-
import os
import unittest
from common import gio, gobject
class TestInputStream(unittest.TestCase):
def setUp(self):
f = open("inputstream.txt", "w")
f.write("testing")
self._f = open("inputstream.txt", "r")
self.stream = gio.unix.InputStream(self._f.filen... | Reorganize tests and make them test more useful things | Reorganize tests and make them test more useful things
svn path=/trunk/; revision=738
| Python | lgpl-2.1 | pexip/pygobject,GNOME/pygobject,davibe/pygobject,alexef/pygobject,davidmalcolm/pygobject,MathieuDuponchelle/pygobject,davidmalcolm/pygobject,Distrotech/pygobject,choeger/pygobject-cmake,sfeltman/pygobject,Distrotech/pygobject,MathieuDuponchelle/pygobject,GNOME/pygobject,thiblahute/pygobject,jdahlin/pygobject,atizo/pygo... |
4db16ece582e8f0a81e032ea1a37c9cbf344a261 | couchdb/tests/testutil.py | couchdb/tests/testutil.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import uuid
from couchdb import client
class TempDatabaseMixin(object):
temp_dbs = None
_d... | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import random
import sys
from couchdb import client
class TempDatabaseMixin(object):
temp_dbs ... | Use a random number instead of uuid for temp database name. | Use a random number instead of uuid for temp database name. | Python | bsd-3-clause | zielmicha/couchdb-python,ajmirsky/couchdb-python |
66a6d66ccdc14ca5ad8c2870b18318c5c94524c6 | src/romaine/core.py | src/romaine/core.py | import os
class Core(object):
"""
The core of the Romaine, provides BDD test API.
"""
# All located features
feature_file_paths = []
instance = None
def __init__(self):
"""
Initialise Romaine core.
"""
self.steps = {}
Core.instance = self
... | import os
class Core(object):
"""
The core of the Romaine, provides BDD test API.
"""
# All located features
feature_file_paths = set()
instance = None
def __init__(self):
"""
Initialise Romaine core.
"""
self.steps = {}
Core.instance = self... | Make feature_file_paths have no duplicates | Make feature_file_paths have no duplicates
| Python | mit | trojjer/romaine,london-python-project-nights/romaine,london-python-project-nights/romaine |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.