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 |
|---|---|---|---|---|---|---|---|---|---|
ac46a0fa28901bfd508c75ec71e9e13a02ac40aa | ard-mediathek.py | ard-mediathek.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import contextlib
import sys
from ard_media_downloader import ArdMediathekDownloader
VERSION = "1.1"
def main(argv):
parser = argparse.ArgumentParser(description='Commandline python script tool to download videos from the online ARD mediathek. Ver... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import contextlib
import sys
from ard_media_downloader import ArdMediathekDownloader
VERSION = "1.1"
def main(argv):
parser = argparse.ArgumentParser(description='Commandline python script tool to download videos from the online ARD mediathek. Ver... | Add better error message if URL doe not contain documentId | Add better error message if URL doe not contain documentId
Improves error messages like the one reported with #24
| Python | mit | Bouni/ard-mediathek |
7ee2ea4f3034a6bfc4bcfb78b7c2cc1e3887fb55 | test/_common.py | test/_common.py | # encoding: utf-8
'''
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
'''
from __future__ import absolute_import, print_function, unicode_literals
def print_test_result(expected, actual):
print("[expected]\n{}\n".format(expected))
print("[actual]\n{}\n".format(actual))
| # encoding: utf-8
'''
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
'''
from __future__ import absolute_import, print_function, unicode_literals
import sys
def print_test_result(expected, actual, error=None):
print("[expected]\n{}\n".format(expected))
print("[actual]\n{}\n".format(actual)... | Add an argument to print stderr of test results | Add an argument to print stderr of test results
| Python | mit | thombashi/pytablewriter |
8902c7612d84a2d14e90c4aac6db78ad95dd213c | trading_as/__init__.py | trading_as/__init__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Trading As Brands
# Copyright (C) 2015 OpusVL (<http://opusvl.com/>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pub... | # -*- coding: utf-8 -*-
##############################################################################
#
# Trading As Brands
# Copyright (C) 2015 OpusVL (<http://opusvl.com/>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pub... | Change order of imports to fix install into blank db or as dependency of company config. | Change order of imports to fix install into blank db or as dependency of
company config.
| Python | agpl-3.0 | OpusVL/odoo-trading-as |
bbb5fa95cd4b9d7fac6ac45546eedcd8a5d14162 | s4v1.py | s4v1.py | from s3v3 import *
| from s3v3 import *
import csv
def write_to_file(filename, data_sample):
example = csv.write(open(filename, 'w', encoding='utf-8'), dialect='excel') # example is the variable of the new file that is open and which we can write to (using utf-8 encoding and an excel dialect).
example.writerows(data_sample) # write row... | Create write to file function | Create write to file function
| Python | mit | alexmilesyounger/ds_basics |
978b9450346f4de687ed3c23bc11c970538e948b | mosecom_air/api/parser.py | mosecom_air/api/parser.py | #coding: utf-8
from collections import namedtuple
Substance = namedtuple('Substance', 'name alias')
Measurement = namedtuple('Measurement', 'substance unit performed value')
Result = namedtuple('Result', 'measurements substances units station_alias')
| #coding: utf-8
from collections import namedtuple
Substance = namedtuple('Substance', ('name', 'alias'))
Measurement = namedtuple('Measurement', ('substance', 'unit', 'performed',
'value'))
Result = namedtuple('Result', ('measurements', 'substances', 'units',
... | Use tuple in namedtuples initization | Use tuple in namedtuples initization
| Python | mit | elsid/mosecom-air,elsid/mosecom-air,elsid/mosecom-air |
e8e2ebb156ce75afa87d26a632ed7aa5c74ba2c6 | eggsclaim.py | eggsclaim.py | import signal
import sys
import serial
import sms
from xbee import XBee
MOBILE_NUM = '0400000000'
NOTIFICATION_MSG = 'Cock-a-doodle-doo! An egg is waiting for you!'
egg_was_present = False
def signal_handler(signal, frame):
xbee.halt()
serial_port.close()
sys.exit(0)
def packet_received(packet):
sam... | import signal
import sys
import serial
import sms
from xbee import XBee
SERIAL_PORT = '/dev/usbserial-143'
MOBILE_NUM = '0400000000'
NOTIFICATION_MSG = 'Cock-a-doodle-doo! An egg is waiting for you!'
egg_was_present = False
def signal_handler(signal, frame):
xbee.halt()
serial_port.close()
sys.exit(0)
d... | Use correct IO pins and serial port | Use correct IO pins and serial port
| Python | mit | jamespettigrew/eggsclaim |
e45f82ad8f11385ba7776beeb7fee497b9f4761a | observatory/dashboard/templatetags/javascript.py | observatory/dashboard/templatetags/javascript.py | # Copyright (c) 2010, Nate Stedman <natesm@gmail.com>
#
# 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 SOFTWARE IS PROVIDED "AS IS" AND THE AUT... | # Copyright (c) 2010, Nate Stedman <natesm@gmail.com>
#
# 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 SOFTWARE IS PROVIDED "AS IS" AND THE AUT... | Remove old lightbox starting stuff that never got done | Remove old lightbox starting stuff that never got done | Python | isc | natestedman/Observatory,rcos/Observatory,rcos/Observatory,natestedman/Observatory,rcos/Observatory,natestedman/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory |
1ca76f55adaa4ffe305f732df47f1a070449d549 | rpmvenv/extensions/loader.py | rpmvenv/extensions/loader.py | """Tools for loading and validating extensions."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import pkg_resources
import semver
class MissingDependency(Exception):
"""No dependency found."""
class Inval... | """Tools for loading and validating extensions."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import pkg_resources
import semver
class MissingDependency(Exception):
"""No dependency found."""
class Inval... | Fix indeterminate ordering issue for extensions | Fix indeterminate ordering issue for extensions
The original code used set() to dedupe enabled extensions. This resulted
in an arbitrary ordering of the values. The expected result was a
deterministic ordering of loaded extensions that matches the order given
by the whitelist. This removes the set() usage to preserve ... | Python | mit | kevinconway/rpmvenv |
2917c8d380bfee3c7589f806ea12f2e3f83e8b93 | npc/character/__init__.py | npc/character/__init__.py | from .character import *
| """
Module for all character objects.
"""
from .character import Character
from .changeling import Changeling
from .werewolf import Werewolf
def build(attributes: dict = None, other_char: Character = None):
"""
Build a new character object with the appropriate class
This derives the correct character cla... | Add helpers to find the right character class | Add helpers to find the right character class
| Python | mit | aurule/npc,aurule/npc |
6d5ce6164c4406be66b787c84de64f6919a6246d | changes/jobs/sync_build.py | changes/jobs/sync_build.py | from flask import current_app
from changes.config import queue
from changes.backends.jenkins.builder import JenkinsBuilder
from changes.constants import Status
from changes.models.build import Build
@queue.job
def sync_build(build_id):
try:
build = Build.query.get(build_id)
if build.status == Sta... | from flask import current_app
from changes.config import queue, db
from changes.backends.jenkins.builder import JenkinsBuilder
from changes.constants import Status
from changes.models.build import Build
@queue.job
def sync_build(build_id):
try:
build = Build.query.get(build_id)
if build.status ==... | Correct base_url usage, and force commit | Correct base_url usage, and force commit
| Python | apache-2.0 | dropbox/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes |
be9daefbdd80380a7fdb8369bf32208ef61a6615 | spacy/tests/test_download.py | spacy/tests/test_download.py | # coding: utf-8
from __future__ import unicode_literals
from ..cli.download import download, get_compatibility, get_version, check_error_depr
import pytest
def test_download_fetch_compatibility():
compatibility = get_compatibility()
assert type(compatibility) == dict
@pytest.mark.slow
@pytest.mark.parametr... | # coding: utf-8
from __future__ import unicode_literals
from ..cli.download import download, get_compatibility, get_version, check_error_depr
import pytest
def test_download_fetch_compatibility():
compatibility = get_compatibility()
assert type(compatibility) == dict
@pytest.mark.parametrize('model', ['en_... | Remove actual model downloading from tests | Remove actual model downloading from tests
| Python | mit | oroszgy/spaCy.hu,raphael0202/spaCy,raphael0202/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,honnibal/spaCy,aikramer2/spaCy,explosion/spaCy,oroszgy/spaCy.hu,oroszgy/spaCy.hu,spacy-io/spaCy,raphael0202/spaCy,Gregory-Howard/spaCy,explosion/spaCy,explosion/spaCy,oroszgy/spaCy.hu,recognai/spaCy,Gregory-Howard/spaCy,spacy-io/spaCy... |
08f4c3a2360f6c5fe0048f6d1a6f0eab536f8aa9 | joku/cogs/_common.py | joku/cogs/_common.py | from collections import OrderedDict
import threading
import aiohttp
from joku.bot import Jokusoramame
class _CogMeta(type):
def __prepare__(*args, **kwargs):
# Use an OrderedDict for the class body.
return OrderedDict()
class Cog(metaclass=_CogMeta):
def __init__(self, bot: Jokusoramame):... | from collections import OrderedDict
import threading
import aiohttp
import random
from joku.bot import Jokusoramame
class _CogMeta(type):
def __prepare__(*args, **kwargs):
# Use an OrderedDict for the class body.
return OrderedDict()
class Cog(metaclass=_CogMeta):
def __init__(self, bot: ... | Add an RNG to each cog. | Add an RNG to each cog.
| Python | mit | MJB47/Jokusoramame,MJB47/Jokusoramame,MJB47/Jokusoramame |
96fe288cbd4c4399c83b4c3d56da6e427aaad0f9 | spicedham/digitdestroyer.py | spicedham/digitdestroyer.py | from spicedham.basewrapper import BaseWrapper
class DigitDestroyer(BaseWrapper):
def train(*args):
pass
def classify(self, response):
if all(map(unicode.isdigit, response)):
return 1
else:
return 0.5
| from spicedham.basewrapper import BaseWrapper
class DigitDestroyer(object):
def train(*args):
pass
def classify(self, response):
if all(map(unicode.isdigit, response)):
return 1
else:
return None
| Fix inheritence error and return value | Fix inheritence error and return value
It shouldn't inherit from BaseWrapper, but merely object.
It should return None instead of 0.5 so it will have no effect on the average.
| Python | mpl-2.0 | mozilla/spicedham,mozilla/spicedham |
cc0c43c3131161902de3a8a68688766cacd637b9 | lowercasing_test/src/tests/lowercasing/fetchletters.py | lowercasing_test/src/tests/lowercasing/fetchletters.py | #! /usr/bin/env python
# Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
# This program reads a Unicode database and emits all letters in lower
# and upper case.
# Refer to http://www.unicode.org/ucd/ to download new files.
import sys
def add_chara... | #!/usr/bin/env python3
# Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
# This program reads a Unicode database and emits all letters in lower
# and upper case.
# Refer to http://www.unicode.org/ucd/ to download new files.
import sys
def add_chara... | Migrate script ot Python 3 | Migrate script ot Python 3
| Python | apache-2.0 | vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa |
cc12a902b772e057141da72c5bffeb678bc37df6 | tvrenamr/tests/base.py | tvrenamr/tests/base.py | from os import mkdir
from os.path import abspath, dirname, exists, join
from shutil import rmtree
from tvrenamr.config import Config
from tvrenamr.main import TvRenamr
from tvrenamr.tests import mock_requests
# make pyflakes STFU
assert mock_requests
class BaseTest(object):
def setup(self):
# absolute pa... | from os import mkdir
from os.path import abspath, dirname, exists, join
from shutil import rmtree
from tvrenamr.config import Config
from tvrenamr.main import TvRenamr
from tvrenamr.tests import mock_requests
# make pyflakes STFU
assert mock_requests
class BaseTest(object):
def setup(self):
# absolute pa... | Set the rename directory to the test files directory | Set the rename directory to the test files directory
| Python | mit | ghickman/tvrenamr,wintersandroid/tvrenamr |
77d72fe0502c64294dbacdbf8defbb44ee21c088 | schools/admin.py | schools/admin.py | from django.contrib import admin
from .models import *
class SchoolBuildingPhotoInline(admin.TabularInline):
model = SchoolBuildingPhoto
@admin.register(SchoolBuilding)
class SchoolBuildingAdmin(admin.ModelAdmin):
fields = ('school', 'building', 'begin_year', 'end_year')
readonly_fields = fields
lis... | from django.contrib import admin
from .models import *
class SchoolBuildingPhotoInline(admin.TabularInline):
model = SchoolBuildingPhoto
@admin.register(SchoolBuilding)
class SchoolBuildingAdmin(admin.ModelAdmin):
fields = ('school', 'building', 'begin_year', 'end_year')
readonly_fields = fields
sea... | Add search based on school name | Add search based on school name
| Python | agpl-3.0 | City-of-Helsinki/kore,City-of-Helsinki/kore,Rikuoja/kore,Rikuoja/kore |
8b628ce91040736e1cb33a544871925608c70479 | penchy/jobs/dependency.py | penchy/jobs/dependency.py | """
This module provides the parts to model and resolve dependencies in the flow of
execution.
"""
class Edge(object):
"""
This class represents edges in the dependency graph.
"""
def __init__(self, source, sink=None, map=None):
"""
:param source: source of data
:param sink: s... | """
This module provides the parts to model and resolve dependencies in the flow of
execution.
"""
from penchy.util import topological_sort
class Edge(object):
"""
This class represents edges in the dependency graph.
"""
def __init__(self, source, sink=None, map=None):
"""
:param sou... | Add edgesort as a frontend to topological_sort. | Add edgesort as a frontend to topological_sort.
Signed-off-by: Michael Markert <5eb998b7ac86da375651a4cd767b88c9dad25896@googlemail.com>
| Python | mit | fhirschmann/penchy,fhirschmann/penchy |
c07b6d2abae4ccd1eacb846a947945ecd6e963af | photutils/utils/_round.py | photutils/utils/_round.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module provides tools to round numpy arrays.
"""
import numpy as np
def _py2intround(a):
"""
Round the input to the nearest integer.
If two integers are equally close, rounding is done away from 0.
"""
data = np.asanyarray(... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module provides tools to round numpy arrays.
"""
import numpy as np
def _py2intround(a):
"""
Round the input to the nearest integer.
If two integers are equally close, rounding is done away from 0.
"""
data = np.asanyarray(... | Replace deprecated np.asscalar(a) with a.item() | Replace deprecated np.asscalar(a) with a.item()
| Python | bsd-3-clause | larrybradley/photutils,astropy/photutils |
445bd6d2b5f68da6d51d9acb84b1e15e6b4af2d8 | k8s/models/common.py | k8s/models/common.py | #!/usr/bin/env python
# -*- coding: utf-8
from __future__ import absolute_import
import six
from ..base import Model
from ..fields import Field, ReadOnlyField, RequiredField
class ObjectMeta(Model):
name = RequiredField(six.text_type)
namespace = Field(six.text_type, "default")
resourceVersion = ReadOnl... | #!/usr/bin/env python
# -*- coding: utf-8
from __future__ import absolute_import
import six
from ..base import Model
from ..fields import Field, ReadOnlyField, RequiredField
class ObjectMeta(Model):
name = Field(six.text_type)
namespace = Field(six.text_type, "default")
resourceVersion = ReadOnlyField(s... | Add support for auto-generated names in metadata | Add support for auto-generated names in metadata
| Python | apache-2.0 | fiaas/k8s |
9bd2d607e52b50ae79ff51199118395e57cedfdc | custom/icds/tests/test_views.py | custom/icds/tests/test_views.py | from __future__ import absolute_import
from __future__ import unicode_literals
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse
class TestViews(TestCase):
@override_settings(CUSTOM_LANDING_TEMPLATE='icds/login.html')
def test_custom_login(self):
... | from __future__ import absolute_import
from __future__ import unicode_literals
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse
class TestViews(TestCase):
@override_settings(CUSTOM_LANDING_TEMPLATE='icds/login.html')
def test_custom_login_old_fo... | Add test for new custom landing format | Add test for new custom landing format
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
03a54ea1920a3716e9c8d326f5c4c408f45b7d08 | apps/api/urls.py | apps/api/urls.py | from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from rest_framework_jwt import views as jwt_views
from . import views
router = DefaultRouter()
router.register(r'quotes', views.QuoteViewSet)
router.register(r'authors', views.AuthorViewSet)
router.register(r'categories', views... | from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from rest_framework_jwt import views as jwt_views
from . import views
router = DefaultRouter()
router.register(r'quotes', views.QuoteViewSet)
router.register(r'authors', views.AuthorViewSet)
router.register(r'categories', views... | Add option to verify jwt token | Add option to verify jwt token
| Python | bsd-3-clause | lucifurtun/myquotes,lucifurtun/myquotes,lucifurtun/myquotes,lucifurtun/myquotes |
7626f955a799cf93bb66aaa9b79a33395e9871e6 | api/api_resource.py | api/api_resource.py | from falcon.util.uri import parse_query_string
import json
from api.actions import pos_tagging
class ApiResource(object):
def parse_request_data(self, raw_post_data):
encoded_raw_post_data = ""
try:
encoded_raw_post_data = str(raw_post_data, 'utf-8')
except UnicodeDecodeError:
... | from falcon.util.uri import parse_query_string
import json
from api.actions import pos_tagging
class ApiResource(object):
def parse_request_data(self, raw_post_data):
encoded_raw_post_data = ""
try:
encoded_raw_post_data = str(raw_post_data, 'utf-8')
except UnicodeDecodeError:
... | Revert "Return utf-8, not ascii." | Revert "Return utf-8, not ascii."
This reverts commit 86cbefc74471e4c991c96e0385b931a2a20f5d50.
Former-commit-id: 3246e0bfefb806bd2b4d3dda0cb77e91f3481971 | Python | mit | EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger |
ed0b33dc0866100c2bede3579711af761d5cb159 | plumeria/util/__init__.py | plumeria/util/__init__.py | MIME_TYPES = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
}
def to_mimetype(ext):
if ext.lower() in MIME_TYPES:
return MIME_TYPES[ext.lower()]
| MIME_TYPES = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.txt': 'text/plain',
}
def to_mimetype(ext):
if ext.lower() in MIME_TYPES:
return MIME_TYPES[ext.lower()]
else:
return "application/octet-stream"
| Fix mimetype detection to handle more types. | Fix mimetype detection to handle more types.
| Python | mit | sk89q/Plumeria,sk89q/Plumeria,sk89q/Plumeria |
ce8c79346d3c7978739ce2c0a05f89a48150fa2f | ratechecker/migrations/0002_remove_fee_loader.py | ratechecker/migrations/0002_remove_fee_loader.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals
from django.db import migrations, OperationalError, ProgrammingError
def fix_fee_product_index(apps, schema_editor):
try:
schema_editor.execute(
'DROP INDEX IF EXISTS idx_16977_pro... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals
from django.db import migrations, OperationalError, ProgrammingError
def fix_fee_product_index(apps, schema_editor):
table_name = 'cfpb.ratechecker_fee'
index_name = 'idx_16977_product_id'
try... | Remove IF EXISTS from fix_fee_product_index | Remove IF EXISTS from fix_fee_product_index
| Python | cc0-1.0 | cfpb/owning-a-home-api |
70daf4157cc8b039d726fd6482fa9bae1b3fee1e | modules/urlparser/__init__.py | modules/urlparser/__init__.py | from modules import *
import re
import urllib2
import traceback
try:
import simplejson as json
except ImportError:
import json
from unidecode import unidecode
from twitter import Twitter
from bitly import Bitly
from youtube import Youtube
class Urlparser(Module):
"""Checks incoming messages for possible... | from modules import *
import re
import urllib2
import traceback
try:
import simplejson as json
except ImportError:
import json
from unidecode import unidecode
from twitter import Twitter
from bitly import Bitly
from youtube import Youtube
class Urlparser(Module):
"""Checks incoming messages for possible... | Change encoding of URL parser | Change encoding of URL parser
| Python | mit | billyvg/piebot |
f59106c4c804b0d0bc04dec9ff28b1b9c4ff08e4 | GeneratePassword/generate_password_v3.py | GeneratePassword/generate_password_v3.py | import os, sys
import random
import re
try:
# Make Python2 work like Python3
input = raw_input
except NameError:
# On Python3; already using input
pass
def get_words_from_file(filepath):
"""Return the set of all words at least three letters
long from within a named file.
"""
with open(... | import os, sys
import random
import re
try:
# Make Python2 work like Python3
input = raw_input
except NameError:
# On Python3; already using input
pass
def get_words_from_file(filepath):
"""Return the set of all words at least three letters
long from within a named file.
"""
with open(... | Use a correct algorithm to determine the length of word to use | Use a correct algorithm to determine the length of word to use
| Python | apache-2.0 | OneScreenfulOfPython/screenfuls,OneScreenfulOfPython/screenfuls |
7264db6b160d27f5b9eeb5571acad254f427ab7e | skan/__init__.py | skan/__init__.py | from .csr import skeleton_to_csgraph, branch_statistics, summarise
__version__ = '0.8.0-dev'
__all__ = ['skeleton_to_csgraph',
'branch_statistics',
'summarise']
| from .csr import skeleton_to_csgraph, branch_statistics, summarise, Skeleton
__version__ = '0.8.0-dev'
__all__ = ['skeleton_to_csgraph',
'branch_statistics',
'summarise']
| Add Skeleton class to package namespace | Add Skeleton class to package namespace
| Python | bsd-3-clause | jni/skan |
4185a93dcb3e53b87280bfe0579d551c338c440f | datatableview/tests/testcase.py | datatableview/tests/testcase.py | # -*- encoding: utf-8 -*-
from django import get_version
from django.test import TestCase
from django.core.management import call_command
if get_version().split('.') >= ['1', '7']:
from django.test import override_settings
from django.apps import apps
initial_data_fixture = 'initial_data_modern'
clear... | # -*- encoding: utf-8 -*-
import django
from django.test import TestCase
from django.core.management import call_command
if django.VERSION >= (1, 7):
from django.test import override_settings
from django.apps import apps
initial_data_fixture = 'initial_data_modern'
clear_app_cache = apps.clear_cache
e... | Fix Django version check for 1.10 | Fix Django version check for 1.10
| Python | apache-2.0 | pivotal-energy-solutions/django-datatable-view,pivotal-energy-solutions/django-datatable-view,jangeador/django-datatable-view,jangeador/django-datatable-view,doganmeh/django-datatable-view,jangeador/django-datatable-view,doganmeh/django-datatable-view,doganmeh/django-datatable-view,pivotal-energy-solutions/django-datat... |
b5be0a7d48d51ef504f47711f53eb0d2f6238b70 | SessionManager.py | SessionManager.py | import sublime
import sublime_plugin
from datetime import datetime
from .modules import messages
from .modules import serialize
from .modules import settings
from .modules.session import Session
class SaveSession(sublime_plugin.ApplicationCommand):
def run(self):
settings.load()
... | import sublime
import sublime_plugin
from datetime import datetime
from .modules import messages
from .modules import serialize
from .modules import settings
from .modules.session import Session
def plugin_loaded():
settings.load()
class SaveSession(sublime_plugin.ApplicationCommand):
def ... | Load settings only on "plugin_loaded" | Load settings only on "plugin_loaded"
Since sublime caches settings internally and subsequent "load_settings"
calls don't refer to the disk, it doesn't make sense to load the settings
each time a command gets executed.
| Python | mit | Zeeker/sublime-SessionManager |
670827e34872b40635d567ff1f5a34f132719fa8 | app/flask_config.py | app/flask_config.py | """
Config parameters for the Flask app itself.
Nothing here is user-configurable; all config variables you can set yourself are in config.py.
Generally speaking, don't touch this file unless you know what you're doing.
"""
import config
import constants
# Flask-SQLAlchemy
SQLALCHEMY_DATABASE_URI = 'mysql://{databas... | """
Config parameters for the Flask app itself.
Nothing here is user-configurable; all config variables you can set yourself are in config.py.
Generally speaking, don't touch this file unless you know what you're doing.
"""
import config
import constants
# Flask-SQLAlchemy
SQLALCHEMY_DATABASE_URI = 'mysql://{databas... | Use more specific session cookie name | Use more specific session cookie name
| Python | mit | LINKIWI/modern-paste,LINKIWI/modern-paste,LINKIWI/modern-paste |
118523251af8861d20b92ce754b48e9911f100c7 | odsimport.py | odsimport.py | from odf.opendocument import load
from odf.table import Table, TableRow, TableCell
from odf.text import P
def import_ods(path):
doc = load(path)
db = {}
tables = doc.spreadsheet.getElementsByType(Table)
for table in tables:
db_table = []
db[table.getAttribute('name')] = db_table
... | from odf.opendocument import load
from odf.table import Table, TableRow, TableCell
from odf.namespaces import TABLENS
from odf.text import P
def import_ods(path):
doc = load(path)
db = {}
tables = doc.spreadsheet.getElementsByType(Table)
for table in tables:
db_table = []
db[table.ge... | Fix ods-import for column repeat | Fix ods-import for column repeat
| Python | bsd-2-clause | aholkner/PoliticalRPG,aholkner/PoliticalRPG |
52e5c8ebb74622d2cb2a378f98563cb615115a21 | uptick/tools.py | uptick/tools.py | # -*- coding: utf-8 -*-
import click
from .decorators import online
from .main import main, config
from .ui import print_table, print_tx
@main.group()
def tools():
""" Further tools
"""
pass
@tools.command()
@click.pass_context
@online
@click.argument("account")
def getcloudloginkey(ctx, account):
"... | # -*- coding: utf-8 -*-
import click
from .decorators import online
from .main import main, config
from .ui import print_table, print_tx
@main.group()
def tools():
""" Further tools
"""
pass
@tools.command()
@click.pass_context
@online
@click.argument("account")
def getcloudloginkey(ctx, account):
"... | Allow to manually generate brainkeys | Allow to manually generate brainkeys
| Python | mit | xeroc/uptick |
d335fce6cea07df872d8cd7d70c6c3fea348e521 | tests/__init__.py | tests/__init__.py | import os.path
import unittest
def get_tests():
start_dir = os.path.dirname(__file__)
return unittest.TestLoader().discover(start_dir, pattern="*.py")
| import os.path
import unittest
def get_tests():
return full_suite()
def full_suite():
from .resource import ResourceTestCase
from .serializer import ResourceTestCase as SerializerTestCase
from .utils import UtilsTestCase
resourcesuite = unittest.TestLoader().loadTestsFromTestCase(ResourceTestCas... | Update get_tests to be backwards compatible with Python 2.6, since the library is compatible it seems worth this extra effort to test against it. | Update get_tests to be backwards compatible with Python 2.6, since the library is compatible it seems worth this extra effort to test against it.
| Python | bsd-2-clause | jannon/slumber,IAlwaysBeCoding/More,zongxiao/slumber,infoxchange/slumber,futurice/slumber,IAlwaysBeCoding/slumber,samgiles/slumber,s-block/slumber,ministryofjustice/slumber |
25b84238204d3970c72d0ac133b0ff59ae4696bd | social/models.py | social/models.py | from django.db import models
# Create your models here.
class User(models.Model):
username = models.CharField(max_length=20)
display_name = models.CharField(max_length=30)
password = models.TextField()
join_date = models.DateField('date joined')
def __str__(self):
return self.display_name... | from django.contrib.auth.models import AbstractBaseUser
from django.db import models
# Create your models here.
class User(AbstractBaseUser):
username = models.CharField(max_length=20)
display_name = models.CharField(max_length=30)
join_date = models.DateField('date joined')
USERNAME_FIELD = 'usernam... | Implement User that extends Django's AbstractBaseUser. | Implement User that extends Django's AbstractBaseUser.
| Python | mit | eyohansa/temu,eyohansa/temu,eyohansa/temu |
fc85f8846c188992438c935b9ba1ff0394bbc866 | deployment/cfn/utils/constants.py | deployment/cfn/utils/constants.py | EC2_INSTANCE_TYPES = [
't2.micro',
't2.small',
't2.medium'
]
RDS_INSTANCE_TYPES = [
'db.t2.micro'
]
ELASTICACHE_INSTANCE_TYPES = [
'cache.m1.small'
]
ALLOW_ALL_CIDR = '0.0.0.0/0'
VPC_CIDR = '10.0.0.0/16'
GRAPHITE = 2003
GRAPHITE_WEB = 8080
HTTP = 80
HTTPS = 443
KIBANA = 5601
POSTGRESQL = 5432
RE... | EC2_INSTANCE_TYPES = [
't2.micro',
't2.small',
't2.medium',
't2.large'
]
RDS_INSTANCE_TYPES = [
'db.t2.micro',
'db.t2.small',
'db.t2.medium',
'db.t2.large'
]
ELASTICACHE_INSTANCE_TYPES = [
'cache.m1.small'
]
ALLOW_ALL_CIDR = '0.0.0.0/0'
VPC_CIDR = '10.0.0.0/16'
GRAPHITE = 2003
GR... | Increase options for EC2 and RDS instance types | Increase options for EC2 and RDS instance types
Adding small through large for both.
| Python | apache-2.0 | project-icp/bee-pollinator-app,WikiWatershed/model-my-watershed,kdeloach/model-my-watershed,lliss/model-my-watershed,project-icp/bee-pollinator-app,lliss/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,lliss/model-my-watershed,kdeloach/model-my-water... |
f70eec24ef936db6318464da27dc9c619da339d3 | scratch/asb/experiment_json_to_cbf_def.py | scratch/asb/experiment_json_to_cbf_def.py | from __future__ import division
# Script to convert the output from refine_quadrants to a header file
# Apply the header file to the cbfs with cxi.apply_metrology
# Note hardcoded distance of 105
from dials.util.command_line import Importer
from xfel.cftbx.detector.cspad_cbf_tbx import write_cspad_cbf, map_detector_t... | from __future__ import division
# Script to convert the output from refine_quadrants to a header file
# Note hardcoded distance of 100 isn't relevant for just a cbf header
from dials.util.options import OptionParser
from dials.util.options import flatten_experiments
from xfel.cftbx.detector.cspad_cbf_tbx import write... | Refactor for new OptionParser interface | Refactor for new OptionParser interface
| Python | bsd-3-clause | dials/dials,dials/dials,dials/dials,dials/dials,dials/dials |
ed9635ab7ca086bb79a48daae8a390887b7bf78f | datadict/datadict_utils.py | datadict/datadict_utils.py | import pandas as pd
def load_datadict(filepath, trim_index=True, trim_all=False):
df = pd.read_csv(filepath, index_col=0)
if trim_index:
df.index = df.index.to_series().str.strip()
if trim_all:
df = df.applymap(lambda x: x.strip() if type(x) is str else x)
return df
def insert_rows_at(... | import pandas as pd
def load_datadict(filepath, trim_index=True, trim_all=False):
df = pd.read_csv(filepath, index_col=0, dtype=object)
if trim_index:
df.index = df.index.to_series().str.strip()
if trim_all:
df = df.applymap(lambda x: x.strip() if type(x) is str else x)
return df
def i... | Read datadict file as-is, without type-guessing | Read datadict file as-is, without type-guessing
| Python | bsd-3-clause | sibis-platform/ncanda-datacore,sibis-platform/ncanda-datacore,sibis-platform/ncanda-data-integration,sibis-platform/ncanda-datacore,sibis-platform/ncanda-data-integration |
0f55195f4461c80e85d132026a70049b36b8cc0b | sub_numbers_lambda/handle.py | sub_numbers_lambda/handle.py | import json
import time
def lambda_handler(event,context):
number_1 = event['key1']
number_2 = event['key2']
return {"number" : abs(number_1 - number_2)} | import json
def lambda_handler(event, context):
number_1 = int(event['key1'])
number_2 = int(event['key2'])
return {"number" : abs(number_1 - number_2)}
| Add int() function for casting from string to integer | Add int() function for casting from string to integer
| Python | mit | OsamaJBR/teach-me-aws-stepfunctions |
2448e6ab81f8a2a0b320a07b42a3f8707ec918cb | chartflo/apps.py | chartflo/apps.py | from __future__ import unicode_literals
import importlib
from goerr import err
from django.apps import AppConfig
GENERATORS = {}
cf = None
def load_generator(modname, subgenerator=None):
try:
path = modname + ".chartflo"
if subgenerator is not None:
path = path + "." + subgenerator
... | from __future__ import unicode_literals
import importlib
from goerr import err
from django.apps import AppConfig
from chartflo.engine import ChartFlo
GENERATORS = {}
cf = ChartFlo()
def load_generator(modname, subgenerator=None):
try:
path = modname + ".chartflo"
if subgenerator is not None:
... | Fix in app initialization for generators | Fix in app initialization for generators
| Python | mit | synw/django-chartflo,synw/django-chartflo,synw/django-chartflo |
43bc1f2670b722d5fb1b0e34a0b098fd2f41bd77 | icekit/plugins/image/admin.py | icekit/plugins/image/admin.py | from django.contrib import admin
from icekit.utils.admin.mixins import ThumbnailAdminMixin
from . import models
class ImageAdmin(ThumbnailAdminMixin, admin.ModelAdmin):
list_display = ['description', 'title', 'thumbnail']
list_display_links = ['description', 'thumbnail']
filter_horizontal = ['categories... | from django.contrib import admin
from icekit.utils.admin.mixins import ThumbnailAdminMixin
from . import models
class ImageAdmin(ThumbnailAdminMixin, admin.ModelAdmin):
list_display = ['thumbnail', 'alt_text', 'title', ]
list_display_links = ['alt_text', 'thumbnail']
filter_horizontal = ['categories', ]... | Add search options for images, reorder field listing, use field names in list display rather than properties. | Add search options for images, reorder field listing, use field names in list display rather than properties.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit |
5f01b9da3cfa899037ac9f7c3262a08c074b5bf9 | bedrock/stories/urls.py | bedrock/stories/urls.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
from bedrock.mozorg.util import page
urlpatterns = (
page("", "stories/landing.html"),
page("art-of-engagemen... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
from bedrock.mozorg.util import page
from bedrock.redirects.util import redirect
urlpatterns = (
page("", "storie... | Add temporary redirect for stories URL | Add temporary redirect for stories URL
| Python | mpl-2.0 | mozilla/bedrock,mozilla/bedrock,alexgibson/bedrock,craigcook/bedrock,craigcook/bedrock,alexgibson/bedrock,craigcook/bedrock,alexgibson/bedrock,craigcook/bedrock,alexgibson/bedrock,mozilla/bedrock,mozilla/bedrock |
6cda221478d3f67bc10ed13eb57854b493f6dbe2 | integration-test/366-beaches.py | integration-test/366-beaches.py | # Baker beach, SF
# https://www.openstreetmap.org/way/195638009
assert_has_feature(
18, 41881, 101308, 'landuse',
{ 'kind': 'beach' })
| # Baker beach, SF
# https://www.openstreetmap.org/relation/6260732
assert_has_feature(
18, 41881, 101308, 'landuse',
{ 'kind': 'beach' })
| Update test - Baker beach was turned into a relation. | Update test - Baker beach was turned into a relation.
| Python | mit | mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource |
f1a6025fb7ba8e69ec52e868ec0f6fc7783aa688 | qipipe/helpers/xnat_config.py | qipipe/helpers/xnat_config.py | import os
__all__ = ['default_configuration']
def default_configuration():
"""
Returns the XNAT configuration file location determined as the first file
found in the following precedence order:
1. ``xnat.cfg`` in the home ``.xnat`` subdirectory
2. ``xnat.cfg`` in the home directory
... | import os
__all__ = ['default_configuration']
def default_configuration():
"""
Returns the XNAT configuration file location determined as the first file
found in the following precedence order:
1. The ``XNAT_CFG`` environment variable, if it is set.
1. ``xnat.cfg`` in the current workin... | Add XNAT_CFG env var to config list. | Add XNAT_CFG env var to config list.
| Python | bsd-2-clause | ohsu-qin/qipipe |
9921b6bd73c5256a3b65c2a5106717ce0fc8f0cf | djangorestframework/utils/breadcrumbs.py | djangorestframework/utils/breadcrumbs.py | from django.core.urlresolvers import resolve
def get_breadcrumbs(url):
"""Given a url returns a list of breadcrumbs, which are each a tuple of (name, url)."""
from djangorestframework.views import APIView
def breadcrumbs_recursive(url, breadcrumbs_list):
"""Add tuples of (name, url) to the bread... | from django.core.urlresolvers import resolve, get_script_prefix
def get_breadcrumbs(url):
"""Given a url returns a list of breadcrumbs, which are each a tuple of (name, url)."""
from djangorestframework.views import APIView
def breadcrumbs_recursive(url, breadcrumbs_list, prefix):
"""Add tuples ... | Use get_script_prefix to play nicely if not installed at the root. | Use get_script_prefix to play nicely if not installed at the root.
| Python | bsd-2-clause | rafaelcaricio/django-rest-framework,maryokhin/django-rest-framework,jtiai/django-rest-framework,cheif/django-rest-framework,vstoykov/django-rest-framework,wwj718/django-rest-framework,ebsaral/django-rest-framework,jpadilla/django-rest-framework,damycra/django-rest-framework,kezabelle/django-rest-framework,cyberj/django... |
d34311cf7bc4dd33e020913538b28a1f5727ed92 | kafka_influxdb/tests/encoder_test/test_echo_encoder.py | kafka_influxdb/tests/encoder_test/test_echo_encoder.py | import unittest
from kafka_influxdb.encoder import echo_encoder
class TestEchoEncoder(unittest.TestCase):
def setUp(self):
self.encoder = echo_encoder.Encoder()
self.messages = [
"yeaal",
["this", "is", "a", "list"],
{'hash': {'maps': 'rule'}},
42,
... | import unittest
from kafka_influxdb.encoder import echo_encoder
class TestEchoEncoder(unittest.TestCase):
def setUp(self):
self.encoder = echo_encoder.Encoder()
self.messages = [
"yeaal",
["this", "is", "a", "list"],
{'hash': {'maps': 'rule'}},
42,
... | Fix unit test for echo encoder | Fix unit test for echo encoder
| Python | apache-2.0 | mre/kafka-influxdb,mre/kafka-influxdb |
c2ae6fb563b1ecc20b11ec6d693bad8a7f9e8945 | scrapple/utils/exceptions.py | scrapple/utils/exceptions.py | """
scrapple.utils.exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~
Functions related to handling exceptions in the input arguments
"""
import re
def handle_exceptions(args):
"""
Validates the arguments passed through the CLI commands.
:param args: The arguments passed in the CLI, parsed by the docopt module
:return: None... | """
scrapple.utils.exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~
Functions related to handling exceptions in the input arguments
"""
import re
def handle_exceptions(args):
"""
Validates the arguments passed through the CLI commands.
:param args: The arguments passed in the CLI, parsed by the docopt module
:return: None... | Update exception handling for levels argument | Update exception handling for levels argument
| Python | mit | scrappleapp/scrapple,AlexMathew/scrapple,AlexMathew/scrapple,scrappleapp/scrapple,AlexMathew/scrapple |
0041b029cc9b55084c89a9875de5e85728b9083c | src/birding/spout.py | src/birding/spout.py | from __future__ import absolute_import, print_function
import datetime
import itertools
from streamparse.spout import Spout
class SimpleSimulationSpout(Spout):
urls = [
'http://www.parsely.com/',
'http://streamparse.readthedocs.org/',
'https://pypi.python.org/pypi/streamparse',
]
... | from __future__ import absolute_import, print_function
import datetime
import itertools
from streamparse.spout import Spout
class SimpleSimulationSpout(Spout):
terms = [
'real-time analytics',
'apache storm',
'pypi',
]
def initialize(self, stormconf, context):
self.term_... | Change simulation to search terms. | Change simulation to search terms.
| Python | apache-2.0 | Parsely/birding,Parsely/birding |
80650a2f32ce8e3de4c26f2bc3fce4bab34cb36f | test/__init__.py | test/__init__.py | # -*- coding: utf-8 -*-
import os
from betamax import Betamax
from betamax_serializers import pretty_json
URL = os.environ.get('CONTENT_SERVICE_URL', 'http://dockerdev:9000')
APIKEY = os.environ.get('CONTENT_SERVICE_APIKEY', '12341234')
Betamax.register_serializer(pretty_json.PrettyJSONSerializer)
with Betamax.conf... | # -*- coding: utf-8 -*-
import os
from betamax import Betamax
from betamax_serializers import pretty_json
URL = os.environ.get('CONTENT_SERVICE_URL', 'http://dockerdev:9000')
APIKEY = os.environ.get('CONTENT_SERVICE_APIKEY', '12341234')
if URL.endswith('/'):
URL = URL[:-1]
Betamax.register_serializer(pretty_js... | Normalize URL for test cases. | Normalize URL for test cases.
| Python | apache-2.0 | deconst/submitter,deconst/submitter |
36a915d5c116ac9c1067ba1cdd079d0c27054b7e | skimage/exposure/__init__.py | skimage/exposure/__init__.py | from .exposure import histogram, equalize, equalize_hist, \
rescale_intensity, cumulative_distribution
from ._adapthist import equalize_adapthist
| from .exposure import histogram, equalize, equalize_hist, \
rescale_intensity, cumulative_distribution
from ._adapthist import equalize_adapthist
__all__ = ['histogram',
'equalize',
'equalize_hist',
'equalize_adapthist',
'rescale_intensity',
... | Add __all__ to exposure package | Add __all__ to exposure package
| Python | bsd-3-clause | blink1073/scikit-image,SamHames/scikit-image,almarklein/scikit-image,jwiggins/scikit-image,vighneshbirodkar/scikit-image,warmspringwinds/scikit-image,keflavich/scikit-image,vighneshbirodkar/scikit-image,pratapvardhan/scikit-image,michaelaye/scikit-image,emon10005/scikit-image,ofgulban/scikit-image,chintak/scikit-image,... |
81e3425bc6b2b9b35071afd7c14322f0dd52b418 | oneanddone/tests/functional/tests/test_task_assignment.py | oneanddone/tests/functional/tests/test_task_assignment.py | # This Source Code Form is subjectfrom django import forms to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
from pages.home import HomePage
class TestAvailableTasks():
@pytest.mark.no... | # This Source Code Form is subjectfrom django import forms to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
from pages.home import HomePage
class TestAvailableTasks():
@pytest.mark.no... | Add positive test for search | Add positive test for search
| Python | mpl-2.0 | VarnaSuresh/oneanddone,VarnaSuresh/oneanddone,VarnaSuresh/oneanddone,VarnaSuresh/oneanddone |
62047d430b1eef61999599b4848237a31f28deae | testprodapp/testapp/admin.py | testprodapp/testapp/admin.py | from django.contrib import admin
from django.http import HttpResponseRedirect, Http404
from django.conf.urls import patterns
from django.conf.urls import url
from django.shortcuts import redirect
from .models import TestResult
from .prod_tests.entity_counting_test import test_entity_count_vs_length
class TestResult... | from django.contrib import admin
from django.http import HttpResponseRedirect, Http404
from django.conf.urls import url
from django.utils.decorators import method_decorator
from django.contrib.admin.views.decorators import staff_member_required
from .models import TestResult
from .prod_tests.entity_counting_test impo... | Make sure the trigger view is locked down | Make sure the trigger view is locked down
| Python | bsd-3-clause | grzes/djangae,potatolondon/djangae,grzes/djangae,potatolondon/djangae,grzes/djangae |
4ca4cfde2daceced65aa0dd4a7bf0226f23efc33 | byceps/config_defaults.py | byceps/config_defaults.py | """
byceps.config_defaults
~~~~~~~~~~~~~~~~~~~~~~
Default configuration values
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from datetime import timedelta
# database connection
SQLALCHEMY_ECHO = False
# Disable Flask-SQLAlchemy's tracking of object modifications.... | """
byceps.config_defaults
~~~~~~~~~~~~~~~~~~~~~~
Default configuration values
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from datetime import timedelta
from pathlib import Path
# database connection
SQLALCHEMY_ECHO = False
# Disable Flask-SQLAlchemy's tracking... | Add missing import of `Path` | Add missing import of `Path`
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps |
bde67aa0ad7aec9c281da65a59e8e8ab82b75918 | app/cogs/admin.py | app/cogs/admin.py | from discord.ext import commands
from discord.ext.commands import Bot
from discord.ext.commands import Context
import checks
class Admin:
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
@checks.is_owner()
async def my_id(self, ctx: Context):
"""Temporary ... | import logging
from discord import ClientException
from discord.ext import commands
from discord.ext.commands import Bot, Context
from discord.ext.commands import UserInputError
import checks
logger = logging.getLogger(__name__)
class Admin:
def __init__(self, bot: Bot):
self.bot = bot
@commands.g... | Add extension load/unload commands (owner only) | Add extension load/unload commands (owner only)
| Python | mit | andrewlin16/duckbot,andrewlin16/duckbot |
483ba69bca57899054270cb24c41b0d2c01e7ff0 | opentreemap/stormwater/models.py | opentreemap/stormwater/models.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.contrib.gis.db import models
from treemap.models import MapFeature
class PolygonalMapFeature(MapFeature):
area_field_name = 'polygon'
skip_detail_form = True
... | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.contrib.gis.db import models
from treemap.models import MapFeature
class PolygonalMapFeature(MapFeature):
area_field_name = 'polygon'
skip_detail_form = True
... | Add placeholder defaults for bioswale stewardship | Add placeholder defaults for bioswale stewardship
| Python | agpl-3.0 | clever-crow-consulting/otm-core,clever-crow-consulting/otm-core,recklessromeo/otm-core,maurizi/otm-core,recklessromeo/otm-core,RickMohr/otm-core,RickMohr/otm-core,RickMohr/otm-core,clever-crow-consulting/otm-core,clever-crow-consulting/otm-core,RickMohr/otm-core,recklessromeo/otm-core,maurizi/otm-core,maurizi/otm-core,... |
36b771ce3028200f57255633dbfa4f6b991e1674 | fuckit_commit.py | fuckit_commit.py | '''
This module will send SMS reminders periodically, using Twilio.
The aim is to encourage user to code, commit and push to GitHub everyday
'''
import requests
from twilio.rest import TwilioRestClient
def get_configuration():
'''
Set Twilio configuration
'''
pass
def get_twilio_client(config):
'... | '''
This module will send SMS reminders periodically, using Twilio.
The aim is to encourage user to code, commit and push to GitHub everyday
'''
import requests
from twilio.rest import TwilioRestClient
def send_sms():
'''
Send SMS reminder
'''
config = {'account_sid' : '', 'auth_token' : ''}
clien... | Add code to send sms | Add code to send sms
| Python | mit | ueg1990/fuckit_commit |
945d64464857581052e18d79e62a6fde8bdecb9b | fabfile.py | fabfile.py | import sys
from fabric.api import local, task
@task
def start_db():
if sys.platform.startswith('darwin'):
# Mac OSX
local('postgres -D /usr/local/var/postgres -s')
| import sys
from pathlib import Path
from fabric.api import local, task, lcd, env
from fabric.contrib.console import confirm
from fabric.utils import abort
src_p = Path(env.real_fabfile).parent / 'src'
@task
def start_db():
if sys.platform.startswith('darwin'):
# Mac OSX
local('postgres -D /usr/lo... | Add fab command to backup and destroy database | Add fab command to backup and destroy database
| Python | mit | ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai |
54f027ec79d9d819a23854dcd79d4f79848ff3ef | tokens/models.py | tokens/models.py | from django.db import models
# Create your models here.
| from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
class Token(models.Model):
public_name = models.CharField(max_length=200)
symbol = models.CharField(max_length=4)
decimals = models.IntergerField(
default=18,
validators=[MaxValueValidator(... | Create a dead simple Django model for storing token information | Create a dead simple Django model for storing token information
| Python | apache-2.0 | onyb/ethane,onyb/ethane,onyb/ethane,onyb/ethane |
65fff1f471b132b97f7a5ef556603e8c2f511503 | mail_optional_autofollow/__manifest__.py | mail_optional_autofollow/__manifest__.py | # Copyright 2016 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Mail optional autofollow",
"summary": """
Choose if you want to automatically add new recipients as followers
on mail.compose.message""",
"author": "ACSONE SA/NV... | # Copyright 2016 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Mail optional autofollow",
"summary": """
Choose if you want to automatically add new recipients as followers
on mail.compose.message""",
"author": "ACSONE SA/NV... | Apply pre-commit changes: Resolve conflicts | [IMP] Apply pre-commit changes: Resolve conflicts
| Python | agpl-3.0 | OCA/social,OCA/social,OCA/social |
c1b6357c4d6876caa081af0799ec6c7a189ad13f | fabfile.py | fabfile.py | from fabric.api import *
from fabric.contrib.console import confirm
appengine_dir='appengine-web/src'
goldquest_dir='src'
def update():
# update to latest code from repo
local('git pull')
def test():
local("nosetests -m 'Test|test_' -w %(path)s" % dict(path=goldquest_dir))
# jslint
# pychecker
... | from fabric.api import *
from fabric.contrib.console import confirm
cfg = dict(
appengine_dir='appengine-web/src',
goldquest_dir='src',
appengine_token='',
)
def update():
# update to latest code from repo
local('git pull')
def test():
local("nosetests -m 'Test|test_' -w %(goldquest_dir)s" %... | Add support for appengine update oauth2 token in deploy script. | NEW: Add support for appengine update oauth2 token in deploy script.
| Python | mit | ollej/GoldQuest,ollej/GoldQuest,ollej/GoldQuest,ollej/GoldQuest |
1eeb6061cfc945ea84485e10fcf39062270c8945 | hooks.py | hooks.py | #!/usr/bin/python
def get_secret_for_user(user, ipparam):
print "Looking up user %s with ipparam %s" % (user, ipparam)
return "user_secret"
def allowed_address_hook(ip):
return True
def chap_check_hook():
return True
def ip_up_notifier(ifname, ouraddr, hisaddr):
print "ip_up_notifier"
def ip_do... | #!/usr/bin/env python
def get_secret_for_user(user, ipparam):
print("Looking up user %s with ipparam %s" % (user, ipparam))
return "user_secret"
def allowed_address_hook(ip):
return True
def chap_check_hook():
return True
def ip_up_notifier(ifname, localip, remoteip):
print("ip_up_notifier")
de... | Fix print statements for Python 3 | Fix print statements for Python 3
Although I haven't tested Python 3 for this, all print statements have
been updated to use parenthesis. There are also some minor fixes to the
names of the ip-up hook arguments.
| Python | mit | metricube/pppd_pyhook,metricube/pppd_pyhook |
5495913d43606407c7fb646b2a0eb4b5d4b80ba1 | network/admin.py | network/admin.py | from django.contrib import admin
from .models.device import Device
from .models.interface import Interface
admin.site.register(Device)
admin.site.register(Interface)
| from django.contrib import admin
from .models.device import Device
from .models.interface import Interface
from members.settings import MAX_INTERFACE_PER_DEVICE
class InterfaceAdmin(admin.TabularInline):
model = Interface
max_num = MAX_INTERFACE_PER_DEVICE
display = ('interface', 'mac_address', 'descript... | Add search box, show devices list in table, show interfaces in device detail | Add search box, show devices list in table, show interfaces in device detail
| Python | mit | Atilla106/members.atilla.org,Atilla106/members.atilla.org,Atilla106/members.atilla.org,Atilla106/members.atilla.org,Atilla106/members.atilla.org |
6d928da6c3848c2fd9f34772033fb645767ae4c3 | dbaas/workflow/steps/util/resize/check_database_status.py | dbaas/workflow/steps/util/resize/check_database_status.py | # -*- coding: utf-8 -*-
import logging
from ...util.base import BaseStep
LOG = logging.getLogger(__name__)
class CheckDatabaseStatus(BaseStep):
def __unicode__(self):
return "Checking database status..."
def do(self, workflow_dict):
try:
if not 'database' in workflow_dict:
... | # -*- coding: utf-8 -*-
import logging
from ...util.base import BaseStep
LOG = logging.getLogger(__name__)
class CheckDatabaseStatus(BaseStep):
def __unicode__(self):
return "Checking database status..."
def do(self, workflow_dict):
try:
if 'database' not in workflow_dict:
... | Change check database status to return even when it is false | Change check database status to return even when it is false
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service |
d117d924a684e0ec651d9f91b5fa7fcdfceb8777 | server.py | server.py | #!/usr/bin/env python
import os
import sys
import requests
import re
from bot import RandomBot
SERVER_HOST = 'http://localhost:9000'
trainingState = requests.post(SERVER_HOST + '/api/training/alone').json()
state = trainingState
bot = RandomBot()
def move(url, direction):
r = requests.post(url, {'dir': directi... | #!/usr/bin/env python
import os
import sys
import requests
import re
from bot import RandomBot
SERVER_HOST = 'http://localhost:9000'
trainingState = requests.post(SERVER_HOST + '/api/training/alone').json()
state = trainingState
bot = RandomBot()
def move(url, direction):
r = requests.post(url, {'dir': directi... | Add some debug when playing | Add some debug when playing
| Python | apache-2.0 | miguel89/vinidium |
d66a6325d210b075ed9aed7b2446aaf079df7936 | blackbelt/tasks.py | blackbelt/tasks.py | import click
import os
plugin_folder = os.path.join(os.path.dirname(__file__), 'commands')
class BlackBelt(click.MultiCommand):
def list_commands(self, ctx):
rv = []
for filename in os.listdir(plugin_folder):
if filename.endswith('.py') and filename != '__init__.py':
... | import click
import os
plugin_folder = os.path.join(os.path.dirname(__file__), 'commands')
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
class BlackBelt(click.MultiCommand):
def list_commands(self, ctx):
rv = []
for filename in os.listdir(plugin_folder):
if filename.end... | Add alias -h to --help | Add alias -h to --help
| Python | mit | apiaryio/black-belt |
424588f4cdad2dd063b15895198611703b187bec | pynpact/tests/steps/conftest.py | pynpact/tests/steps/conftest.py | import pytest
import taskqueue
@pytest.fixture(scope="session")
def async_executor(request):
taskqueue.LISTEN_ADDRESS = ('127.0.1.1', 57129)
sm = taskqueue.get_ServerManager(make_server=True)
sm.start()
request.addfinalizer(sm.shutdown)
return sm.Server()
class NullExecutor(object):
"An exec... | import pytest
def taskqueue_executor():
import taskqueue
taskqueue.LISTEN_ADDRESS = ('127.0.1.1', 57129)
sm = taskqueue.get_ServerManager(make_server=True)
sm.start()
request.addfinalizer(sm.shutdown)
return sm.Server()
@pytest.fixture(scope="session")
def async_executor(request):
from p... | Make pynpact tests use GeventExecutor | Make pynpact tests use GeventExecutor
We've almost completely deprecated taskqueue at this point; lets test
the new pieces instead of th old.
| Python | bsd-3-clause | NProfileAnalysisComputationalTool/npact,NProfileAnalysisComputationalTool/npact,NProfileAnalysisComputationalTool/npact,NProfileAnalysisComputationalTool/npact,NProfileAnalysisComputationalTool/npact |
3cdff0baeb349bcf4761269cc289cf2722ecbe62 | rasp/base.py | rasp/base.py | import urllib
import urllib.error
import urllib.request
from rasp.constants import DEFAULT_USER_AGENT
from rasp.errors import EngineError
class Engine(object):
def get_page_source(self, url):
raise NotImplemented("get_page_source not implemented for {}"
.format(str(self.__cla... | import urllib
import urllib.error
import urllib.request
from rasp.constants import DEFAULT_USER_AGENT
from rasp.errors import EngineError
class Engine(object):
def get_page_source(self, url):
raise NotImplemented("get_page_source not implemented for {}"
.format(str(self.__cla... | Use more pythonic pattern for default attributes | Use more pythonic pattern for default attributes
| Python | bsd-3-clause | anidata/rasp |
097bbde9aabc09d6bca679663c0ece3e12802414 | utils/esicog.py | utils/esicog.py | import asyncio
import esipy
from discord.ext import commands
from requests.adapters import DEFAULT_POOLSIZE
from utils.log import get_logger
ESI_SWAGGER_JSON = 'https://esi.evetech.net/dev/swagger.json'
class EsiCog:
_esi_app_task: asyncio.Task = None
_semaphore = asyncio.Semaphore(DEFAULT_POOLSIZE)
d... | import asyncio
import esipy
from discord.ext import commands
from requests.adapters import DEFAULT_POOLSIZE
from utils.log import get_logger
ESI_SWAGGER_JSON = 'https://esi.evetech.net/dev/swagger.json'
class EsiCog:
_esi_app_task: asyncio.Task = None
_semaphore = asyncio.Semaphore(DEFAULT_POOLSIZE)
d... | Fix reference to class attribute | Fix reference to class attribute
| Python | mit | randomic/antinub-gregbot |
2d4a3b82d982017fe51e2dd23eca7f1d83ad115f | plugoo/assets.py | plugoo/assets.py | class Asset:
"""
This is an ooni-probe asset. It is a python
iterator object, allowing it to be efficiently looped.
To create your own custom asset your should subclass this
and override the next_asset method and the len method for
computing the length of the asset.
"""
def __init__(self... | class Asset:
"""
This is an ooni-probe asset. It is a python
iterator object, allowing it to be efficiently looped.
To create your own custom asset your should subclass this
and override the next_asset method and the len method for
computing the length of the asset.
"""
def __init__(self... | Add a method for line by line asset parsing | Add a method for line by line asset parsing
| Python | bsd-2-clause | Karthikeyan-kkk/ooni-probe,lordappsec/ooni-probe,lordappsec/ooni-probe,0xPoly/ooni-probe,kdmurray91/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-probe,juga0/ooni-probe,0xPoly/ooni-probe,kdmurray91/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,juga0/ooni-probe,kdmurray91/ooni-probe,hackerb... |
d51b7bf7766dc4d56158fcc7e072e27f275f57e8 | skyfield/__init__.py | skyfield/__init__.py | """Elegant astronomy for Python
Most users will use Skyfield by importing ``skyfield.api`` and using the
functions and classes there.
"""
__version_info__ = (0, 2)
__version__ = '%s.%s' % __version_info__
| """Elegant astronomy for Python
Most users will use Skyfield by importing ``skyfield.api`` and using the
functions and classes there.
"""
VERSION = (0, 2)
__version__ = '.'.join(map(str, VERSION))
| Rename silly __version_info__ symbol to VERSION | Rename silly __version_info__ symbol to VERSION
Django uses the name VERSION and it always seems good to rid ourselves
of another faux-dunder symbol that really means nothing to the Python
runtime and therefore should not enjoy the (in-?)dignity of a dunder.
| Python | mit | GuidoBR/python-skyfield,ozialien/python-skyfield,exoanalytic/python-skyfield,ozialien/python-skyfield,exoanalytic/python-skyfield,skyfielders/python-skyfield,GuidoBR/python-skyfield,skyfielders/python-skyfield |
1d924ad8d47260b90f71d7f805cdd1a6aa734c2c | conda_build/external.py | conda_build/external.py | from __future__ import absolute_import, division, print_function
import os
import sys
from os.path import isfile, join, expanduser
import conda.config as cc
from conda_build.config import config
def find_executable(executable):
if sys.platform == 'win32':
dir_paths = [join(config.build_prefix, 'Scripts')... | from __future__ import absolute_import, division, print_function
import os
import sys
from os.path import isfile, join, expanduser
import conda.config as cc
from conda_build.config import config
def find_executable(executable):
# dir_paths is referenced as a module-level variable
# in other code
global... | Fix error message when patch is missing. | Fix error message when patch is missing.
| Python | bsd-3-clause | shastings517/conda-build,dan-blanchard/conda-build,ilastik/conda-build,takluyver/conda-build,takluyver/conda-build,rmcgibbo/conda-build,ilastik/conda-build,frol/conda-build,sandhujasmine/conda-build,dan-blanchard/conda-build,dan-blanchard/conda-build,takluyver/conda-build,sandhujasmine/conda-build,sandhujasmine/conda-b... |
683a3727fc5363c2a2a53fabfde555207e8bab66 | brains/orders/models.py | brains/orders/models.py | from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Order(models.Model):
user = models.ForeignKey(User)
# Last updated timestamp, used for sorting
date = models.DateTimeField(auto_now_add=True, auto_now=True)
# When we will strike
striketime = m... | from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Order(models.Model):
user = models.ForeignKey(User)
# Last updated timestamp, used for sorting
date = models.DateTimeField(auto_now_add=True, auto_now=True)
# When we will strike
striketime = m... | Allow strike time to be blank. | Allow strike time to be blank.
| Python | bsd-3-clause | crisisking/udbraaains,crisisking/udbraaains,crisisking/udbraaains,crisisking/udbraaains |
88263748a1ec742e514b6f321002d06e6e79b36e | plim/adapters/babelplugin.py | plim/adapters/babelplugin.py | """gettext message extraction via Babel: http://babel.edgewall.org/"""
from mako.ext.babelplugin import extract as _extract_mako
from .. import lexer
from ..util import StringIO
def extract(fileobj, keywords, comment_tags, options):
"""Extract messages from Plim templates.
:param fileobj: the file-like obj... | """gettext message extraction via Babel: http://babel.edgewall.org/"""
from mako.ext.babelplugin import extract as _extract_mako
from .. import lexer
from ..util import StringIO, PY3K
def extract(fileobj, keywords, comment_tags, options):
"""Extract messages from Plim templates.
:param fileobj: the file-lik... | Fix Babel plugin in Python3 environment | Fix Babel plugin in Python3 environment
| Python | mit | kxxoling/Plim |
b730fc84e07994d0a12357b70a1e912d0a032832 | Lib/vanilla/test/testTools.py | Lib/vanilla/test/testTools.py | from AppKit import *
from PyObjCTools import AppHelper
class _VanillaMiniAppDelegate(NSObject):
def applicationShouldTerminateAfterLastWindowClosed_(self, notification):
return True
def executeVanillaTest(cls, **kwargs):
"""
Execute a Vanilla UI class in a mini application.
"""
app = NS... | from AppKit import *
from PyObjCTools import AppHelper
class _VanillaMiniAppDelegate(NSObject):
def applicationShouldTerminateAfterLastWindowClosed_(self, notification):
return True
def executeVanillaTest(cls, **kwargs):
"""
Execute a Vanilla UI class in a mini application.
"""
app = NS... | Add a menu to the test runner. | Add a menu to the test runner.
| Python | mit | typemytype/vanilla,typesupply/vanilla,moyogo/vanilla |
0dc45239dde56ec7f1406646de4749a5cf43303e | proj_name/app_name/models.py | proj_name/app_name/models.py | from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date_published')
class Admin:
pass
def __unicode__(self):
return "<Poll '%s'>" % self.question
class Tag(models.Model):
name = models.CharField(max_length=200)
class Choice... | from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date_published')
class Admin:
pass
def __unicode__(self):
return "<Poll '%s'>" % self.question
class Tag(models.Model):
name = models.CharField(max_length=200)
class Choice... | Add a test for django model inheritance of the foreign key kind. | Add a test for django model inheritance of the foreign key kind.
| Python | bsd-3-clause | g2p/tranquil |
16dda42316176f0ad9c747731764855792fe88d6 | lymph/utils/observables.py | lymph/utils/observables.py | # Taken from https://github.com/delivero/lymph-storage/blob/master/lymph/storage/observables.py
class Observable(object):
def __init__(self):
self.observers = {}
def notify_observers(self, action, *args, **kwargs):
for callback in self.observers.get(action, ()):
callback(*args, **kw... |
class Observable(object):
def __init__(self):
self.observers = {}
def notify_observers(self, action, *args, **kwargs):
kwargs.setdefault('action', action)
for callback in self.observers.get(action, ()):
callback(*args, **kwargs)
def observe(self, actions, callback):
... | Allow observing more than one action at once | Allow observing more than one action at once
| Python | apache-2.0 | lyudmildrx/lymph,mouadino/lymph,Drahflow/lymph,itakouna/lymph,vpikulik/lymph,deliveryhero/lymph,kstrempel/lymph,alazaro/lymph,lyudmildrx/lymph,itakouna/lymph,mamachanko/lymph,torte/lymph,mamachanko/lymph,lyudmildrx/lymph,alazaro/lymph,mouadino/lymph,mamachanko/lymph,mouadino/lymph,alazaro/lymph,itakouna/lymph,dushyant8... |
383480592964f5b1f9fd0bb31672464d94ee46e5 | test/integration/022_bigquery_test/test_bigquery_adapter_specific.py | test/integration/022_bigquery_test/test_bigquery_adapter_specific.py | """"Test adapter specific config options."""
from test.integration.base import DBTIntegrationTest, use_profile
import textwrap
import yaml
class TestBigqueryAdapterSpecific(DBTIntegrationTest):
@property
def schema(self):
return "bigquery_test_022"
@property
def models(self):
return ... | """"Test adapter specific config options."""
from test.integration.base import DBTIntegrationTest, use_profile
import textwrap
import yaml
class TestBigqueryAdapterSpecific(DBTIntegrationTest):
@property
def schema(self):
return "bigquery_test_022"
@property
def models(self):
return ... | Use injected sql from results | Use injected sql from results
| Python | apache-2.0 | analyst-collective/dbt,analyst-collective/dbt |
ab63a427361ef72f0e573654cf6100754b268616 | l10n_es_facturae/components/edi_output_l10n_es_facturae.py | l10n_es_facturae/components/edi_output_l10n_es_facturae.py | # Copyright 2020 Creu Blanca
# @author: Enric Tobella
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.addons.component.core import Component
class EdiOutputL10nEsFacturae(Component):
_name = "edi.output.generate.l10n_es_facturae"
_inherit = "edi.component.output.mixin"
_usage = ... | # Copyright 2020 Creu Blanca
# @author: Enric Tobella
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.addons.component.core import Component
class EdiOutputL10nEsFacturae(Component):
_name = "edi.output.generate.l10n_es_facturae"
_inherit = "edi.component.output.mixin"
_usage = ... | Fix components names using the new logic | [FIX] l10n_es_facturae: Fix components names using the new logic
| Python | agpl-3.0 | OCA/l10n-spain,OCA/l10n-spain,OCA/l10n-spain |
d09e2831d95a2bc045da75496c70337246e77d5f | BoxAndWhisker.py | BoxAndWhisker.py | from matplotlib import pyplot
from PlotInfo import *
class BoxAndWhisker(PlotInfo):
"""
Box and whisker plots
"""
def __init__(self):
super(BoxAndWhisker,self).__init__("boxplot")
self.width=None
self.color="black"
self.label = None
self.xSequence = []
def ... | from matplotlib import pyplot
from PlotInfo import *
from Marker import Marker
class BoxAndWhisker(PlotInfo):
"""
Box and whisker plots
"""
def __init__(self):
super(BoxAndWhisker,self).__init__("boxplot")
self.width=None
self.color="black"
self.label = None
sel... | Allow flier markers in box-and-whisker plots to be modified. | Allow flier markers in box-and-whisker plots to be modified.
| Python | bsd-3-clause | alexras/boomslang |
04d5fef36b778d2a2d1f217e85ed919e50c75c9a | es_enas/controllers/regularized_evolution_controller.py | es_enas/controllers/regularized_evolution_controller.py | # coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# 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 applicab... | # coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# 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 applicab... | Replace deprecated PyGlove symbols to new ones. | Replace deprecated PyGlove symbols to new ones.
PiperOrigin-RevId: 408683720
| Python | apache-2.0 | google-research/google-research,google-research/google-research,google-research/google-research,google-research/google-research,google-research/google-research,google-research/google-research,google-research/google-research,google-research/google-research,google-research/google-research,google-research/google-research,... |
abbae774903165f19d144905ad77553ec913c78d | saves.py | saves.py | import os
import json
from serializable import Serializable
class Saves: #Only partially implemembted- only works for PlayerCharacters
#Because we want the user to be able to play on whatever world they want with whatever character
#they want, characters have to be stored independently of everything else
#We nee... | import os
import json
from serializable import Serializable
class Saves: #Only partially implemembted- only works for PlayerCharacters
#Because we want the user to be able to play on whatever world they want with whatever character
#they want, characters have to be stored independently of everything else
#We nee... | Fix for non-existent character folder bug | Fix for non-existent character folder bug
| Python | mit | benjamincongdon/adept |
474eda82f332a645193c1806dbaf840b8d506a65 | sigma_core/serializers/cluster.py | sigma_core/serializers/cluster.py | from rest_framework import serializers
from sigma_core.models.cluster import Cluster
from sigma_core.serializers.group import GroupSerializer
class BasicClusterSerializer(serializers.ModelSerializer):
"""
Serialize Cluster model without memberships.
"""
class Meta:
model = Cluster
excl... | from rest_framework import serializers
from sigma_core.models.cluster import Cluster
from sigma_core.serializers.group import GroupSerializer
class BasicClusterSerializer(serializers.ModelSerializer):
"""
Serialize Cluster model without memberships.
"""
class Meta:
model = Cluster
excl... | Use only foreign keys in Cluster serialisation and add _id suffixes | Use only foreign keys in Cluster serialisation and add _id suffixes
| Python | agpl-3.0 | ProjetSigma/backend,ProjetSigma/backend |
9df2bae691e8613794be3713194db2420fc75385 | gapipy/resources/dossier/transport_dossier.py | gapipy/resources/dossier/transport_dossier.py | from __future__ import unicode_literals
from ..base import Resource
from .details import DossierDetail, DossierDetailsMixin
from .dossier_features import DossierFeature
class TransportDossier(Resource, DossierDetailsMixin):
_resource_name = 'transport_dossiers'
_as_is_fields = [
'id', 'href', 'featu... | from __future__ import unicode_literals
from ..base import Resource
from .details import DossierDetail, DossierDetailsMixin
from .dossier_features import DossierFeature
class TransportDossier(Resource, DossierDetailsMixin):
_resource_name = 'transport_dossiers'
_as_is_fields = [
'id', 'href', 'capac... | Remove features from as-is fields on TransportDossier | Remove features from as-is fields on TransportDossier
Reflected as a model_collection_field
| Python | mit | gadventures/gapipy |
94d7dc0a116ff089ac5943dd795c9f02bc040788 | waterbutler/providers/dropbox/settings.py | waterbutler/providers/dropbox/settings.py | try:
from waterbutler import settings
except ImportError:
settings = {}
config = settings.get('DROPBOX_PROVIDER_CONFIG', {})
BASE_URL = config.get('BASE_URL', 'https://api.dropboxapi.com/1/')
BASE_CONTENT_URL = config.get('BASE_CONTENT_URL', 'https://content.dropboxapi.com/1/')
| try:
from waterbutler import settings
except ImportError:
settings = {}
config = settings.get('DROPBOX_PROVIDER_CONFIG', {})
BASE_URL = config.get('BASE_URL', 'https://api.dropbox.com/1/')
BASE_CONTENT_URL = config.get('BASE_CONTENT_URL', 'https://api-content.dropbox.com/1/')
| Revert "Update drobox api urls h/t @felliott" | Revert "Update drobox api urls h/t @felliott"
This reverts commit 6d1612698c2e42ab60d521915f31ff08832e3745.
| Python | apache-2.0 | RCOSDP/waterbutler,CenterForOpenScience/waterbutler,felliott/waterbutler,Johnetordoff/waterbutler,rdhyee/waterbutler,TomBaxter/waterbutler |
b6db1edc503222d3e954168d12e2a17b9387fc5b | bddbot/dealer.py | bddbot/dealer.py | from os import mkdir, getcwd
from bank import split_bank
from errors import BotError
class Dealer(object):
def __init__(self):
self.__feature = ""
self.__scenarios = []
def assign(self):
try:
with open("features.bank", "rb") as bank_input:
(header, self.__fe... | from os.path import join
from os import mkdir, getcwd
from bank import split_bank
from errors import BotError
FEATURE_BANK_FILENAME = "features.bank"
FEATURES_DIRECTORY = "features"
OUTPUT_FEATURES_FILENAME = join(FEATURES_DIRECTORY, "all.feature")
class Dealer(object):
def __init__(self):
self.__feature ... | Replace magic strings with constants | Replace magic strings with constants
| Python | mit | nivbend/bdd_bot |
77541e5b3956d9e6b130810211fcae10de29eb85 | tests/integration/base.py | tests/integration/base.py | import righteous
from ConfigParser import SafeConfigParser
from ..compat import unittest
class RighteousIntegrationTestCase(unittest.TestCase):
def setUp(self):
config = SafeConfigParser()
config.read('righteous.config')
if not config.has_section('auth'):
raise Exception('Pleas... | import righteous
from ConfigParser import SafeConfigParser
from ..compat import unittest
class RighteousIntegrationTestCase(unittest.TestCase):
def setUp(self):
config = SafeConfigParser()
config.read('righteous.config')
if not config.has_section('auth'):
raise Exception('Pleas... | Make the integration test fail, so we can see the request / response | Make the integration test fail, so we can see the request / response
| Python | unlicense | michaeljoseph/righteous,michaeljoseph/righteous |
643e04ec09612d6f36dcd98dba44e00011674353 | fito/data_store/dict_ds.py | fito/data_store/dict_ds.py | from fito.data_store.base import BaseDataStore
class DictDataStore(BaseDataStore):
def __init__(self, *args, **kwargs):
super(DictDataStore, self).__init__(*args, **kwargs)
self.data = {}
def iteritems(self):
return self.data.iteritems()
def save(self, spec, object):
self... | from fito.data_store.base import BaseDataStore
class DictDataStore(BaseDataStore):
def __init__(self, *args, **kwargs):
super(DictDataStore, self).__init__(*args, **kwargs)
self.data = {}
def iteritems(self):
return self.data.iteritems()
def save(self, spec, object):
self... | Clean method for dict ds | Clean method for dict ds
| Python | mit | elsonidoq/fito |
4a8ac74a4d32379eb6a366308e238452b6ba53b0 | openstack_dashboard/dashboards/project/routers/forms.py | openstack_dashboard/dashboards/project/routers/forms.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012, Nachi Ueno, NTT MCL, Inc.
# All rights reserved.
"""
Views for managing Quantum Routers.
"""
import logging
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import forms
from horizon imp... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012, Nachi Ueno, NTT MCL, Inc.
# All rights reserved.
"""
Views for managing Quantum Routers.
"""
import logging
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import forms
from horizon imp... | Make 'Router created' message translatable | Make 'Router created' message translatable
Change-Id: If0e246157a72fd1cabdbbde77e0c057d9d611eaa
| Python | apache-2.0 | nvoron23/avos,henaras/horizon,tellesnobrega/horizon,CiscoSystems/avos,kaiweifan/horizon,eayunstack/horizon,Tesora/tesora-horizon,redhat-cip/horizon,redhat-openstack/horizon,yeming233/horizon,idjaw/horizon,BiznetGIO/horizon,wolverineav/horizon,damien-dg/horizon,openstack/horizon,kaiweifan/horizon,coreycb/horizon,citrix-... |
e2d27eba4c751b63a3e25daef8f22d910fa47cdc | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(
name='wagtail_embed_videos',
version='0.0.5',
description='Embed Videos for Wagtail CMS.',
long_description=README,
author='Diogo Marques',
author_email='doriva.marques.29@gmail.com',
maintainer='Diogo Marques',
maintainer_e... | #!/usr/bin/env python
from distutils.core import setup
setup(
name='wagtail_embed_videos',
version='0.0.5',
description='Embed Videos for Wagtail CMS.',
long_description=(
'Simple app that works similar to wagtailimages,'
'but for embedding YouTube and Vimeo videos and music from Soun... | Fix NameError: name 'README' is not defined | Fix NameError: name 'README' is not defined
Traceback (most recent call last):
File "<string>", line 20, in <module>
File "/tmp/pip-g43cf6a2-build/setup.py", line 9, in <module>
long_description=README,
NameError: name 'README' is not defined | Python | bsd-3-clause | SalahAdDin/wagtail-embedvideos,SalahAdDin/wagtail-embedvideos,infoportugal/wagtail-embedvideos,SalahAdDin/wagtail-embedvideos,infoportugal/wagtail-embedvideos,infoportugal/wagtail-embedvideos |
e2462e51f760d0f22d52ae3c758c5a2bf34d4b63 | setup.py | setup.py | import os, sys
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
from distutils.core import setup
import wtforms
setup(
name='WTForms',
version=wtforms.__version__,
url='http://wtforms.simplecodes.com/',
license='BSD',
author='Thomas Johansson, James Crasta',
author_email='wtforms... | import os, sys
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
from distutils.core import setup
import wtforms
setup(
name='WTForms',
version=wtforms.__version__,
url='http://wtforms.simplecodes.com/',
license='BSD',
author='Thomas Johansson, James Crasta',
author_email='wtforms... | Make sure ext.csrf is installed with WTForms | Make sure ext.csrf is installed with WTForms
| Python | bsd-3-clause | pawl/wtforms,pawl/wtforms,wtforms/wtforms,subyraman/wtforms,crast/wtforms,skytreader/wtforms,Aaron1992/wtforms,jmagnusson/wtforms,hsum/wtforms,Xender/wtforms,cklein/wtforms,Aaron1992/wtforms |
d96adde7fbb561719aeb101df01e8809a5a06ea7 | src/model.py | src/model.py | from keras.models import Sequential
from keras.layers import Activation, TimeDistributed, Dense, RepeatVector, Embedding
from keras.layers.recurrent import LSTM
def get_model(X_vocab_len, X_max_len, y_vocab_len, y_max_len, hidden_size, num_layers):
model = Sequential()
# encoder
model.add(Embedding(X_voc... | from keras.models import Sequential
from keras.layers import Activation, TimeDistributed, Dense, RepeatVector, Embedding
from keras.layers.recurrent import LSTM
def get_model(X_vocab_len, X_max_len, y_vocab_len, y_max_len, hidden_size, num_layers):
model = Sequential()
# encoder
model.add(Embedding(X_voc... | Add one more lstm layer | Add one more lstm layer
| Python | mit | vdragan1993/python-coder |
e09fe37d78a94bcec284f65672a8892b73bb8a27 | watchman/management/commands/watchman.py | watchman/management/commands/watchman.py | from __future__ import absolute_import
import json
from django.core.management.base import BaseCommand, CommandError
from watchman.utils import get_checks
class Command(BaseCommand):
help = 'Runs the default django-watchman checks'
def handle(self, *args, **options):
verbosity = options['verbosity... | from __future__ import absolute_import
import json
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from watchman.utils import get_checks
class Command(BaseCommand):
help = 'Runs the default django-watchman checks'
option_list = BaseCommand.option_list + (... | Add check / skip ability to management command | 23: Add check / skip ability to management command
* `-c`, `--checks`, `-s`, `--skips` options take comma-separated list of python paths to run / skip
| Python | bsd-3-clause | blag/django-watchman,gerlachry/django-watchman,gerlachry/django-watchman,ulope/django-watchman,ulope/django-watchman,mwarkentin/django-watchman,blag/django-watchman,JBKahn/django-watchman,mwarkentin/django-watchman,JBKahn/django-watchman |
0c3529bd264d5512e31d828c65676baff6edefa6 | pinax/waitinglist/templatetags/pinax_waitinglist_tags.py | pinax/waitinglist/templatetags/pinax_waitinglist_tags.py | from django import template
from ..forms import WaitingListEntryForm
register = template.Library()
@register.assignment_tag
def waitinglist_entry_form():
"""
Get a (new) form object to post a new comment.
Syntax::
{% waitinglist_entry_form as [varname] %}
"""
return WaitingListEntryF... | from django import template
from ..forms import WaitingListEntryForm
register = template.Library()
@register.simple_tag(takes_context=True)
def waitinglist_entry_form(context):
"""
Get a (new) form object to post a new comment.
Syntax::
{% waitinglist_entry_form as [varname] %}
"""
i... | Update template tag to also take context | Update template tag to also take context
| Python | mit | pinax/pinax-waitinglist,pinax/pinax-waitinglist |
7698a548102fae9d801cf2a5cb94163d8e4a39f2 | kolla_mesos/tests/base.py | kolla_mesos/tests/base.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Make sure any config overrides are reset | Make sure any config overrides are reset
The new deploy unit tests have conf.set_override() but
don't reset these after each test, so depending on the
test order there are failures.
This just addes a generic cleanup in the base class to catch
all of them.
Change-Id: Idb1b4ef158808b08657f34bfe1546fa2ec0dae9f
| Python | apache-2.0 | asalkeld/kolla-mesos,openstack/kolla-mesos,openstack/kolla-mesos,openstack/kolla-mesos |
116d9565050ad69888cb38c302f8ae0d9232eec3 | gameserver/utils.py | gameserver/utils.py | import random as orig_random
from decorator import decorator
import binascii
import struct
import hashlib
from gameserver.database import db
db_session = db.session
random = orig_random.Random()
random.seed()
def node_to_dict(node):
connections = []
for edge in node.lower_edges:
connections.append(
... | import random as orig_random
from decorator import decorator
import binascii
import struct
import hashlib
from gameserver.database import db
db_session = db.session
random = orig_random.Random()
random.seed()
def node_to_dict(node):
connections = []
for edge in node.lower_edges:
connections.append(
... | Add in the active level to json output for the mobile game to use | Add in the active level to json output for the mobile game to use
| Python | apache-2.0 | hammertoe/didactic-spork,hammertoe/didactic-spork,hammertoe/didactic-spork,hammertoe/didactic-spork |
0fcf47c09402bd49866ace6ddbe584de40800534 | yahoo.py | yahoo.py | import time
from yahoo_finance import Share
# Collect 30 mins of Finance data on 5 companies, one value per minute
nyt = Share('NYT')
ibm = Share('IBM')
google = Share('GOOG')
facebook = Share('FB')
linkedin = Share('LNKD')
for minute in range(30):
print "%s minutes" % minute
nyt.refresh()
print "The New York Time... | import time
from yahoo_finance import Share
# Collect 30 mins of Finance data on 5 companies, one value per minute
for minute in range(30):
nyt = Share('NYT')
ibm = Share('IBM')
google = Share('GOOG')
facebook = Share('FB')
linkedin = Share('LNKD')
print "%s minutes" % minute
print "The New York Times' stock... | Remove need for refresh() by putting everything in loop | Remove need for refresh() by putting everything in loop
| Python | mit | cathyq/yahoo-finance |
ecd201216562c8b802fada27e2f79cda5b05a4d5 | cron/__init__.py | cron/__init__.py | import schedule
import settings
from .poll_pull_requests import poll_pull_requests as poll_pull_requests
from .restart_homepage import restart_homepage as restart_homepage
def schedule_jobs():
schedule.every(settings.PULL_REQUEST_POLLING_INTERVAL_SECONDS).seconds.do(poll_pull_requests)
schedule.every(settings... | import schedule
import settings
from .poll_pull_requests import poll_pull_requests as poll_pull_requests
from .restart_homepage import restart_homepage as restart_homepage
def schedule_jobs():
schedule.every(settings.PULL_REQUEST_POLLING_INTERVAL_SECONDS).seconds.do(poll_pull_requests)
schedule.every(settings... | Change hours to seconds in cron job | Change hours to seconds in cron job
| Python | mit | amoffat/Chaos,eukaryote31/chaos,phil-r/chaos,g19fanatic/chaos,phil-r/chaos,botchaos/Chaos,Chaosthebot/Chaos,mark-i-m/Chaos,chaosbot/Chaos,g19fanatic/chaos,phil-r/chaos,hongaar/chaos,rudehn/chaos,rudehn/chaos,Chaosthebot/Chaos,botchaos/Chaos,mpnordland/chaos,amoffat/Chaos,mark-i-m/Chaos,chaosbot/Chaos,amoffat/Chaos,amof... |
6270f9b926e741efb86940c9c670e23b397e45de | tests/grammar_atomic_tests.py | tests/grammar_atomic_tests.py | from unittest import TestCase
from pyparsing import ParseException
from regparser.grammar.atomic import *
class GrammarAtomicTests(TestCase):
def test_em_digit_p(self):
result = em_digit_p.parseString('(<E T="03">2</E>)')
self.assertEqual('2', result.p5)
def test_double_alpha(self):
... | from unittest import TestCase
from pyparsing import ParseException
from regparser.grammar.atomic import *
class GrammarAtomicTests(TestCase):
def test_em_digit_p(self):
result = em_digit_p.parseString('(<E T="03">2</E>)')
self.assertEqual('2', result.p5)
def test_double_alpha(self):
... | Refactor test to eliminate assertRaises() error with Python 2.6 | Refactor test to eliminate assertRaises() error with Python 2.6
| Python | cc0-1.0 | cmc333333/regulations-parser,eregs/regulations-parser,tadhg-ohiggins/regulations-parser,cmc333333/regulations-parser,eregs/regulations-parser,tadhg-ohiggins/regulations-parser |
5a6175f3d5a7d3bb709d55d317e19c804ad0634c | captura/views.py | captura/views.py | from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to rende... | from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
#@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to rend... | Correct the view of capturist dashboard | Correct the view of capturist dashboard
| Python | mit | erikiado/jp2_online,erikiado/jp2_online,erikiado/jp2_online |
a79801b4f67f3372231b1df2c73e52a7cc6b35a3 | perfiles_usuario/models.py | perfiles_usuario/models.py | from django.db import models
from django.conf import settings
from django.contrib.auth.models import Group
from .utils import CAPTURISTA_GROUP
class Capturista(models.Model):
""" Extension of Django's User Model for Capturistas.
We extend the Django User Model to identify Capturistas since they have relatio... | from django.db import models
from django.conf import settings
from django.contrib.auth.models import Group
from .utils import CAPTURISTA_GROUP
class Capturista(models.Model):
""" Extension of Django's User Model for Capturistas.
We extend the Django User Model to identify Capturistas since they have relatio... | Fix user documentation in Capturista. | Fix user documentation in Capturista.
| Python | mit | erikiado/jp2_online,erikiado/jp2_online,erikiado/jp2_online |
c8550f68977077347eba7331c882585e9bb945bf | cla_backend/apps/cla_eventlog/management/commands/find_and_delete_old_cases.py | cla_backend/apps/cla_eventlog/management/commands/find_and_delete_old_cases.py | from django.core.management.base import BaseCommand
from dateutil.relativedelta import relativedelta
from legalaid.models import Case
from cla_butler.tasks import DeleteOldData
class FindAndDeleteCasesUsingCreationTime(DeleteOldData):
def get_eligible_cases(self):
super(FindAndDeleteCasesUsingCreationTim... | from django.core.management.base import BaseCommand
from dateutil.relativedelta import relativedelta
from legalaid.models import Case
from cla_butler.tasks import DeleteOldData
class FindAndDeleteCasesUsingCreationTime(DeleteOldData):
def get_eligible_cases(self):
self._setup()
two_years = self.n... | Refactor command to find cases by default | Refactor command to find cases by default | Python | mit | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.